0
我寫下面的代碼將圖像轉換爲字節數組並稍後轉換回來,但它不起作用。任何人都可以幫忙在windows8中bitmapimage和字節數組之間的轉換
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
byte[] pixeByte;
using (IRandomAccessStream stream = await file.OpenReadAsync())
{
WriteableBitmap image = new WriteableBitmap(400, 250);
image.SetSource(stream);
testImage.Source = image;
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
BitmapTransform transform = new BitmapTransform();
transform.ScaledWidth = 400;
transform.ScaledHeight = 250;
PixelDataProvider pixeldata =await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
pixeByte = pixeldata.DetachPixelData();
}
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
BitmapImage image = new BitmapImage();
await stream.WriteAsync(pixeByte.AsBuffer());
stream.FlushAsync().AsTask().Wait();
stream.Seek(0);
image.SetSource(stream);
testImage2.Source = image;
}
解決:
public static async Task<byte[]> ImageToByteArrayAsync(StorageFile file)
{
using (IRandomAccessStream stream = await file.OpenReadAsync())
{
using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
{
await reader.LoadAsync((uint)stream.Size);
byte[] pixeByte = new byte[stream.Size];
reader.ReadBytes(pixeByte);
return pixeByte;
}
}
}
// Convert a byte array to BitmapImage
public static async Task<BitmapImage> ByteArrayToImageAsync(byte[] pixeByte)
{
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
BitmapImage image = new BitmapImage();
await stream.WriteAsync(pixeByte.AsBuffer());
stream.Seek(0);
image.SetSource(stream);
return image;
}
}
你是什麼意思的「它不工作」? – jbkkd
testImage2不顯示圖像 – James
檢查這個答案http://stackoverflow.com/a/13778983/772608 – Suny