将位图图像转换为字节数组(Windows Phone 8) [英] Convert Bitmap Image to byte array (Windows phone 8)
本文介绍了将位图图像转换为字节数组(Windows Phone 8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Windows Phone开发人员的新手.我的小应用程序需要图像(照片库)中的字节数组.我尝试了多种方法进行转换,但效果不佳.
I am new to windows phone dev. My small app need a bytesarray from image (photo gallery). I tried many ways to convert, but it did not work fine.
这是我的代码:
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();
}
}
但是后来我将此字节数组保存到照相馆的图像中,我当时是黑色图像!
But then I saved this byte array to image in photogallery, I was be a black image!
public static void SavePicture2Library(byte[] bytes)
{
var library = new MediaLibrary();
var name = "image_special";
library.SavePicture(name, bytes);
}
有人可以帮助我吗? 请测试您的代码:(非常感谢!
Could anyone help me? Please test your code :( Thanks so much!
更新已解决!
var wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
data = stream.GetBuffer();
推荐答案
对于发现此问题的任何人,此方法都有效;
To anyone who finds this, this works;
图像到字节;
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();
}
}
字节为图像
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; }
}
这篇关于将位图图像转换为字节数组(Windows Phone 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文