简体   繁体   中英

How to set image from code behind?

I have the following aspx code

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

And my code behind c# code is

System.Drawing.Image image;
image = System.Drawing.Image.FromStream(new MemoryStream(dDSImageViewerDTO.ROI));
pbScannedImage.Visible = true;
pbScannedImage.ImageUrl = "";

// This is available but I don't want to write file to the disk and 
// assign directly to the image box something like 
pbScannedImage.Image = image;
//i know this is not possible so any other work around would be great help

So basically I want to assign the image to the image control without writing it to the anywhere else. Is it possible and if not then are there any workarounds for this available?

You can seperate your database image logic into a Generic Handler (ASHX) and then use the handler as your image's src eg

img.src=GetImage.ashx?id=1;

You'd need to create GetImage.ashx and handle your id's (or whatever your using) appropriately. Then you can do a simple write back to the page.

One way to do this, especially if you want to ensure images are never cached (which is common with dynamically loaded images) is to add the image data as CSS background-image data to an element such as a div with:

"background-image:url(data:image/gif;base64," + ImageToBase64String(Image) + ")"

    public string ImageToBase64String(Image image)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            image.Save(stream, ImageFormat.Png);
            return Convert.ToBase64String(stream.ToArray());
        }
    }
pbScannedImage.Src = "ImageHandler.ashx";

And the handler code must be like:

name

 System.Drawing.Image dbImage =
                 System.Drawing.Image.FromFile("file path");
            System.Drawing.Image thumbnailImage =
                 dbImage.GetThumbnailImage(80, 80, null, new System.IntPtr());
            thumbnailImage.Save(mstream, dbImage.RawFormat);
            Byte[] thumbnailByteArray = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(thumbnailByteArray, 0, Convert.ToInt32(mstream.Length));
            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(thumbnailByteArray);

解决了盖米的答案,您还可以像这样从后面的代码中分配img.Src。

pbScannedImage.Src = "data:image/png;base64," + ImageToBase64String(Image);

How said @Sain Pradeep, you can create service(ashx or contoller method if you use mvc) for return image stream and use that with html tag <img> (asp:Image is wrapper over <img> ). See samples from Display Image using ashx Handler

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