简体   繁体   中英

Bind Image to Image Control

I want to convert the image in the byte[] array and again convert the byte[] array into image and bind that image with the image control. Please check the below code:

 private void ShowImage()
        {

            var img = new System.Drawing.Bitmap(@"C:\Users\User\Desktop\Section-13.png");
            byte[] image = imageToByteArray(img);
            Image image1 = byteArrayToImage(image);
            Image2.ImageUrl = image1.ToString();
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {

            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

Image Control:

<asp:Image ID="Image2" runat="server" />

As you can see in my above code I am passing my image in Image2.ImageUrl by converted it into string. I know I am doing wrong. Please suggest if I am on the right track.

I goggle and find to bind the images in the GridView, but the above code is just for my knowledge my objective is just simply get the image. Thanks in advance.

The easiest solution would be to simply copy this Section-13.png inside the folder structure of your web application and then point the ImageUrl property to it:

Image2.ImageUrl = "~/images/Section-13.png";

If on the other hand you want to reference the image from some location outside of your web application then you have 2 possibilities:

  1. Write a generic handler which will stream the image to the response and then point the ImageUrl property to this generic handler:

     public class MyImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/png"; context.Response.WriteFile(@"C:\\Users\\User\\Desktop\\Section-13.png"); } public bool IsReusable { get { return true; } } } 

    and then:

     Image2.ImageUrl = "~/MyImageHandler.ashx"; 
  2. Embed the image using the Data URI scheme . In this case you could directly use the <img> HTML tag:

     <img src="data:image/png;base64,<%= Convert.ToBase64String(System.IO.File.ReadAllBytes(@"")) %>" alt="C:\\Users\\User\\Desktop\\Section-13.png" /> 

Create a http handler and pass handler to img src tag

 <img src="/imagehandler.ashx" />




 public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            byte[] buffer = imageToByteArray();
            context.Response.OutputStream.Write(buffer , 0, buffer .Length);
            context.Response.ContentType = "image/JPEG";
        }
    }

Try to Make Data URL Scheme

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

In Image control

<asp:image id="reddot" runat="server" ImageUrl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />

Commonly this method we used for image resizing and dynamic images

http://i-skool.co.uk/net/resize-and-optimise-image-class-in-c/

Image2.ImageUrl = "data:image/png;base64,"  + Convert.ToBase64String(imageToByteArray(image1))

Image to Byte Array

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}

I will also go for this Image Handler For handling this image. i used this sample code for retrieving the image in my webform with an .ashx handler

 Context.Session["emp"] = "anything u could pass your id or something";
 Image1.ImageUrl = "~/img.ashx";

i passed the id through Context.Session and called img.ashx--> my handler

Inside handler i did

 public class img : IHttpHandler,System.Web.SessionState.IReadOnlySessionState
    {
        Connection connect = new Connection();
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["emp"].ToString() != null)
            {
                try
                {
                    string text;
                    text =retrive your data from here by using  context.Session["emp"]
                    DataTable dt1 = connect.exexc(text, connect.connectfunction());
                    if (dt1.Rows.Count > 0)
                    {
                        string img = dt1.Rows[0].ItemArray[0].ToString();--> i retrived the byte array here
                        byte[] imageBytes = Convert.FromBase64String(img);
                        context.Response.ContentType = "image/JPEG";
                        context.Response.BinaryWrite(imageBytes);
                    }
                 }
                catch
                {

                }
            }
         }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM