Search code examples
c#pngarraysresourcemanager

How to get PNG as byte[] using ResourceManager with C#


I imported a PNG file into Visual Studio 2013. A MIME mail library we're using adds visuals to HTML mail with a function that expects a byte array parameter. How to get the object returned by ResourceManager into a byte array?

ResourceManager rm;
rm = new ResourceManager("Foo.Properties.Resources", typeof(MYFORM).Assembly);
var obj = rm.GetObject("Logo");

When I try to use the .GetStream method, error says the object is not a stream, and to use .GetObject instead.


Solution

  • The GetObject will return a System.Drawing.Image object if the file is an Image

    Image img = (Image)rm.GetObject("Logo")
    

    With the Image object you can directly save it to any System.IO.Stream object

    MemoryStream stream = new MemoryStream();
    img.Save(stream, ImageFormat.Png);
    

    Now you can make a copy of the bytes with the Stream.ToArray

    byte[] bytes = stream.ToArray();
    

    Or save it directly to a file

    img.Save(Application.StartupPath + "/testImage.jpg")
    

    Dont forget to close any used stream

    Stream.Close();