Windows XP Tablet 版GDI+Windows VistaWindows 2003.NET 3.0Windows 2000Windows XP.NET 3.5C# 2.0C# 3.0中级开发Windows.NETASP.NETC#
图像处理以及读写数据库






4.83/5 (5投票s)
这段代码允许你从数据库读取和写入数据,并更改图像尺寸、大小和质量。
引言
有很多文章介绍了如何将图片插入数据库并读回,如何降低图片质量和大小,以及如何更改图片尺寸。但我还没有找到一篇文章将以上所有功能集成到一个项目中。这篇文章将展示所有这些技巧,例如,更改照片的质量,以便在不影响质量的情况下减小文件大小[用于网页发布或电子邮件目的],更改尺寸,如何将图片保存到数据库,以及如何从数据库读取图像并在图像控件中显示。这非常适合批量处理。
背景
基本思路来自 GeekPedia 上 Andrei Pociu 的一篇文章;部分帮助来自 Microsoft 和 DZone Snippets 网站。
使用代码
下面的代码将从包含图片的文件夹中加载列表
if (fbdOpen.ShowDialog() == DialogResult.OK)
{
// Clear any previous items in the list
lstPhotos.Items.Clear();
// Run a loop through all the files in the directory at the selected path
foreach (string Filename in Directory.GetFiles(fbdOpen.SelectedPath))
{
// We'll create a new FileInfo object from the file path
FileInfo fiPicture = new FileInfo(Filename);
// If it's a JPEG file
if (fiPicture.Extension.ToLower() == ".jpeg" ||
fiPicture.Extension.ToLower() == ".jpg")
{
// Add it to the list of files
lstPhotos.Items.Add(Filename);
}
}
}
// We want the ProgressBar to have the same
// maximum value as the number of pictures to resize
prgReduce.Maximum = lstPhotos.Items.Count;
这将处理你的请求,以调整大小、调整质量并将图片保存到数据库,以及保存到另一个文件夹,并具有所需的尺寸和质量。
// Reset the progress bar
prgReduce.Value = 0;
// Show the FolderBrowserDialog where
// the user selects where to save the files
if (fbdSave.ShowDialog() == DialogResult.OK)
{
// We will store the correct image codec in this object
ImageCodecInfo iciJpegCodec = null;
// This will specify the image quality to the encoder
EncoderParameter epQuality =
new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
(int)numQual.Value);
// Get all image codecs that are available
ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders();
// Store the quality parameter in the list of encoder parameters
EncoderParameters epParameters = new EncoderParameters(1);
epParameters.Param[0] = epQuality;
// Loop through all the image codecs
for (int i = 0; i < iciCodecs.Length; i++)
{
// Until the one that we are interested
// in is found, which is image/jpeg
if (iciCodecs[i].MimeType == "image/jpeg")
{
iciJpegCodec = iciCodecs[i];
break;
}
}
// Loop through the files in the list
// Insert to database and Save on Disk
foreach (string strFile in lstPhotos.Items)
{
SqlConnection cn = new SqlConnection(strCn);
SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest" +
" (BLOBData, BLOBName, InsertDate) " +
"VALUES (@BLOBData, @BLOBName, @DateTime)", cn);
// Take another step on the progress bar
prgReduce.PerformStep();
// Create a new Image object from the current file
Image newImage = Image.FromFile(strFile);
// Get the file information again,
// this time we want to find out the extension
FileInfo fiPicture = new FileInfo(strFile);
//Get the desired photos size
int PhotoWidth = 0;
if (radioButton1.Checked)
{
PhotoWidth = 1024;
}
else if(radioButton2.Checked)
{
PhotoWidth = 640;
}
else if (radioButton3.Checked)
{
PhotoWidth = 420;
}
//Re-Size the photo
System.Drawing.Image ImageReSized =
ResizeImage(strFile, fbdSave.SelectedPath.ToString() +
"\\" + fiPicture.Name, PhotoWidth, 768, false);
//newImage.GetThumbnailImage(640, 480, null, IntPtr.Zero);
//Convert Image to byt to save on database
System.Drawing.ImageConverter ic =
new System.Drawing.ImageConverter();
byte[] bytBLOBData = new byte[1];
bytBLOBData = (byte[])ic.ConvertTo(ImageReSized, bytBLOBData.GetType());
//Update the database
SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary,
bytBLOBData.Length, ParameterDirection.Input, false,
0, 0, null, DataRowVersion.Current, bytBLOBData);
SqlParameter prm1 = new SqlParameter("@BLOBName", SqlDbType.VarChar, 100,
ParameterDirection.Input, false, 0, 0, null,
DataRowVersion.Current, fiPicture.FullName);
SqlParameter prm2 = new SqlParameter("@DateTime", SqlDbType.DateTime, 21,
ParameterDirection.Input, false, 0, 0, null,
DataRowVersion.Current, DateTime.Now);
//Add parameter
cmd.Parameters.Add(prm);
cmd.Parameters.Add(prm1);
cmd.Parameters.Add(prm2);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
// Save resized picture here
ImageReSized.Save(fbdSave.SelectedPath.ToString() + "\\" +
fiPicture.Name, iciJpegCodec, epParameters);
}
// Open the folder containing the new items
System.Diagnostics.Process.Start(fbdSave.SelectedPath.ToString());
}
上面的代码调用此函数来更改尺寸
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(originalFile);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (onlyResizeIfWider)
{
if (FullsizeImage.Width <= newWidth)
{
newWidth = FullsizeImage.Width;
}
}
int NewHeight = FullsizeImage.Height * newWidth / FullsizeImage.Width;
// NewHeight = maxHeight; //temp Test
if (NewHeight > maxHeight)
{
// Resize with height instead
newWidth = FullsizeImage.Width * maxHeight / FullsizeImage.Height;
NewHeight = maxHeight;
}
System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(newWidth,
NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose();
// Save resized picture here as well if you wish to
// NewImage.Save(newFile);
return NewImage;
关注点
现在,你拥有在一个项目中实现所有图像或照片处理功能的代码。现在,我的妻子就不需要再使用画笔来降低图片质量来通过电子邮件发送照片了。