您的位置:首页 > 编程语言 > C#

C# 批量修改图片尺寸的代码

2009-03-06 08:50 393 查看
这是批量改图片尺寸的:

调用方法: ResizeImages(包含原始图片的路经,存放修改大小后图片的路经,图片的最大尺寸(大于该尺寸的就压缩),输出文件的质量,是否处理子文件夹里的图片)

public static void SaveFileAsJPG(string orgionalExt, System.IO.Stream file, System.Drawing.Size size, long quality, ref FileStream targetFile)
{
orgionalExt = orgionalExt.Replace(".", "").ToLower();
System.Drawing.Graphics g;
System.Drawing.Image img;
if (orgionalExt == "bmp")
{
img = System.Drawing.Bitmap.FromStream(file);
if (size.Width == 0 || size.Height == 0)
{
size.Width = img.Width;
size.Height = img.Height;
}
}
else
{
img = System.Drawing.Image.FromStream(file);
if (size.Width == 0 || size.Height == 0)
{
size.Width = img.Width;
size.Height = img.Height;
}
}
System.Drawing.Image img1;
if (img.Width > size.Width || img.Height > size.Height)
{
if (img.Width > img.Height)
{
float h = ((float)size.Width / img.Width * img.Height);
img1 = new System.Drawing.Bitmap(size.Width, (int)h);
}
else
{
float w = ((float)size.Height / img.Height * img.Width);
img1 = new System.Drawing.Bitmap((int)w, size.Height);
}

g = System.Drawing.Graphics.FromImage(img1);
g.DrawImage(img, 0, 0, (float)img1.Width, (float)img1.Height);
}
else
{
img1 = img;
g = System.Drawing.Graphics.FromImage(img1);
}
g.Save();
System.IO.Stream srm = targetFile;
System.Drawing.Imaging.ImageCodecInfo ici = GetCodecInfo("image/jpeg");
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
img1.Save(srm, ici, parameters);
srm.Position = 0;
}
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}

private void ResizeImages(string path, string target, Size size, long quality, bool subfolder)
{
if (!Directory.Exists(target))
Directory.CreateDirectory(target);
List<string> lst = new List<string>();
lst.AddRange(Directory.GetFiles(path, "*.jpg", subfolder ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
lst.AddRange(Directory.GetFiles(path, "*.bmp", subfolder ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
for (int i = 0; i < lst.Count; i++)
{
label7.Text = string.Format("{0}/{1}", i, lst.Count);
Application.DoEvents();
string ext = Path.GetExtension(lst[i]);
string tarfile = target + Path.GetFileNameWithoutExtension(lst[i]) + "_" + i.ToString() + ".jpg";
if (File.Exists(tarfile))
{
if (checkBox2.Checked)
{
File.SetAttributes(tarfile,FileAttributes.Normal );
File.Delete(tarfile);
}
else
continue;
}
FileStream fs = File.OpenWrite(tarfile );
SaveFileAsJPG(ext, File.OpenRead(lst[i]), size, quality, ref fs);
fs.Flush();
fs.Close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息