如何在 C# 中将字节数组转换为图像?

How to convert a byte-array to a Image in C#?

我有一个 SQL 服务器数据库,我在其中存储 PNG。屏幕截图的值是十六进制 (0x085A3B...)。如何从 "Screenshot"(我自己的数据类型)转换为 "Image" 或类似 "BitmapImage" 的类型?

一开始,我截图如下:

private Screenshot LoadScreenshot()
{
    using (var context = new Context())
    {
        return context.Screenshots.FirstOrDefault();
    }
}

上面的方法returns我是一个像

这样的字节数组
byte[40864]

我无法执行以下操作,因为我遇到异常(我不知道是哪一个以及为什么):

public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit(); //the compiler breaks here
    return image;
}

我正在使用 C# 和 WPF

谢谢

编辑:

这是我的例外情况:

System.Runtime.Serialization.SafeSerializationManager No imaging component suitable to complete this operation was found

如何解决:

我需要添加这行代码:

Byte[] screenshotBytes = screenshot.Screenshot; //.Screenshot is a byte [] (I dont knwo why it didnt work before)

和@frebinfrancis 方法

试试这个:

public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
  var data = new byte[width * height * 4];

  int o = 0;

  for (var i = 0; i < width * height; i++)
  {
     var value = imageData[i];

     data[o++] = value;
     data[o++] = value;
     data[o++] = value;
     data[o++] = 0;
  }

  unsafe
  {
     fixed (byte* ptr = data)
     {
        using (Bitmap image = new Bitmap(width, height, width * 4,PixelFormat.Format32bppRgb, new IntPtr(ptr)))
        {
           image.Save(Path.ChangeExtension(fileName, ".bmp"));
        }
      }
   }
}

你的代码看起来不错,你的代码没有问题,当我做同样的事情时,一些图像对我有用,但有些不会't.after 搜索了很长时间,我发现了下面这个 link.

http://support.microsoft.com/kb/2771290

这是我的代码:

public BitmapImage ImageFromBuffer(Byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0) return null;
            var image = new BitmapImage();
            using (var mem = new MemoryStream(bytes))
            {
                mem.Position = 0;
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = null;
                image.StreamSource = mem;
                image.EndInit();
            }
            image.Freeze();
            return image;
        }