Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Convert file to WriteableBitmap

Posted on 2011-03-13
11
Medium Priority
?
1,024 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Cloud Training Guides

FREE GUIDES: In-depth and hand-crafted Linux, AWS, OpenStack, DevOps, Azure, and Cloud training guides created by Linux Academy instructors and the community.

 
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
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…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

688 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