我需要在一個byte []中轉換一個BitmapImage,但我不知道如何在C#web中做到這一點。 我發現的例子,但沒有一個工作(JpegBitmapEncoder不存在,BitmapImageObject.StreamSource不存在,沒有帶BitmapImage作爲參數的WriteableBitmap構造函數,Extensions.SaveJpeg(參數)不存在... )。BitmapImage to byte [] - C#web
例子,我發現:
構造新的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;
}
新的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嗎? –