Asp.net(c#)将数据库中以二进制存的图片显示出来

这篇博客展示了如何在ASP.NET应用程序中,通过C#从数据库中检索以二进制形式存储的图片,并将其显示在网页上。在Page_Load事件中,连接到数据库并填充下拉列表,用户选择图片后,Button1_Click事件读取所选图片的二进制数据,转换为Bitmap对象,保存为本地文件并显示在Image控件上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlConnection con = new SqlConnection("server=(local);user id=sa;pwd=;database=库名");
            SqlDataAdapter ada = new SqlDataAdapter("select * from tb_17 ", con);
            con.Open();
            DataSet ds = new DataSet();
            ada.Fill(ds);
            DropDownList1.DataSource = ds;
            DropDownList1.DataTextField = "字段";
            DropDownList1.DataValueField = "字段";
            DropDownList1.DataBind();
            Image1.Visible=false;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Image1.Visible = true;
        SqlConnection con = new SqlConnection("server=(local);user id=sa;pwd=;database=库名");
        string imagename = "";
        try
        {
            con.Open();
            SqlCommand com = new SqlCommand("select name from 表名 where 字段="+DropDownList1.Text+"", con);
            SqlDataReader dr = com.ExecuteReader();
            dr.Read();
            MemoryStream ms = new MemoryStream((Byte[])dr["name"]);
            Bitmap image = new Bitmap(ms);
            string filepath = Server.MapPath("Files/");
            DirectoryInfo dir = new DirectoryInfo(filepath);
            FileInfo[] filecount = dir.GetFiles();
            int i = filecount.Length;
            imagename = filepath + ((i + 1) + ".jpg");
            image.Save(imagename);
            dr.Close();
            Image1.ImageUrl = "Files/" + ((i + 1) + ".jpg");
        }
        finally
        {
            con.Close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值