How to add a 'System.Drawing.Image' to a 'System.Web.UI.WebControls.Image'

23,400

Solution 1

You can't. WebControls.Image is just a HTML container for an image url - you can't store the image data directly in it, you just store the reference (url) to an image file.

If you need to retrieve image data dynamically, the usual approach is to create an image handler that will handle the request and return the image as a stream that the browser can display.

See this question

Solution 2

It looks like you just want a simple method to convert an image byte array into a picture. No problem. I found an article that helped me a lot.

    System.Web.UI.WebControls.Image image = (System.Web.UI.WebControls.Image)e.Item.FindControl("image");

    if (!String.IsNullOrEmpty(currentAd.PictureFileName))
    {
        image.ImageUrl = GetImage(currentAd.PictureFileContents);
    }
    else
    {
        image.Visible = false;
    }

    //The actual converting function
    public string GetImage(object img)
    {
        return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
    }

PictureFileContents is a Byte[] and that's what the function GetImage is taking as an object.

Share:
23,400
Eric Bergman
Author by

Eric Bergman

Updated on July 09, 2022

Comments

  • Eric Bergman
    Eric Bergman almost 2 years

    I have two functions:

    Function 1: ImageToByteArray: Is used to Convert an Image into a Byte Array and then Store in an Oracle Database, in a BLOB Field.

                public byte[] ImageToByteArray(string sPath)
                {
                    byte[] data = null;
                    FileInfo fInfo = new FileInfo(sPath);
                    long numBytes = fInfo.Length;
                    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fStream);
                    data = br.ReadBytes((int)numBytes);
                    return data;
                }
    

    Function 2: ByteArrayToImage: Is used to Convert a Byte Array from the Database into an Image:

               public System.Drawing.Image ByteArrayToImage(byte[] byteArray)
                {
                    MemoryStream img = new MemoryStream(byteArray);
                    System.Drawing.Image returnImage = System.Drawing.Image.FromStream(img);
                    return returnImage;
                }
    

    In my Markup I have an Imgage Control: <asp:Image ID="Image1" runat="server" />

    In the Code Behind I want to Assign the Returned Value from Function 2 to (which is of type System.Drawing.Image) to the "image1" control which is of type (System.Web.UI.WebControls.Image).

    Obviously I can't just assign: image1 = ByteArrayToImage(byteArray); because I'd get the following error: Cannot implicitly convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image'

    Is there anyway to do this?