Solved

Convert file to WriteableBitmap

Posted on 2011-03-13
11
976 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 1

Author Comment

by:wint100
Comment Utility
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
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 1

Author Comment

by:wint100
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks, I'll give it a go.
0
 
LVL 1

Author Comment

by:wint100
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now