Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Convert file to WriteableBitmap

Posted on 2011-03-13
11
Medium Priority
?
1,033 Views
Last Modified: 2012-06-21
I have a folder full on images on my server, that I need to read, save as writeablebitmap (to shrink), then save back to a zip file.

The zip file part is taken care of, so I only need a method that converts each file to a writeablebitmap, and saves the image back to the same folder, tagged with '_shrunk'.

Here's what I have so far, I need to use the same file lookup to convert to writeablebitmap, with max width = 1920 and max height = 1080.

I can then rescan and save the '_Shrunk' appended files to the zip file.
public void SavetoZip()
        {
            string filename = string.Empty;
            string folder = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "FileStore"));
            string zipFolder=Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Zips"));
            
            
            foreach (string fileName in System.IO.Directory.GetFiles(folder))
            {


                
                string name = Path.GetFileName(fileName);
                
                
                if (File.Exists(zipFolder+"\\Images.zip"))
                {
                    using (ZipFile zip = ZipFile.Read(zipFolder+"\\Images.zip"))
                    {
                        // add this map file into the "images" directory in the zip archive
                        if (zip[name] == null)
                        {
                            zip.AddFile(fileName, "");


                            zip.Save();
                        }

                    }
                }
                else //Create file
                {
                    if (!System.IO.Directory.Exists(zipFolder))
                        System.IO.Directory.CreateDirectory(zipFolder);
                    using (ZipFile zip = new ZipFile())
                    {
                        if (zip[name] == null)
                        {
                            zip.AddFile(fileName,"");
                            zip.Save(zipFolder+"\\Images.zip");
                        }
                    }
                }
                File.Delete(fileName);
            }
        }

Open in new window

0
Comment
Question by:wint100
  • 5
  • 4
10 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123500
What are you using to zip the files?  Does it support streams?  If so, you might be able to read the bitmap, change the format, and add to the zip file, without having to write the bitmap to a file.
0
 
LVL 1

Author Comment

by:wint100
ID: 35123520
I'm using dotnetzip to zip up the files.

I've got the file, to a stream, then into a writeablebitmap with the correct sizing, so I would then need to convert from WB to stream to zip.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123533
I believe that you are looking for something like this:

WriteableBitmap  
http://www.i-programmer.info/programming/wpf-workings/527-writeablebitmap.html

Uri uri = new Uri(@"pack://application:,,,/Resources/mypic.jpg"); 
BitmapImage bmi = new BitmapImage(uri); 
WriteableBitmap bmi2 = new WriteableBitmap(bmi); 
image1.Source = bmi2;

Open in new window

0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
LVL 1

Author Comment

by:wint100
ID: 35123567
Well, I already have my WB, so just need to convert to a stream so I can save to zip.

I believe dotnetzip allows save from stream, so I just need to convert my WB to a stream.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 35123582
Ok, now we are getting down to "brass tacks"...

Here is a reference, so I don't have to repeat it:

http://stackoverflow.com/questions/3231873/silverlight-converting-writeablebitmap-to-stream

Ok, so Silverlight doesn't have anything built-in to turn a WriteableBitmap into an image stream.

After much wailing and gnashing of teeth, I found the excellent open source ImageTools library for Silverlight, which provides encoders and decoders for JPG, BMP, GIF, and PNG.

.NET Image Tools
http://imagetools.codeplex.com/
0
 
LVL 1

Author Comment

by:wint100
ID: 35123591
Yes I've seen this, trouble is i'm trying to do it server side, rather than in the SL client.

Should i rethink this? The files are uploaded to the server then saved to file. A method us then run on the server to manipulate the files then save to a zip.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123634
I believe that you could achieve what you need with the System.Drawing.Bitmap class, since it supports streams, but it may not support the other processing that you need...
0
 
LVL 1

Author Comment

by:wint100
ID: 35123643
Thanks, I'll give it a go.
0
 
LVL 1

Author Comment

by:wint100
ID: 35136156
OK, here is the method I used to achieve this. It seems to work very well, and operates server side, just before the save to zip. I end up with 2 Files, original and new, but I delete these as soon as the newFile is saved to ZIP.
private void ReSize(string OriginalFile, string NewFile, int Width, int Height)
        {

            Bitmap imgOutput=null;
            Image imgOriginal=null;
            try
            {

                const int intMaxWidth = 1920;
                //max width 
                const int intMaxHgt = 1080;
                //max height 
                int intNewWidth = 0;
                int intNewHgt = 0;
                // new width/height 
                float sglSize = 0;
                //temp variable used when calculating new size 
                imgOriginal = default(Image);
                //holds the original image 
                imgOriginal = Image.FromFile(OriginalFile);

                if ((imgOriginal.Width / intMaxWidth) > (imgOriginal.Height / intMaxHgt))
                {
                    sglSize = imgOriginal.Width;
                    intNewWidth = intMaxWidth;
                    intNewHgt = imgOriginal.Height * (intMaxWidth / (int)sglSize);
                    if (intNewHgt > intMaxHgt)
                    {
                        intNewWidth = intNewWidth * (intMaxHgt / intNewHgt);
                        intNewHgt = intMaxHgt;
                    }
                }
                else
                {
                    sglSize = imgOriginal.Height;
                    intNewHgt = intMaxHgt;
                    intNewWidth = imgOriginal.Width * (intMaxHgt / (int)sglSize);
                    if (intNewWidth > intMaxWidth)
                    {
                        intNewHgt = intNewHgt * (intMaxWidth / intNewWidth);
                        intNewWidth = intMaxWidth;
                    }
                }

                //Create a graphics object    
                imgOutput = new Bitmap(intNewWidth, intNewHgt);
                imgOutput = (Bitmap)imgOriginal.GetThumbnailImage(intNewWidth, intNewHgt, null, IntPtr.Zero);

                Graphics gr_dest = Graphics.FromImage(imgOutput);
                //Re-draw the image to the specified height and width 
                gr_dest.DrawImage(imgOriginal, 0, 0, imgOutput.Width, imgOutput.Height);
                //imgOriginal.Dispose();
                imgOutput.Save(NewFile, imgOriginal.RawFormat);

                //Dispose of Files
                imgOutput.Dispose();
                imgOriginal.Dispose();
            }
            catch (Exception ex)
            {
                string msg = "Resize Image after Upload Error: ";
                msg += ex.Message;
                emailData(msg, "ENERGYweb Error");
                string timestamp = DateTime.Now.ToString();
                new Logger.Logger().ErrorLog(timestamp + msg);

            }
            finally
            {
                //Make sure things have been cleaned up
                if (imgOriginal != null)
                {
                    imgOriginal.Dispose();
                    imgOriginal = null;
                }
                if (imgOutput != null)
                {
                    imgOutput.Dispose();
                    imgOutput = null;
                }
            }


        }

Open in new window

0
 
LVL 19

Expert Comment

by:Amandeep Singh Bhullar
ID: 35944490
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

783 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question