Silverlight:图像到字节[] [英] Silverlight: image to byte[]

查看:29
本文介绍了Silverlight:图像到字节[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将字节 [] 转换为图像:

I'm able to convert a byte[] to an image:

byte[] myByteArray = ...;  // ByteArray to be converted

MemoryStream ms = new MemoryStream(my);
BitmapImage bi = new BitmapImage();
bi.SetSource(ms);

Image img = new Image();
img.Source = bi;

但我无法将图像转换回字节 []!我在网上找到了一个适用于 WPF 的解决方案:

But I'm not able to convert the Image back to a byte[]! I found in the Internet a solution, that works for WPF:

var bmp = img.Source as BitmapImage;
int height = bmp.PixelHeight;
int width  = bmp.PixelWidth;
int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8);

byte[] bits = new byte[height * stride];
bmp.CopyPixels(bits, stride, 0);

Silverlight 库非常小,以至于 BitmapImage 类没有名为 Format 的属性!

The Silverlight libary is so tiny that the class BitmapImage has no property called Format!

有没有人有解决我的问题的想法.

Has anybody an idea which solves my problem.

我在网上找了半天没有解决办法,在silverlight下是可行的!

I searched in the internet for a long time to find a solution, but there are is no solution, which works in silverlight!

谢谢!

推荐答案

(您缺少的每像素位数方法只是详细说明了如何按像素存储颜色信息)

(the bits per pixel method you are missing just details how the color information is stored per pixel)

正如安东尼所建议的,WriteableBitmap 将是最简单的方法 - 查看 http://kodierer.blogspot.com/2009/11/convert-encode-and-decode-silverlight.html 用于获取 argb 字节数组的方法:

As anthony suggested, a WriteableBitmap would be the easiest way - check out http://kodierer.blogspot.com/2009/11/convert-encode-and-decode-silverlight.html for a method to get an argb byte array out :

public static byte[] ToByteArray(this WriteableBitmap bmp)
{
   // Init buffer
   int w = bmp.PixelWidth;
   int h = bmp.PixelHeight;
   int[] p = bmp.Pixels;
   int len = p.Length;
   byte[] result = new byte[4 * w * h];

   // Copy pixels to buffer
   for (int i = 0, j = 0; i < len; i++, j += 4)
  {
      int color = p[i];
      result[j + 0] = (byte)(color >> 24); // A
      result[j + 1] = (byte)(color >> 16); // R
      result[j + 2] = (byte)(color >> 8);  // G
      result[j + 3] = (byte)(color);       // B
   }

    return result;
}

这篇关于Silverlight:图像到字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