Delen via


How to convert image into byte[] and byte[] to image using C# in ASP.NET

Recently I worked on a code sample for converting the image to the byte array and convert it back to the image type in ASP.NET 2.0 application.

 

Here is the code sample:

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

public partial class Default2 : System.Web.UI.Page

{

    HttpPostedFile postedImage;

    private static byte[] byteImageData;

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    # region Converting Image to Byte

    private static byte[] ReadImage(string p_postedImageFileName, string[] p_fileType)

    {

        bool isValidFileType = false;

        try

        {

            FileInfo file = new FileInfo(p_postedImageFileName);

            foreach (string strExtensionType in p_fileType)

            {

                if (strExtensionType == file.Extension)

                {

                    isValidFileType = true;

                    break;

                }

            }

            if (isValidFileType)

            {

                FileStream fs = new FileStream(p_postedImageFileName, FileMode.Open, FileAccess.Read);

                BinaryReader br = new BinaryReader(fs);

                byte[] image = br.ReadBytes((int)fs.Length);

                br.Close();

                fs.Close();

                return image;

            }

            return null;

        }

        catch (Exception ex)

        {

            throw ex;

        }

    }

    #endregion

    #region Converting Byte to Image

    private void byteArrayToImage(byte[] byteArrayIn)

    {

        System.Drawing.Image newImage;

        string strFileName = GetTempFolderName() + "yourfilename.gif";

        if (byteArrayIn != null)

        {

            using (MemoryStream stream = new MemoryStream(byteArrayIn))

            {

                newImage = System.Drawing.Image.FromStream(stream);

                newImage.Save(strFileName);

                img.Attributes.Add("src", strFileName);

            }

    lblMessage.Text = "The image conversion was successful.";

        }

        else

        {

            Response.Write("No image data found!");

        }

    }

    #endregion

    #region Getting Temporary Folder Name

    private static string GetTempFolderName()

    {

        string strTempFolderName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\";

        if (Directory.Exists(strTempFolderName))

        {

            return strTempFolderName;

        }

        else

        {

            Directory.CreateDirectory(strTempFolderName);

            return strTempFolderName;

        }

    }

    #endregion

    protected void Button1_Click(object sender, EventArgs e)

    {

        postedImage = this.imgUpload.PostedFile;

        byteImageData = ReadImage(postedImage.FileName, new string[] { ".gif", ".jpg", ".bmp" });

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        byteArrayToImage(byteImageData);

    }

}

ImageConverter.zip

