
Introduction
The Internet is full of all kinds of programs, both shareware and freeware, to resize images. Turns out, you don't need a program if you have access to a Windows PC with at least Windows Vista (XP from SP1 on is also supported, but requires a separate download).
Resizing can be done entirely in a script using Windows Image Acquisition Automation. Here is a script that will resize all the images in a given directory.
Background
Anyone who has ever created a webpage with thumbnails may find this useful.
Using the Code
Example:
resize_image.wsf /indir:"My Pictures" /width:160 /height:120
All options can be found by running resize_image.wsf (or just look at the image above).
How it Works
Windows Image Acquisition (WIA) COM objects include WIA.ImageFile
and WIA.ImageProcess
. After an image file has been loaded with ImageFile.LoadFile()
, various filters can be used on it via ImageProcess.Filters.Add()
. One of the filters (called Scale
) can scale the image. This is what the script is using:
var Img = WScript.CreateObject("WIA.ImageFile.1");
var IP = WScript.CreateObject("WIA.ImageProcess.1");
var fso = WScript.CreateObject("Scripting.FileSystemObject");
...
function resize(filename)
{
var path = inDir + "\\" + filename;
var newWidth, newHeight;
Img.LoadFile(path);
if (IP.Filters.Count == 0)
{
IP.Filters.Add(IP.FilterInfos("Scale").FilterID);
}
if (Img.Width > Img.Height)
{
newWidth = scaledWidth;
newHeight = scaledHeight;
}
else
{
newWidth = scaledHeight;
newHeight = scaledWidth;
}
IP.Filters(1).Properties("MaximumWidth") = newWidth;
IP.Filters(1).Properties("MaximumHeight") = newHeight;
if (Img.Width > newWidth || Img.Height > newHeight)
{
Img = IP.Apply(Img);
if (!fso.FolderExists(outDir))
{
fso.CreateFolder(outDir);
}
var newPath = outDir + "\\" + filename;
if (!fso.FileExists(newPath))
{
Img.SaveFile(newPath);
return true;
}
}
return false;
}
Points of Interest
I found there was no version-independent ProgID (without ".1") on my XP SP3 machine. That's why WScript.CreateObject()
calls use version 1 ProgIDs (e.g., WIA.ImageFile.1
instead of WIA.ImageFile
). So far, there is only version 1 of the WIA automation library anyway. However, my Windows 7 machine contains version-independent WIA ProgIDs, so ".1" could be removed.
Another thing - if you run the script under the default WSH host (WScript), it will display a popup before going through the directory and another after it's done (see Echo
commands). To run in non-blocking mode (text output instead of graphical popups), start it under cscript:
cscript resize_image.wsf