检索图像从数据库和网页上显示

本文关键字:网页 显示 数据库 图像 检索 | 更新日期: 2023-09-27 18:03:23

我将面板保存为数据库中的图像,使用以下代码:

public Form2()
{
    InitializeComponent();
}
public static byte[] ImageToByte2(Bitmap img)
{
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();
        byteArray = stream.ToArray();
    }
    return byteArray;
}
private void button1_Click(object sender, EventArgs e)
{
    Form1 fom = new Form1();
    Bitmap bitmap = new Bitmap(fom.panel1.ClientSize.Width,
                          fom.panel1.ClientSize.Height);
    fom.panel1.DrawToBitmap(bitmap, fom.panel1.ClientRectangle);
    byte[] imgArray = ImageToByte2(bitmap);
    ImageData img = new ImageData
    {
        ClassName = textBox1.Text,
        Password = textBox2.Text,
        Image = imgArray,
    };
    using (BoardDatabaseEntities dc = new BoardDatabaseEntities())
    {
        dc.ImageDatas.Add(img);
        dc.SaveChanges();
        MessageBox.Show("Saved into database");      
    }
    this.Close();
}

我正在尝试从网页(视图控制)数据库显示图像,但还没有成功。互联网上有很多源代码,但他们都上传一个文件。代码为UploadedFile。我只是想不出如何使它(那些代码)适合我的情况。你能帮帮我吗?

检索图像从数据库和网页上显示

一般做法是使用某种处理程序从数据库中检索图像并将其提供给客户机。为了知道要检索什么图像,您需要主键。为了提供正确的MIME类型,您需要从数据库中提取该数据。

在项目中添加一个通用处理程序(.ashx)。

public class Handler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        string ImageId = context.Request.QueryString["Id"]; //you'll want to do defensive coding and make sure this query string variable exists

        byte[] ImageBytes = Database.GetImageBytes(ImageId); //I assume you know how to retrieve the byte array from the database?
        string MimeType = Database.GetMimeType(ImageId);
        context.Response.ContentType = MimeType;
        context.Response.BinaryWrite(ImageBytes);
    }
    public bool IsReusable { get { return false; } }
}

然后在页面上,您只需将URL放在图像源的处理程序中。

<asp:Image runat="server" ImageUrl="~/RetrieveImage.ashx?Id=505874" />

一种解决方案是将字节数组转换为base64编码的字符串,然后将其发送给视图。

将图像转换为data:image/png;base64用于网页显示