我無法將圖像資源轉換爲字節[]。將資源轉換爲字節[]
例如,我有以下資源:
pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg
在我的計劃。如何將其轉換爲字節[]。
我試過使用BitMapImage,但它的ImageSource最終在初始化後變爲null。
我無法將圖像資源轉換爲字節[]。將資源轉換爲字節[]
例如,我有以下資源:
pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg
在我的計劃。如何將其轉換爲字節[]。
我試過使用BitMapImage,但它的ImageSource最終在初始化後變爲null。
這似乎工作:
var info = Application.GetResourceStream(uri);
var memoryStream = new MemoryStream();
info.Stream.CopyTo(memoryStream);
return memoryStream.ToArray();
的一般解爲BitmapSource
轉換成byte[]
是這樣的:
public byte[] GetImageBuffer(BitmapSource bitmap, BitmapEncoder encoder)
{
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
你可以使用下面這樣想,任何的BitmapEncoder s在WPF中可用。
var uri = new Uri("pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg");
var bitmap = new BitmapImage(uri);
var buffer = GetImageBuffer(bitmap, new JpegBitmapEncoder());
你有沒有讀過[這個問題](http://stackoverflow.com/questions/1192054/load-image-from-resources-in-c-sharp)關於圖像資源? – Corey 2013-02-18 05:04:11