Friday, February 26, 2010

Tips to Convert Image to Array and Array to Image, C# .NET

I know my friend working on .NET development in a company. She wanted me to help her out in an occasion today. She actually wanted to convert a double array(double[]) into an image (Image) in C# .NET. I did googling on the this thing and I found something useful for my modifications.

You know I do also have little knowledge on .NET. I have Microsoft Visual Studio 2008 installed on my laptop which helped me to do this work. Unfortunately I could not finish this for converting exactly from double[] to Image. However it is useful for converting byte[] to Image.


Converting double[] to byte[], then using that will work for this C# code. I will try it out and let you know in the comments section. Here I share my search on this:








using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Namespaces to be added
using System.IO;
using System.Drawing.Imaging;

namespace doubletoimg
{
    public partial class frmMain : Form
    {
        public byte[] bImg; //byte array
        //public double dImg;
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            if (ofdImage.ShowDialog()==DialogResult.OK )
            {
                bImg = ImageToArray(Image.FromFile(ofdImage.FileName));
                //dImg = BitConverter.ToDouble(bImg,0);
                //bImg = BitConverter.GetBytes(dImg);
            }
            lblMsg.Text = "Converted to Array!";
        }
        public byte[] ImageToArray(Image imgIn)
        {
            //MemoryStream is a class in System.IO namespace
            MemoryStream ms = new MemoryStream();
            imgIn.Save(ms, ImageFormat.Jpeg);
            return ms.ToArray();
        }
        public Image ArrayToImage(byte[] bIn)
        {
            MemoryStream ms = new MemoryStream(bIn);
            return Image.FromStream(ms);
        }
       
        private void btnShow_Click(object sender, EventArgs e)
        {
            pbShow.Image = ArrayToImage(bImg);
        }
       
    }
}












Hope the Information is useful!

No comments:
Write comments