Batch Optimizing Images

The same image can be saved in multitude of ways. Whether it is camera phone or editing application, usually goal is to save image quickly without caring for each and every byte. I mean, is it really important if image is 2.5 MB or 2.1 MB? Under most circumstances bigger file is written more quickly and slightly bigger size is perfectly acceptable compromise.

However, if you place the image on a website, this suddenly starts to matter. If your visitors are bandwidth-challenged, it makes a difference between the load time measured in seconds or tenths of seconds. However, if you start optimizing, you can spend way too much time dealing with this. If you are lazy like me and don't want to change your flow too much, there is always an option to save unoptimized files now and optimize later.

For optimizing images I tend to stick with two utilities: OptiPNG for PNG and jpegoptim for JPEG files. Both of them do their optimizations in a completely lossless fashion. This might not bring you the best savings, especially for JPEG images, but it has one great advantage - if you run optimization over the already optimized images, there will be no harm. This means you don't need to track what files are already optimized and which need work. Just run the tools every once in a while and you're golden.

I created the following script to go over each image and apply optimizations:

@ECHO OFF

SET EXE_OPTIPNG="\Tools\optipng-0.7.5\optipng.exe"
SET EXE_JPEGTRAN="\Tools\jpegoptim-1.4.3\jpegoptim.exe"

SET DIRECTORY=.\pictures

ECHO = OPTIMIZE PNG =
FOR /F "delims=" %%F in ('DIR "%DIRECTORY%\*.png" /B /S /A-D') do (
ECHO %%F
DEL "%%F.tmp" 2> NUL
%EXE_OPTIPNG% -o7 -silent -out "%%F.tmp" "%%F"
MOVE /Y "%%F.tmp" "%%F" > NUL
IF ERRORLEVEL 1 PAUSE && EXIT
)

ECHO.

ECHO = OPTIMIZE JPEG =
FOR /F "delims=" %%F in ('DIR "%DIRECTORY%\*.jpg" /B /S /A-D') do (
ECHO %%F
%EXE_JPEGTRAN% --strip-all --quiet "%%F"
IF ERRORLEVEL 1 PAUSE && EXIT
)

And yes, this will take ages. :)

Leave a Reply

Your email address will not be published. Required fields are marked *