3

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

我的查询如下。

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

我不知道如何检索二值图像 blueBallImage。

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

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

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

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;
4

3 回答 3

6

这是一个从数据库快速加载图像并在 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);
}
于 2013-09-25T09:23:20.893 回答
0

您需要创建一个 ASP.NET 处理程序 (*.ASHX) 来提供图像的字节

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

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

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";
    }
}

请参阅此以获取更多信息来自数据库的图像

于 2013-09-25T07:34:34.593 回答
0
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Connect();
    }

    try
    {
        cm = new SqlCommand("select profile_pic from TblNewMemberRegistration where    user_name='sudhanshu@mailbox.com'", 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();


}
于 2013-10-15T21:08:37.547 回答