nsane
nsane

Reputation: 1765

Image.Save method yields no result

My aim is to convert a base64 string into an image and save it to the disk. I have the following code (mostly from this SO answer) -

namespace ImageSaver
{
    using System;
    static class Program
    {
        public static void LoadImage()
        {
            //get a temp image from bytes, instead of loading from disk
            //data:image/gif;base64,
            //this image is a single pixel (black)
            byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

            Image image;
            Bitmap bimage;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                image = Image.FromStream(ms);
            }
                bimage = new Bitmap(image);
                bimage.Save("c:\\img.gif", System.Drawing.Imaging.ImageFormat.Gif);
        }
        static void Main(string[] args)
        {
            ImageSaver.Program.LoadImage();
        }
    }
}

I ran it on MS Visual Studio 2010 Ultimate (Windows 8.1 Pro x64), without errors, but I could not find the image file in C drive. Where did I go wrong?

Upvotes: 1

Views: 84

Answers (2)

Oliver Gray
Oliver Gray

Reputation: 874

Try updating LoadImage to this to find out what the error is, and set a debug point on the MessageBox to examine the full details of what's happening;

public static void LoadImage()
    {
        try
        {
            //get a temp image from bytes, instead of loading from disk
            //data:image/gif;base64,
            //this image is a single pixel (black)
            byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

            Image image;
            Bitmap bimage;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                image = Image.FromStream(ms);
            }
            bimage = new Bitmap(image);
            bimage.Save("c:\\img.gif", System.Drawing.Imaging.ImageFormat.Gif);

        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }

Upvotes: 1

Galma88
Galma88

Reputation: 2546

Try to save your file in this way:

File.WriteAllBytes(@"c:\img.gif", bytes);

EDIT

Anyway put your code under try'n'catch to better understand why you file is not being saved.

Upvotes: 1

Related Questions