2014-03-07 142 views
1

我是windows phone開發新手。我的小應用程序需要從圖像(照片庫)的bytesarray。我嘗試了很多方法來轉換,但它不能正常工作。將位圖圖像轉換爲字節數組(Windows Phone 8)

這裏是我的代碼:

public static byte[] ConvertBitmapImageToByteArray(BitmapImage bitmapImage) 
    { 
     using (var ms = new MemoryStream()) 
     { 
      var btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight); 
      // write an image into the stream 
      btmMap.SaveJpeg(ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100); 
      return ms.ToArray(); 
     } 
    } 

但後來我在照相館保存此字節數組的形象,我是一個黑色的形象!

public static void SavePicture2Library(byte[] bytes) 
    { 
     var library = new MediaLibrary(); 
     var name = "image_special"; 
     library.SavePicture(name, bytes); 
    } 

任何人都可以幫助我嗎? ! 請測試你的代碼:(非常感謝


更新解決

var wBitmap = new WriteableBitmap(bitmapImage); 
      wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100); 
      stream.Seek(0, SeekOrigin.Begin); 
      data = stream.GetBuffer(); 

回答

3

爲了任何人誰發現這個,這個工作;

圖片爲字節;

public static byte[] ImageToBytes(BitmapImage img) 
     { 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       WriteableBitmap btmMap = new WriteableBitmap(img); 
       System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100); 
       img = null; 
       return ms.ToArray(); 
      } 
     } 

Bytes to Image

public static BitmapImage BytesToImage(byte[] bytes) 
     { 
      BitmapImage bitmapImage = new BitmapImage(); 
      try 
      { 
       using (MemoryStream ms = new MemoryStream(bytes)) 
       { 
        bitmapImage.SetSource(ms); 
        return bitmapImage; 
       } 
      } 
      finally { bitmapImage = null; } 
     } 
0

for windows phone 8

using System.IO;

public static class FileToByteArray 
{ 
    public static byte[] Convert(string pngBmpFileName) 
    { 
     System.IO.FileStream fileStream = File.OpenRead(pngBmpFileName); 

     using (MemoryStream memoryStream = new MemoryStream()) 
     { 
      fileStream.CopyTo(memoryStream); 
      return memoryStream.ToArray(); 
     } 
    } 
} 
byte[] PasPhoto = FileToByteArray.Convert("Images/NicePhoto.png") 
相關問題