现在的位置: 首页 > 综合 > 正文

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

2013年10月13日 ⁄ 综合 ⁄ 共 1788字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.