How To Resize All Images In Folder
Instead of resizing every image manually in Photoshop or some similar software, .Net Framework provides an easy way to resize all images in folder by calling one function. To resize all images in folder we need to perform these tasks:
1. List all images on some location
2. Iterate through a collection of file names and resize every image.
First step is explained in How To Get A List Of Files From Folder In ASP.NET? tutorial. Resizing of images is covered in How To Create Thumbnail From Larger Image?. To solve resizing of all images in specified folder we'll use both tutorials and final solution is a ResizeImagesInFolder function that has three parameters:
- SourceFolder - string, folder where original images are stored
- DestinationFolder - string, folder where resized images will be saved
- NewImageSize - integer, width or height depending of which is higher (is it landscape or portrait) of resized image.
[ C# ]
// Include these namespaces
// To open image files from directory
using System.IO;
// To store image file names to ArrayList
using System.Collections;
// To resize an image and store it to destination folder
using System.Drawing;
using System.Drawing.Drawing2D;
...
public void ResizeImagesInFolder(string SourceFolder,
string DestinationFolder, int NewImageSize)
{
// Check if source folder exists and throw exception if not
if (!Directory.Exists(SourceFolder))
throw new Exception("SourceFolder does not exist");
// Check if destination folder exists, but create it if not
if (!Directory.Exists(DestinationFolder))
{
Directory.CreateDirectory(DestinationFolder);
}
// List all images from source directory
DirectoryInfo diImages = new DirectoryInfo(SourceFolder);
ArrayList alImages = new ArrayList();
// GetFiles method doesn't allow us to filter for multiple
// file extensions, so we must find images in four steps
// Feel free to add new or remove existing extension to
// suit your needs
alImages.AddRange(diImages.GetFiles("*.gif"));
alImages.AddRange(diImages.GetFiles("*.jpg"));
alImages.AddRange(diImages.GetFiles("*.bmp"));
alImages.AddRange(diImages.GetFiles("*.png"));
Image imgOriginal;
float OriginalHeight;
float OriginalWidth;
int NewWidth;
int NewHeight;
Bitmap ResizedBitmap;
Graphics ResizedImage;
// Resize every image
foreach(FileInfo fiImage in alImages)
{
// Loads original image from source folder
imgOriginal = Image.FromFile(fiImage.FullName);
// Finds height and width of original image
OriginalHeight = imgOriginal.Height;
OriginalWidth = imgOriginal.Width;
// Finds height and width of resized image
if (OriginalHeight > OriginalWidth)
{
NewHeight = NewImageSize;
NewWidth = (int)((OriginalWidth / OriginalHeight) * (float)NewImageSize);
}
else
{
NewWidth = NewImageSize;
NewHeight = (int)((OriginalHeight / OriginalWidth) * (float)NewImageSize);
}
// Create new bitmap that will be used for resized image
ResizedBitmap = new Bitmap(NewWidth, NewHeight);
ResizedImage = Graphics.FromImage(ResizedBitmap);
// Resized image will have best possible quality
ResizedImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
ResizedImage.CompositingQuality = CompositingQuality.HighQuality;
ResizedImage.SmoothingMode = SmoothingMode.HighQuality;
// Draw resized image
ResizedImage.DrawImage(imgOriginal, 0, 0, NewWidth, NewHeight);
// Save thumbnail to file
ResizedBitmap.Save(DestinationFolder + fiImage.Name);
// It is important to take care of memory, especially in cases
// when code works with graphics
imgOriginal.Dispose();
ResizedBitmap.Dispose();
ResizedImage.Dispose();
}
}
[ VB.NET ]
' We need these namespaces
' To open image files from directory
Imports System.IO
' To store image file names to ArrayList
Imports System.Collections
' To resize an image and store it to destination folder
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Sub ResizeImagesInFolder(ByVal SourceFolder As String, _
ByVal DestinationFolder As String, ByVal NewImageSize As Integer)
' Check if source folder exists and throw exception if not
If Not Directory.Exists(SourceFolder) Then
Throw New Exception("SourceFolder does not exist")
End If
' Check if destination folder exists, but create it if not
If Not Directory.Exists(DestinationFolder) Then
Directory.CreateDirectory(DestinationFolder)
End If
' List all images from source directory
Dim diImages As DirectoryInfo = New DirectoryInfo(SourceFolder)
Dim alImages As ArrayList = New ArrayList()
' GetFiles method doesn't allow us to filter for multiple
' file extensions, so we must find images in four steps
' Feel free to add new or remove existing extension to
' suit your needs
alImages.AddRange(diImages.GetFiles("*.gif"))
alImages.AddRange(diImages.GetFiles("*.jpg"))
alImages.AddRange(diImages.GetFiles("*.bmp"))
alImages.AddRange(diImages.GetFiles("*.png"))
Dim imgOriginal As Image
Dim OriginalHeight As Single
Dim OriginalWidth As Single
Dim NewWidth As Integer
Dim NewHeight As Integer
Dim ResizedBitmap As Bitmap
Dim ResizedImage As Graphics
' Resize every image
For Each fiImage As FileInfo In alImages
' Loads original image from source folder
imgOriginal = Image.FromFile(fiImage.FullName)
' Finds height and width of original image
OriginalHeight = imgOriginal.Height
OriginalWidth = imgOriginal.Width
' Finds height and width of resized image
If (OriginalHeight > OriginalWidth) Then
NewHeight = NewImageSize
NewWidth = ((OriginalWidth / OriginalHeight) * NewImageSize)
Else
NewWidth = NewImageSize
NewHeight = ((OriginalHeight / OriginalWidth) * NewImageSize)
End If
' Create new bitmap that will be used for resized image
ResizedBitmap = New Bitmap(NewWidth, NewHeight)
ResizedImage = Graphics.FromImage(ResizedBitmap)
' Resized image will have best possible quality
ResizedImage.InterpolationMode = InterpolationMode.HighQualityBicubic
ResizedImage.CompositingQuality = CompositingQuality.HighQuality
ResizedImage.SmoothingMode = SmoothingMode.HighQuality
' Draw resized image
ResizedImage.DrawImage(imgOriginal, 0, 0, NewWidth, NewHeight)
' Save thumbnail to file
ResizedBitmap.Save(DestinationFolder + fiImage.Name)
' It is important to take care of memory, especially in cases
' when code works with graphics
imgOriginal.Dispose()
ResizedBitmap.Dispose()
ResizedImage.Dispose()
Next
End Sub
To use this function, simply set source and destination folder and define new image size. For example, let say you want to create image gallery software that will create a gallery from images taken from digital camera. These images are usually large in size, so ResizeImagesInFolder function frees memory after every image is resized. I tested code with 104 digital images taken from digital camera and stored in folder OriginalImages. Every image has 3456x2592 resolution (it is about 2.68 MB on disc). For image browsing, I want maximum size of 150 pixels, and for single image view I choose 500px because 2.68 MB images are still too much on web page.
To implement image resizing in some web application, I need one button control on page. On button's click code will call ResizeImagesInFolder function twice, first time to resize images to 500px and save them to ResizedImages folder, and second time to create thumbnails of 150px and store them to Thumbnails folder. Code to resize images in two folders will look like this:
[ C# ]
protected void btnResizeImages_Click(object sender, EventArgs e)
{
// Resize images to 500px for single image view
ResizeImagesInFolder(Request.MapPath("~/OriginalImages/"), Request.MapPath("~/ResizedImages/"), 500);
// Resize images to thumbnails of 150px for browsing
ResizeImagesInFolder(Request.MapPath("~/OriginalImages/"), Request.MapPath("~/ThumbnailImages/"), 150);
}
[ VB.NET ]
Protected Sub btnResizeImage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnResizeImage.Click
' Resize images to 500px for single image view
ResizeImagesInFolder(Request.MapPath("~/OriginalImages/"), _
Request.MapPath("~/ResizedImages/"), 500)
' Resize images to thumbnails of 150px for browsing
ResizeImagesInFolder(Request.MapPath("~/OriginalImages/"), _
Request.MapPath("~/ThumbnailImages/"), 150)
End Sub
Please note that you need to have read/write access to save resized images in specified folder. If you have really a lot of large images, it is possible that you'll get ASP.NET script time out error. The solution could be to resize files in smaller groups or to increase timeout value. Default time for ASP.NET page execution is 90 seconds. To change it, use Server.ScriptTimeout property to set new script timeout in seconds.
Tutorial toolbar: Tell A Friend | Add to favorites | Feedback |
|