在 Windows 10 UAP 中将 BitmapImage 或 IRandomAccessStream 转换为字节数组
Convert BitmapImage or IRandomAccessStream to byte array in Windows 10 UAP
谁能帮帮我。我不明白如何将 BitmapImage 或 IRandomAccessStream 转换为字节数组。
我试试:
foreach (StorageFile file in files)
{
BitmapImage src = new BitmapImage();
using (IRandomAccessStream stream = await file.OpenReadAsync())
{
await src.SetSourceAsync(stream);
WriteableBitmap bitMap = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
await bitMap.SetSourceAsync(stream);
}
}
然后我有 WriteableBitmap 并试试这个:
private byte[] ImageToByeArray(WriteableBitmap wbm)
{
using (Stream stream = wbm.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
但这对我不起作用;(
我在我的 WPF 应用程序中使用此解决方案将数据库中的图像保存为 byte[]
。它也应该适用于您的情况。
public static byte[] ImageToString(System.Windows.Media.Imaging.BitmapImage img) {
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)img));
encoder.Save(stream);
stream.Flush();
return stream.ToArray();
}
应该这样做:
async Task<byte[]> Convert(IRandomAccessStream s)
{
var dr = new DataReader(s.GetInputStreamAt(0));
var bytes = new byte[s.Size];
await dr.LoadAsync((uint)s.Size);
dr.ReadBytes(bytes);
return bytes;
}
谁能帮帮我。我不明白如何将 BitmapImage 或 IRandomAccessStream 转换为字节数组。 我试试:
foreach (StorageFile file in files)
{
BitmapImage src = new BitmapImage();
using (IRandomAccessStream stream = await file.OpenReadAsync())
{
await src.SetSourceAsync(stream);
WriteableBitmap bitMap = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
await bitMap.SetSourceAsync(stream);
}
}
然后我有 WriteableBitmap 并试试这个:
private byte[] ImageToByeArray(WriteableBitmap wbm)
{
using (Stream stream = wbm.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
但这对我不起作用;(
我在我的 WPF 应用程序中使用此解决方案将数据库中的图像保存为 byte[]
。它也应该适用于您的情况。
public static byte[] ImageToString(System.Windows.Media.Imaging.BitmapImage img) {
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)img));
encoder.Save(stream);
stream.Flush();
return stream.ToArray();
}
应该这样做:
async Task<byte[]> Convert(IRandomAccessStream s)
{
var dr = new DataReader(s.GetInputStreamAt(0));
var bytes = new byte[s.Size];
await dr.LoadAsync((uint)s.Size);
dr.ReadBytes(bytes);
return bytes;
}