Image.Save方法没有结果

时间:2015-06-24 10:15:25

标签: c# .net

我的目标是将base64字符串转换为图像并将其保存到磁盘。我有以下代码(主要来自this SO答案) -

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();
        }
    }
}

我在MS Visual Studio 2010 Ultimate(Windows 8.1 Pro x64)上运行它,没有错误,但我在C盘中找不到图像文件。我哪里出错了?

2 个答案:

答案 0 :(得分:1)

尝试以这种方式保存文件:

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

修改

无论如何,请将您的代码置于“尝试”之后,以便更好地了解文件未被保存的原因。

答案 1 :(得分:1)

尝试将LoadImage更新到此处以找出错误是什么,并在MessageBox上设置调试点以检查所发生情况的完整详细信息;

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);
        }
    }