如何在 ASP.NET 中使用 C# 从数据库中检索二进制图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18998763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:50:56  来源:igfitidea点击:

How to retrieve binary image from database using C# in ASP.NET

c#asp.netsql-serverimage

提问by Liu Jia Hui

I need to retrieve a binary image from the database.

我需要从数据库中检索二进制图像。

My queries are as below.

我的查询如下。

SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyGames;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select blueBallImage from CorrespondingBall WHERE objective = Default Ball", con);

I do not know how to retrieve blueBallImage which is a binary image.

我不知道如何检索 blueBallImage 这是一个二进制图像。

After I have retrieve it successfully, I need to add a text onto the image using a dropdownlist which contain the text. The codes are as below.

成功检索后,我需要使用包含文本的下拉列表将文本添加到图像上。代码如下。

Bitmap bmp = new Bitmap(@"C:\Users\apr13mpsip\Documents\Visual Studio 2012\WebSites\CorrespondingBallWebSite\Images\blueBallDefault.png");

For the time being, I do not know how to retrieve the image. Therefore, I hard coded it which I do not want. I want to retrieve it from database.

目前,我不知道如何检索图像。因此,我对其进行了硬编码,这是我不想要的。我想从数据库中检索它。

Graphics gra = Graphics.FromImage(bmp);

gra.DrawString(ddlCharacter.Text, new Font("Verdana", 18), Brushes.Black, new PointF(4, 6));

MemoryStream ms1 = new MemoryStream();
bmp.Save(ms1, ImageFormat.Png);
var base64Data = Convert.ToBase64String(ms1.ToArray());
imgImage.ImageUrl = "data:image/png;base64," + base64Data;

采纳答案by Mehdi Bugnard

Here is a basic sample to load an image from database quickly and load into a html image source in ASP. Please tell me if it works for you ;-)

这是一个快速从数据库加载图像并加载到 ASP 中的 html 图像源的基本示例。请告诉我它是否适合你;-)

//Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    // Get the byte array from image file
    byte[] imgBytes = (byte[]) row["logo"];

    // If you want convert to a bitmap file
    TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
    Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);

    string imgString = Convert.ToBase64String(imgBytes);
    //Set the source with data:image/bmp
    imgLogoCompany.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}

回答by Sain Pradeep

you need to made an ASP.NET handler (*.ASHX) that serves the bytes of the image

您需要制作一个 ASP.NET 处理程序 (*.ASHX) 来处理图像的字节

<img src="ImageHandler.ashx?id=<%=id%>" />

In image handler you need to code like this

在图像处理程序中,您需要像这样编码

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Load the image (see previous code sample)
        byte[] data = Convert.FromBase64String(encodedString);

        // Display the image
        context.Response.OutputStream.Write(data, 0, data.Length);
        context.Response.ContentType = "image/JPEG";
    }
}

please refer this for more info Image from Database

请参考此了解更多信息来自数据库的图像

回答by Sudhanshu Kumar

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Connect();
    }

    try
    {
        cm = new SqlCommand("select profile_pic from TblNewMemberRegistration where    user_name='[email protected]'", cn);
        byte[] b = (byte[])cm.ExecuteScalar();
        stream.Write(b, 0, b.Length);
        Bitmap bm = new Bitmap(stream);
        Response.ContentType = "image/gif";
        bm.Save(Response.OutputStream, ImageFormat.Gif);
    }
    catch(Exception ex) 
    {
        Response.Write(ex.Message);
    }
    finally
    {
        cn.Close();
        stream.Close();
    }
}
protected void Connect()
{
    cn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
    cn.Open();


}