Monday, July 30, 2012

Converting an Image into Byte Array and vice versa in C#

      

Putting a jpeg image into an Image Object (System.Drawing)

     Image m_imageIn= Image.FromFile("world.jpeg");

Converting any Image object into Byte Array:

       private byte[] ImageToByteArray(System.Drawing.Image m_imageIn)
        {
            MemoryStream oMemoryStream = new MemoryStream();
            
            // ImageFormat could be other formats like bmp,gif,icon,png etc.
            m_imageIn.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
            return oMemoryStream.ToArray();
        }

     
Converting back Byte Array into Image object:       
 
private Image ByteArrayToImage(byte[] m_byteArrayIn)
        {
            MemoryStream oMemoryStream = new MemoryStream(m_byteArrayIn);
            Image oImage = Image.FromStream(oMemoryStream);
            return oImage;
        }


2 comments: