Silverlight: image to byte[]

前端 未结 3 1470
遇见更好的自我
遇见更好的自我 2020-12-03 13:08

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

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

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


        
相关标签:
3条回答
  • 2020-12-03 13:14

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

    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;
    }
    
    0 讨论(0)
  • 2020-12-03 13:29

    There is no solution that works in Silverlight by design. Images can be retrieved without the need to conform to any cross domain access policy as other http requests have to. The basis of this relaxation of the cross domain rules is that the data making up the image cannot be be retrieved in the raw. It can only be used as an image.

    If you want to simply write to and read from a bitmap image use the WriteableBitmap class instead of BitmapImage. The WriteableBitmap exposes a Pixels property not available on the BitmapImage.

    0 讨论(0)
  • 2020-12-03 13:30
        public static void Save(this BitmapSource bitmapSource, Stream stream)
        {
            var writeableBitmap = new WriteableBitmap(bitmapSource);
    
            for (int i = 0; i < writeableBitmap.Pixels.Length; i++)
            {
                int pixel = writeableBitmap.Pixels[i];
    
                byte[] bytes = BitConverter.GetBytes(pixel);
                Array.Reverse(bytes);
    
                stream.Write(bytes, 0, bytes.Length);
            }
        }
    
        public static void Load(this BitmapSource bitmapSource, byte[] bytes)
        {
            using (var stream = new MemoryStream(bytes))
            {
                bitmapSource.SetSource(stream);
            }
        }
    
        public static void Load(this BitmapSource bitmapSource, Stream stream)
        {
            bitmapSource.SetSource(stream);
        }
    
    0 讨论(0)
提交回复
热议问题