Comments

  • Anonymous
    January 18, 2008
    hi, I am also doing same application but i am not getting either GetTempFolderName() method or UIUtilities.GetTempFolderName().getting following error .The name 'GetTempFolderName' does not exist in the current context . pls give some advice very urgent 4 geting a job...

  • Anonymous
    January 18, 2008
    hi, I am also doing same application but i am not getting either GetTempFolderName() method or UIUtilities.GetTempFolderName().getting following error .The name 'GetTempFolderName' does not exist in the current context . pls give some advice very urgent 4 geting a job to linuak@gmail.com

  • Anonymous
    February 24, 2008
    pls give me the code on convert the picture in byte

  • Anonymous
    March 17, 2008
    I have uploaded the code sample used for the project which shows the conversion from image to byte and vice-versa. The temp folder is nothing but the location where the image files are being stored temporalily. In my machine the location is C:\Documents and Settings\vijay\Local Settings\Temporary Internet Files
    Hope this helps!

  • Anonymous
    July 02, 2008
    I am also doing same application but iam getting error with the function System.Drawing.Image.FromStream(stream); "The parameter is not valid"

  • Anonymous
    November 27, 2008
    I also had the "parameter is not valid" error... I'm just trying to use the code that creates the image from the memory stream.

  • Anonymous
    December 03, 2008
    Thank you.. This is very handy.

  • Anonymous
    February 15, 2009
    Hi, Is there any way in .Net 1.0 other than saving to physical files? FromStream is not supported for 1.0 Thanks, Priyaranjan

  • Anonymous
    June 16, 2009
    I am trying the code to convert image to byte[]. It's a good code

  • Anonymous
    September 09, 2009
    i am getting error when converting image to byte... Could not find file 'C:Program FilesMicrosoft Visual Studio 9.0Common7IDEarrow.GIF'.

  • Anonymous
    December 28, 2009
    hello, i am working with similar application in asp.net. here, i have stored images into sql data source with datatype image. it stores the image in binary format. now while retrieving image back from database, i have to get it in image tool on my web page. but the image can be set just by imageurl property. Now, the problem is- to give Image tool the url of a byte array. can you please help me.. thanks in advance...

  • Anonymous
    February 04, 2010
    I have a to take a screen shot of an web page without using any 3rd party control. Im able to convert to bytes through webclient. furthur im struct with the exception 'parameter not valid'. can i get any help on this. WebClient objWebClient = new WebClient(); string strURL = Request.Url.AbsoluteUri; byte[] bytes = objWebClient.DownloadData(strURL); System.Drawing.Image newImage; MemoryStream ms = new MemoryStream(bytes ); // getting error at this point. newImage = System.Drawing.Image.FromStream(stream); newImage.Save(strFileName); -- C#, ASP.NET thanks & regards.

  • Anonymous
    March 11, 2010
    i want to create a crystal report in vs 2008 the table which is connected through the report is having field barcode is of binary type containing image in binary format i want to change its type into image(jpg) in my crysta report what is the solution for that

  • Anonymous
    March 21, 2010
    The comment has been removed

  • Anonymous
    May 09, 2010
    i am also getting error when converting image to byte... Could not find file 'C:Program FilesMicrosoft Visual Studio 9.0Common7IDEarrow.GIF'. please help me to solve it...

  • Anonymous
    May 25, 2010
    @sadhana singh - please see my reply posted on 17 Mar 2008 9:43 AM .

  • Anonymous
    May 25, 2010
    @Aini - please see my reply posted on 17 Mar 2008 9:43 AM .

  • Anonymous
    August 24, 2010
    This was very useful and educational... Thank you

  • Anonymous
    September 08, 2010
    hi dear peps can this be don using c++ or java,i don't quite understand c# nor ASP.NET.i really need help in converting images to its bytes and vis-va sa.i can be reached via jesusebube@yahoo.com,jesusebube@hotmail.com.

  • Anonymous
    September 18, 2011
    Converting Images to Text using Office 2007

  • Anonymous
    September 18, 2011
    Converting Images to Text using Office 2007 using c#? pls help me pratbha.sharma9@gmail.com

  • Anonymous
    March 08, 2012
    Thanks For that nice code..i have used your concept on my Image Cropping utility. In my utility i dont want to store the image in any folder or physical path on my server. I am saving my images in byte array. Problem is that my solution runs successfully on my System(Windows 7 Professional) but when i host it on my local server (windows Server 2008 Enterprise) and try to run the solution the given Error occurs:     ....    <Data>NT AUTHORITYNETWORK SERVICE</Data>    <Data>FileNotFoundException</Data>    <Data>Could not find file 'c:windowssystem32inetsrvimagesCANK42RX.jpg'.</Data>     .....   I think there is any problem with getting the string strTempFolderName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @""; Please suggest any solution how get right path...if u need any other information please ask ...

  • Anonymous
    June 21, 2012
    I want show the binary image into repeater control in asp.net can anyone provide me the code for it...

  • Anonymous
    June 21, 2012
    Below is my code i dont knw how to show it repeater image control plz help me for next step of this code... SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);            con.Open();            SqlCommand cmd = new SqlCommand("select * from Products", con);            SqlDataAdapter da = new SqlDataAdapter(cmd);            DataSet ds = new DataSet();            da.Fill(ds);            if (ds.Tables[0].Columns.Count>0)            {                byte[] image = (byte[])ds.Tables[0].Rows[0]["Product_Image"];                MemoryStream ms=new MemoryStream(image);                System.Drawing.Image imgFromGB = System.Drawing.Image.FromStream(ms);

  • Anonymous
    November 19, 2012
    I am able to run to covert but image metadata information is lost. any idea so that we can retain metadata information.

  • Anonymous
    February 05, 2013
    Thanks Vijay this helped me to reach my goal.

  • Anonymous
    February 24, 2013
    @[267642143271329:0] @[311722825508110:0]

  • Anonymous
    November 12, 2013
    Throws error when i convert Image to Byte.. Could not find file 'C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0arrow.GIF'. ???

  • Anonymous
    November 23, 2013
    The variable img does not exist in current context. Nothing more annoying than a solution that is like 90% complete with a couple of errors. ) :

  • Anonymous
    July 15, 2014
    The comment has been removed

  • Anonymous
    April 22, 2015
    plz gave  solution with proper output. nd aspx page also

  • Anonymous
    May 21, 2015
    Thanks..... This is wonderful and simple to go.....

  • Anonymous
    November 03, 2015
    how to convert the image to binary value

  • Anonymous
    January 02, 2016
    Hi sir, I'd like to read an binary image file by specific width and height, say 640x480. but I'm new for C# so can you advise code for this, please?