【发布时间】:2017-08-24 09:22:42
【问题描述】:
我需要将 BitmapImage 转换为 byte[],但我没有找到如何在 C# web.xml 中执行此操作。 我找到了示例,但它们都不起作用(JpegBitmapEncoder 不存在,BitmapImageObject.StreamSource 不存在,没有以 BitmapImage 作为参数的 WriteableBitmap 构造函数,Extensions.SaveJpeg(parameters) 不存在存在...)。
我找到的例子:
构造函数new WriteableBitmap(bitmapImage)不存在。
public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
byte[] data;
// Get an Image Stream
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
// reset the stream pointer to the beginning
ms.Seek(0, 0);
//read the stream into a byte array
data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
}
//data now holds the bytes of the image
return data;
}
new WriteableBitmap(img),System.Windows.Media.Imaging.Extensions.SaveJpeg 不存在。
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();
}
}
imageSource.StreamSource 不存在。
public static byte[] ImageToByte(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
JpegBitmapEncoder 不存在。
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
【问题讨论】:
-
看来您需要链接一些外部库。阅读相关内容,之后您也许可以解决此问题。
-
你能把你的代码分享到github吗?
标签: c# arrays bitmap bitmapimage