简体   繁体   中英

Displaying image in ASP.NET C#

I am converting Base64 code to image and I am using following way to save and display that image.

var kpin = Base64ToImage(TextBox1.Text);
kpin.Save(@"e:\myim.png");
Image1.ImageUrl = @"e:\myim.png";

and class is

public Image Base64ToImage(string base64String)
{
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0,
      imageBytes.Length);
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);
    return image;
}

and this process working fine but I need an image not to be saved in hard disk. How to display this image directly without saving to hard disk and retrieving back.

Instead of setting the Image1.ImageURL to the path of your image, you can instead do one of several things:

  1. Use an img tag with the Base64 data in it directly - http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html Not all browsers support this.
  2. Create an Action or Webform (depending on whether you're using ASP.NET MVC or not) that takes as input whatever you need to either retrieve or generate the Base64 encoded data, and then set the response headers to serve the correct content type (image/png or something) and write the image directly to the Response.OutputStream (or use ContentResult in ASP.NET MVC). Tons of examples via Stackoverflow on how to do either.

-M

Don't bother with the image object at all, and just do it direct:

public void Base64ToResponse(string base64String)
{
    Response.ContentType = "text/png"; //or whatever...
    byte[] imageBytes = Convert.FromBase64String(base64String);
    Response.OutputStream(imageBytes, 0, imageBytes.Length);
}

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