我正在尝试使用 FileUpload 控件调整我上传的 jpg 图像的大小,并将其转换为字节,然后再将其保存到数据库(SQL Server 2008)作为(varbinary(MAX))。我所做的和下面显示的代码是我设法将其转换为字节并作为 varbinary(MAX) 保存到数据库中。我想知道在执行所有这些功能之前如何调整图像大小。帮帮我吧。谢谢!
读取文件
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
根据文件扩展名设置内容类型
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
}
使用 varbinary 转换为字节并保存到数据库中
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into MemberReport(username, typeofcrime, location, crdatetime, citizenreport, image1, image2, image3, image4, image5)" +
" values ('" + username + "','" + typeofcrime + "','" + location.Trim() + "','" + datetime + "','" + detail.Trim() + "', @Data, @Data2, @Data3, @Data4, @Data5)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("@Data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("@Data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("@Data4", SqlDbType.Binary).Value = bytes4;
cmd.Parameters.Add("@Data5", SqlDbType.Binary).Value = bytes5;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Report Sent!";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image formats";
}
插入更新数据方法
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}