2013-02-18 47 views
2

我無法將圖像資源轉換爲字節[]。將資源轉換爲字節[]

例如,我有以下資源:

pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg 

在我的計劃。如何將其轉換爲字節[]。

我試過使用BitMapImage,但它的ImageSource最終在初始化後變爲null。

+0

你有沒有讀過[這個問題](http://stackoverflow.com/questions/1192054/load-image-from-resources-in-c-sharp)關於圖像資源? – Corey 2013-02-18 05:04:11

回答

4

這似乎工作:

var info = Application.GetResourceStream(uri); 
var memoryStream = new MemoryStream(); 
info.Stream.CopyTo(memoryStream); 
return memoryStream.ToArray(); 
0

的一般解爲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()); 
+0

使用特定的編碼器有沒有好處,而只是將圖像直接轉換爲字節[]? – GoalMaker 2013-02-18 20:50:49

+0

當你只有一個BitmapSource時,你不能「直接將圖像轉到一個字節[]」。只有當您已經擁有緩衝區時,纔會發生這種情況,例如作爲資源或圖像文件。正如你那樣,你的情況沒有任何好處。 – Clemens 2013-02-18 21:04:23