본문 바로가기

언어/C#

Image to Byte Array C#

출처: http://net-informations.com/q/faq/imgtobyte.html


The following program first convert an Image to ByteArray and then convert that byteArray to Image and loads in a picture box.

 
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //image to byteArray
            Image img = Image.FromFile("d:\\bank-copy.png");
            byte[] bArr = imgToByteArray(img);
            //byte[] bArr = imgToByteConverter(img);
            //Again convert byteArray to image and displayed in a picturebox
            Image img1 = byteArrayToImage(bArr);
            pictureBox1.Image = img1;
        }
        //convert image to bytearray
        public byte[] imgToByteArray(Image img)
        {
            using (MemoryStream mStream = new MemoryStream())
            {
                img.Save(mStream, img.RawFormat);
                return mStream.ToArray();
            }
        }
        //convert bytearray to image
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            using (MemoryStream mStream = new MemoryStream(byteArrayIn))
            {
                return Image.FromStream(mStream);
            }
        }
        //another easy way to convert image to bytearray
        public static byte[] imgToByteConverter(Image inImg)
        {
            ImageConverter imgCon = new ImageConverter();
            return (byte[])imgCon.ConvertTo(inImg, typeof(byte[]));
        }
    }
}

'언어 > C#' 카테고리의 다른 글

[JSON] Newtonsoft.Json 을 이용한 json 문자 파싱  (0) 2018.04.07
Newtonsoft.Json 사용법  (0) 2018.04.07
NLog.Windows.Forms  (0) 2018.03.22
Rich text box appender  (0) 2018.03.20
log4net TextBox Appender  (0) 2018.03.20