数据库读取图片展示
2011-09-28 09:19 Carl Xing 阅读(429) 评论(0) 编辑 收藏 举报将bitmap保存到页面的输出流中。在其它页面的img的src就可以使用这个流。
img.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Bitmap img = null;
string connStr = ConfigurationManager.ConnectionStrings["dbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sql = "SELECT IMG FROM MOVIE WHERE IMG IS NOT NULL";
SqlCommand cmd = new SqlCommand(sql, conn);
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
byte[] buffer = (byte[])obj;
MemoryStream mStream = new MemoryStream(buffer);
img = new Bitmap(mStream);
}
else
{
img = new Bitmap(Server.MapPath("img/android.jpg"));
}
}
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
<img alt="" src="img.aspx" />
上传图片到数据库(img字段为image格式):
protected void btnUpload_Click(object sender, EventArgs e)
{
int fileLeng = FileUpload1.PostedFile.ContentLength;
byte[] buffer = new byte[fileLeng];
Stream stream = FileUpload1.FileContent;
stream.Read(buffer, 0, fileLeng);
string connStr = ConfigurationManager.ConnectionStrings["dbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sql = "UPDATE Movie SET IMG=@img WHERE IMG IS NULL";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@img", SqlDbType.Image);
cmd.Parameters["@img"].Value = buffer;
cmd.ExecuteNonQuery();
}
}