拍了不少照片,如果不加修改直接上传太耗空间,上载和下载速度也慢。不喜欢用第三方的程序,于是马马虎虎自己写了个,把一个目录里的所有JPG文件缩小(如果需要的话),然后存到另一个目录里去,文件名不变。好像效果还行。
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace PhotoResize
{
class Program
{
private const int defWidth = 640;
private const int defHeight = 480;
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("PhotoResize source target [width] [height]");
return;
}
string source = args[0];
string target = args[1];
int width;
if ((args.Length < 3) || (!int.TryParse(args[2], out width)))
{
width = defWidth;
}
int height;
if ((args.Length < 4) || (!int.TryParse(args[2], out height)))
{
height = defHeight;
}
string[] files = Directory.GetFiles(source, "*.jpg");
foreach (string file in files)
{
string filename = Path.GetFileName(file);
Resize(
file,
Path.Combine(target, filename),
(double)width,
(double)height
);
}
}
private static void Resize(string source, string target, double width, double height)
{
Image image = Image.FromFile(source);
double imgWidth = (double)image.Width;
double imgHeight = (double)image.Height;
if (imgHeight > imgWidth)
{
double temp = width;
width = height;
height = temp;
}
double deltaWidth = width / imgWidth;
double deltaHeight = height / imgHeight;
if ((deltaWidth >= 1) && (deltaHeight >= 1))
{
Console.WriteLine("{0}",source);
File.Copy(source, target, true);
return;
}
Size targetSize;
if (deltaWidth > deltaHeight)
{
targetSize = new Size(
(int) (imgWidth * deltaHeight),
(int)height
);
}
else
{
targetSize = new Size(
(int)width,
(int)(imgHeight * deltaWidth)
);
}
using (Bitmap bitmap = new Bitmap(image, targetSize))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Rectangle rectSrc = new Rectangle(0,0,image.Width,image.Height);
Rectangle rectTarget = new Rectangle(0,0,targetSize.Width,targetSize.Height);
graphics.DrawImage(
image,
rectTarget,
rectSrc,
GraphicsUnit.Pixel
);
}
Console.WriteLine("{0}", source);
bitmap.Save(target, ImageFormat.Jpeg);
}
}
}
}