Silverlight Tips[2]: How to convert image to bytes

在Silverlight中, 任何一个UIElement都可以转换成writeablebitmap,但是如何把writeablebitmap转换成bytes呢?

View Code
 public static byte[] ToByteArray(this WriteableBitmap input)
        {
            int[] pixels = input.Pixels;
            int length = pixels.Length * 4;
            byte[] result = new byte[length];
            Buffer.BlockCopy(pixels, 0, result, 0, length);
            return result;
        }

注意:bytes里只有图像的基本像素信息,并不包含图像高度和宽度信息。

下面是根据bytes信息转换成Image。

View Code
  public static Image ConvertBytesToImage(this byte[] input, int pixelWidth, int pixelHeight)
        {
            WriteableBitmap bitmap = new WriteableBitmap(pixelWidth, pixelHeight);
            bitmap.FromByteArray(input);
            return new Image() { Source = bitmap, Stretch = Stretch.None };
        }

你可能感兴趣的:(silverlight)