Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

c# - How display any type of images in asp.net?

How to display images in different formats?

I tried this.

context.Response.ContentType = "image/jpeg";  

This will display only jpeg images.But I need to display images in different formats.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit : I understand from comments that your question is :

how to set the src of an ASP.Net image to be the base64 encoded data ? Or How display images that come from database in different format in an asp.net image?

Assuming that you get image bytes from database and you have an img tag

<img id= "img" runat= "server" />

You can create an extension method for byte[] like this

// Add a new csharp file to your project
// Add below code to it
public static class DrawingExtensions
{
    public static string ConvertToBase64ImageFormat ( this byte[] b, ImageFormats f)
    {
            // you can find other formats image mimeType and add all you need
           string mt = system.Net.Mime.MediaTypeNames.Image.Tiff;
           string i = Convert.ToBase64String(b);
           return string.Format("data:{0};base64,{1}",mt,i);
    }
}
public enum  ImageFormats
{
     Jpeg
     Png ,
     // And other formats
}

On your webform page use method like this

public partial class DisplayImagePage:Page
{
    public void ibDisplayImg_click(object sender,EventArgs e)
    {
        // read image bytes from database
        Byte[] i= ReadImageFromDatabase();
        img.Src = i.ConvertToBase64ImageFormat(  ImageFormats.Png);
    }
}

If you want mime type for other kind of images they available with

 System.Web.MimeMapping

And use like this

string mimeType = MimeMapping.GetMimeMapping(fileName);
context.Response.ContentType = mimeType;

More information :

https://msdn.microsoft.com/en-us/library/ms525208(v=vs.90).aspx

https://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...