繁体   English   中英

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

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

我有一个SQL Server数据库,我在其中存储PNG。 屏幕截图的值为十六进制(0x085A3B ...)。 如何将“屏幕截图”(我自己的数据类型)转换为“图像”或类似“BitmapImage”的类似内容?

首先,我获取这样的截图:

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

上面的方法返回一个字节数组

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找不到适合完成此操作的成像组件

怎么解决:

我需要添加这行代码:

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

和@frebinfrancis方法

你的代码看起来很好,你的代码没有问题,当我做同样的事情时,一些图像对我有用但有些不会。经过很长一段时间的搜索,我发现以下链接。

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

试试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM