Solved

Convert file to WriteableBitmap

Posted on 2011-03-13
11
982 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
 
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Two different visual studio versions 3 22
C# Json POSt to Rest API 4 36
C# Single Form 8 27
C# Comparing String Arrays. 5 0
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

911 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

23 Experts available now in Live!

Get 1:1 Help Now