Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bytes out of a PNG file using C#

Tags:

c#

xml

byte

png

How do I get bytes out of a PNG file using C#, (Reason for this:I need to pass the PNG as a string in an XML file.)

like image 411
Nevin Mathai Avatar asked Dec 16 '09 03:12

Nevin Mathai


2 Answers

System.IO.File.ReadAllBytes

System.Convert.ToBase64String

System.Convert.ToBase64String(System.IO.File.ReadAllBytes(filePath));
like image 100
ChaosPandion Avatar answered Oct 02 '22 23:10

ChaosPandion


Alternatively, if you have the PNG file in memory:

  • create a System.Drawing.Bitmap object out of it
  • Serialize it to a memory stream using Bitmap.Save() (pass in PNG as the encoding)
  • Use MemoryStream.GetBuffer() to retrieve the underlying byte array for the MS
  • Use Convert.ToBase64String(byte[], 0, memoryStream.Position) to convert it to a base64 string
like image 42
LorenVS Avatar answered Oct 03 '22 01:10

LorenVS