项目需要,经常需要手动调整图片尺寸,流程太过麻烦,效率低下。所以写了一个小程序,以提高工作效率
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace ChangeImgSize
{
class Program
{
static void Main(string[] args)
{
int num = 0;
if (!System.IO.Directory.Exists("Img"))
{
System.IO.Directory.CreateDirectory("Img");
Console.WriteLine("已创建Img目录,请把需要处理的图片放到该目录下");
Console.ReadKey(true);
return;
}
if (!System.IO.Directory.Exists("NewImg"))
{
System.IO.Directory.CreateDirectory("NewImg");
}
Console.WriteLine("请输入需要缩小的倍数");
double size = Convert.ToDouble(Console.ReadLine());
string[] fileStrs = System.IO.Directory.GetFiles("Img");
foreach (string s in fileStrs)
{
System.IO.FileInfo info = new System.IO.FileInfo(s);
if (info.Extension == ".png" || info.Extension == ".jpg")
{
Image img = GetFile(s);
Bitmap bit = GetNewSizeBitmap(img,size);
SaveImage(bit, info.Name, info.Extension);
}
++num;
}
Console.WriteLine("共处理:" + num + "张图片,已经保存到NewImg目录中。");
Console.ReadKey(true);
}
static public Image GetFile(string path)
{
FileStream stream = File.OpenRead(path);
int fileLength = 0;
fileLength = (int)stream.Length;
Byte[] image = new Byte[fileLength];
stream.Read(image, 0, fileLength);
System.Drawing.Image result = System.Drawing.Image.FromStream(stream);
stream.Close();
return result;
}
static public Bitmap GetNewSizeBitmap(Image img , double size){
int newWidth = Convert.ToInt32(img.Width / size);
int newHeight = Convert.ToInt32(img.Height / size);
Size s = new Size(newWidth, newHeight);
Bitmap newBit = new Bitmap(img, s);
return newBit;
}
static public void SaveImage(Bitmap bit,string name,string ext)
{
bit.Save(@"NewImg" + name);
bit.Dispose();
Console.WriteLine("已处理:" + name);
}
}
}