简体   繁体   English

在ASP.NET C#中显示图像

[英]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. 我正在将Base64代码转换为图像,并且正在使用以下方式保存和显示该图像。

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: 除了将Image1.ImageURL设置为图像的路径,您还可以执行以下操作之一:

  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. 直接使用与Base64编码数据img标签在里面- http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html并非所有的浏览器都支持这一点。
  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). 创建一个Action或Webform(取决于您是否使用ASP.NET MVC),将检索或生成Base64编码数据所需的任何内容作为输入,然后设置响应标头以提供正确的内容类型( image / png之类的图片),然后将图片直接写入Response.OutputStream(或在ASP.NET MVC中使用ContentResult)。 Tons of examples via Stackoverflow on how to do either. 通过Stackoverflow的大量示例说明了如何执行这些操作。

-M -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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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