我的网页允许用户上传图像,并将图像保存到SQL Server,并将图像显示给用户。以下代码是我保存图像的方式:
FileUpload img = (FileUpload)fileUploadLocationPic;
Byte[] imgByte = null;
string strFileExtension = Path.GetExtension(img.PostedFile.FileName.ToString());
// Create a FILE
HttpPostedFile File = fileUploadLocationPic.PostedFile;
// Create byte array
imgByte = new Byte[File.ContentLength];
// force control to load data
File.InputStream.Read(imgByte, 0, File.ContentLength);
strQuery = "INSERT INTO [Table](Image) VALUES(@LocImage)";
SqlParameter ParamLocImage = new SqlParameter();
ParamLocImage.ParameterName = "@LocImage";
ParamLocImage.Value = imgByte;
cmd.Parameters.Add(ParamLocImage);
以下是我使用ashx从数据库中检索的方法:
public Stream ShowEmpImage(string PLID){
string connectionString = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
//string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sql = "SELECT [Image] FROM [Table] WHERE [ID] = @PLID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@PLID", PLID);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public void ProcessRequest(HttpContext context){
string PLID = "";
PLID = (context.Request.QueryString["PLID"]);
context.Response.ContentType = "image/jpg";
Stream strm;
strm = ShowEmpImage(PLID);
int count = 2048;
byte[] buffer = new byte[count];
int byteSeq = 0;
try
{
byteSeq = strm.Read(buffer, 0, count);
}
catch
{
}
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, count);
}
}
最后,我使用
<asp:Image ID="imageChargingLocation" runat="server" />
imageChargingLocation.ImageUrl = "~/Editor/ShowImage.ashx?PLID=" + strPLID;
检索图像。 但是我的图像质量下降了。 我该怎么办? (图像是jpg。尝试png时同样的问题。)