Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert resource to byte[]

Tags:

c#

wpf

I am having trouble converting an image resource into byte[].

For example, I have the following resource:

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

in my program. How do I convert this into a byte[].

I've tried using a BitMapImage, but it's ImageSource ends up being null after initialised.

like image 850
GoalMaker Avatar asked Apr 16 '26 06:04

GoalMaker


2 Answers

This seems to work:

var info = Application.GetResourceStream(uri);
var memoryStream = new MemoryStream();
info.Stream.CopyTo(memoryStream);
return memoryStream.ToArray();
like image 70
GoalMaker Avatar answered Apr 18 '26 19:04

GoalMaker


A general solution to convert a BitmapSource into a byte[] would look like this:

public byte[] GetImageBuffer(BitmapSource bitmap, BitmapEncoder encoder)
{
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = new MemoryStream())
    {
        encoder.Save(stream);
        return stream.ToArray();
    }
}

You would use it like shown below, with any of the BitmapEncoders that are available in WPF.

var uri = new Uri("pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg");
var bitmap = new BitmapImage(uri);
var buffer = GetImageBuffer(bitmap, new JpegBitmapEncoder());
like image 41
Clemens Avatar answered Apr 18 '26 19:04

Clemens