[英]C# Resize jpg image, convert to byte and save into database using varbinary
I'm trying to resize my jpg image uploaded by using FileUpload control and convert it into byte before saving it to database (SQL Server 2008) as (varbinary(MAX)). 我正在尝试调整我使用FileUpload控件上传的jpg图像,并在将其保存到数据库(SQL Server 2008)之前将其转换为byte(varbinary(MAX))。 What I have done and code show below was that I manage to convert it into byte and save into database as varbinary(MAX). 我所做的和下面的代码显示我设法将其转换为字节并作为varbinary(MAX)保存到数据库中。 I wish to know how to I resize the image before doing all those function. 我想知道如何在完成所有这些功能之前调整图像大小。 Do help me out. 帮帮我吧 Thanks! 谢谢!
Read the file 阅读文件
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
Set the contenttype based on File Extension 根据文件扩展名设置contenttype
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
}
Convert into byte and save into database using varbinary 转换为字节并使用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";
}
InsertUpdateData method InsertUpdateData方法
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();
}
You need to convert the uploaded file to an Image
object, which can be done simply with: 您需要将上传的文件转换为Image
对象,这可以通过以下方式完成:
Image uploaded = Image.FromStream(FileUpload1.PostedFile.InputStream);
Next, figure out how big you want the image to be. 接下来,弄清楚你想要的图像有多大。 Let's say you want the largest dimension to be 256 pixels, and maintain aspect ratio. 假设您希望最大尺寸为256像素,并保持纵横比。 Some code adapted from the CodeProject article Resizing an Image On-The-Fly using .NET : 一些代码改编自CodeProject文章使用.NET动态调整图像大小 :
int originalWidth = uploaded.Width;
int originalHeight = uploaded.Height;
float percentWidth = (float)256 / (float)originalWidth;
float percentHeight = (float)256 / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
int newWidth = (int)(originalWidth * percent);
int newHeight = (int)(originalHeight * percent);
Now create a new Bitmap
object to contain the resized image (from the same CodeProject article) and draw the original image to it: 现在创建一个新的Bitmap
对象来包含调整大小的图像(来自相同的CodeProject文章)并将原始图像绘制到它:
Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, newWidth, newHeight);
}
And finally, convert back to bytes to save into the database: 最后,转换回字节以保存到数据库中:
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
I took the long route to set the quality level of the output. 我采用漫长的路线来设定输出的质量水平。 If you don't mind what compression level is used, a simple img.Save(ms, ImageFormat.Jpeg);
如果你不介意使用什么压缩级别,一个简单的img.Save(ms, ImageFormat.Jpeg);
call replaces the first 4 lines inside the using
code block. call取代了using
代码块中的前4行。
Check out the CodeProject article I mentioned above for more information on resizing images, and read C# Image to Byte Array and Byte Array To Image Converter Class (also on CodeProject) for more on converting images to/from byte arrays. 查看我上面提到的CodeProject文章 ,了解有关调整图像大小的更多信息,并阅读C#Image to Byte Array和Byte Array To Image Converter Class (也在CodeProject上),了解有关将图像转换为字节数组的更多信息。
The last part, inserting the image into a database table. 最后一部分,将图像插入数据库表。 I'll assume Microsoft SQL, and do a very simple table insert. 我将假设Microsoft SQL,并做一个非常简单的表插入。
Table is defined as: 表定义为:
CREATE TABLE [Images](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImageData] [varbinary](max) NULL,
CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
And the code to insert the image data into the table: 以及将图像数据插入表格的代码:
static string connString = "Data Source=localhost; Initial Catalog=project; Integrated Security=True";
public static int InsertImage(byte[] imgdata)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Images(ImageData) OUTPUT inserted.ID VALUES(@p1)", conn))
{
cmd.Parameters.AddWithValue("@p1", imgdata);
int res = (int)cmd.ExecuteScalar()
return res;
}
}
}
The returned value is the auto-increment value generated by SQL for the record. 返回值是SQL为记录生成的自动增量值。
Or to update an existing image: 或者更新现有图像:
public static void UpdateImage(int id, byte[] imgdata)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Images SET ImageData = @p1 WHERE ID = @p2", conn))
{
cmd.Parameters.AddWithValue("@p1", imgdata);
cmd.Parameters.AddWithValue("@p2", id);
cmd.ExecuteNonQuery();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.