文件夹大小调整
如何调整大量图像的大小。
引言
当我从数码相机下载照片时,我发现它们非常大,并且我不得不花费很长时间来上传和单独调整它们的大小。因此,我编写了这个简单的应用程序,它可以调整指定文件夹中所有图像的大小。
使用代码
代码非常简单。如您在窗体中所见,它非常简单易懂。首先,您选择文件夹,然后单击“开始”以开始调整大小的过程,并且可以更改调整大小的比例和将包含调整大小的图像的文件夹名称。
该代码使用了 System.IO
和 System.Drawing.Imaging
命名空间。第一个用于创建文件夹,第二个用于指定图像格式。
第一个按钮将打开 FolderBrowserDialog
,允许您选择包含要调整大小的图像的文件夹。
private void button1_Click(object sender, System.EventArgs e)
{
DialogResult dr = folderBrowserDialog1.ShowDialog();
if(dr == DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
textBox1.Text=path;
button2.Enabled=true;
}
选择文件夹后,我们单击第二个按钮开始调整大小,代码如下
private void button2_Click(object sender, System.EventArgs e)
{
// Create The new directory with the name specified in the textbox
DirectoryInfo newDiroctory = new DirectoryInfo(path+"\\"+textBox3.Text);
newDiroctory.Create();
// This is the new path that will contain the new resized images
string newPath =path +"\\"+ textBox3.Text+"\\";
string []images = Directory.GetFiles(path);
// this array contain ALL files in the specified directory
progressBar1.Minimum=0;
progressBar1.Maximum=images.Length;
int couter = 0; // this will count the number of images in the folder
for (int i=0;i < images.Length;i++)
{
// select only the image format in the folder
string fileExtention =
images[i].Substring(images[i].Length - 3, 3);
if(fileExtention== "bmp"||fileExtention=="jpg"||
fileExtention=="JPG"||fileExtention=="BMP"||
fileExtention=="gif"||fileExtention=="Gif")
{
couter++;
Image currentImage = Image.FromFile(images[i]);
int h = currentImage.Height;
int w = currentImage.Width;
// calculate the new dimensions
// according to the resizing factor
float factor =
float.Parse(comboBox1.SelectedItem.ToString());
int newH = (int)Math.Ceiling((double)h*factor);
int newW = (int)Math.Ceiling((double)w*factor);
// get the Image name from the path
string imageName = images[i].Substring(path.Length+1,
images[i].Length-path.Length-5);
// create the new bitmap with the specified size
Bitmap newBitmap = new Bitmap(currentImage,new Size(newW,newH));
// according to type of the file we will save the new image
if(fileExtention=="bmp"||fileExtention=="BMP")
newBitmap.Save(newPath+imageName+".bmp",ImageFormat.Bmp);
if(fileExtention=="JPG"||fileExtention=="jpg")
newBitmap.Save(newPath+imageName+".jpg",ImageFormat.Jpeg);
if(fileExtention=="gif"||fileExtention=="GIF")
newBitmap.Save(newPath+imageName+".gif",ImageFormat.Gif);
progressBar1.Value++;
}
}
MessageBox.Show(couter.ToString()+
" images was resized and its path is:"+newPath,"Done");
}
代码非常简单,并且有很多有用的注释。