Solved

Convert file to WriteableBitmap

Posted on 2011-03-13
11
992 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
11 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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 500 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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying 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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

808 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