.Net中將插入並顯示圖片
protected void InsertImageToSQL(string filepath)
{
try
{
Stream file;
file = File.OpenRead(filepath);
BinaryReader sr = new BinaryReader(file);
int n = (int)file.Length;
byte[] buf = new byte[n];
buf = sr.ReadBytes(n);
sr.Close();
SqlConnection connection = new SqlConnection(strconn);
string strSQL = "insert into Test_Img(img) values(@buf)";
SqlCommand command = new SqlCommand(strSQL,connection);
//buf=@buf;
SqlParameter paramData = new SqlParameter( "@buf", SqlDbType.Image );
paramData.Value = buf;
command.Parameters.Add( paramData );
connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
//connection.Close();
Console.Write("OK");
string sql="SELECT * FROM nn" ;
command.CommandText = sql;
command.Connection = connection;
SqlDataReader myDataReader = command.ExecuteReader();
if(myDataReader.Read() == true)
{
Stream file1;
file1 = File.OpenWrite(".\\jjd.jpg");
byte[] mydata=((byte[])myDataReader["body"]);
Console.Write(mydata.ToString());
BinaryWriter sw = new BinaryWriter(file1);
sw.Write(mydata);
sw.Close();
}
Console.ReadLine();
}
catch(System.Exception e)
{
Console.Write(e.Message);
}
}
將圖片顯示在GridView中
通过ashx动态获取数据库中的某条图片数据,然后在GridView等控件的自定义模版中安置一个Image控件,并设置Image控件的ImageUrl属性为类似 XXX.ashx?photoId=1 即可显示图片。
Data:
Test_img
(
Sid int,
img image
)
下面为Handler.ashx的代码:
![]()
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Configuration;public class Handler : IHttpHandler {
public bool IsReusable {
get {
return false;
}
}const string strconn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
public void ProcessRequest(HttpContext context)
{// Set up the response settings
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;Stream outstream = null;
int photoId = -1;if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "")
{
photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
outstream = GetPhoto(photoId);
}
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = outstream.Read(buffer, 0, buffersize);
while (count > 0)
{
context.Response.OutputStream.Write(buffer, 0, count);
count = outstream.Read(buffer, 0, buffersize);
}
}
public Stream GetPhoto(int Sid)
{
SqlConnection myConnection = new SqlConnection(strconn);SqlCommand myCommand = new SqlCommand
("SELECT img FROM [test_img] where sid=@Sid",
myConnection);
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add(new SqlParameter("@Sid", Sid));
myConnection.Open();
object result = myCommand.ExecuteScalar();
try
{
return new MemoryStream((byte[])result);
}
catch (ArgumentNullException e)
{
return null;
}
finally
{
myConnection.Close();
}
}然后在GridView中自定义模版列:
}
<asp:TemplateField HeaderText="Img">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?PhotoID=" + Eval("Sid") %>' />
</ItemTemplate>
</asp:TemplateField>
这样即可在GridView中动态显示数据库中image类型图片数据了。
