Persits Software, Inc. Knowledge Base Articles

HOWTO: Resize images based on file size

Problem Summary

AspJpeg cannot automatically process images to be a certain file size.

This article describes how to force images to be a certain file size via an iterative process.

Solution

There are two different approaches that can be taken to reducing file size. Both of these use the VB function LenB() in conjunction with the .Binary property of AspJpeg to determine the current file size.
This requires AspJpeg version 1.3 or higher.

Method 1: Progressively reduce image quality

<%
Set Jpeg = Server.CreateObject("Persits.Jpeg")

'change as needed
Jpeg.Open "c:\path\file.jpg"

iQuality = 80

While LenB(Jpeg.Binary) > 150000  '150 kilobytes
    'a lower number will mean more iterations
    iQuality = iQuality - 5     
    Jpeg.Quality = iQuality
Wend

Jpeg.Save ...

%>

Method 2: Progressively reduce image size

<%
Set Jpeg = Server.CreateObject("Persits.Jpeg")

iScale = 100

Do
    ' It is recommended to have the Jpeg.Open statement 
    ' within this loop to avoid quality loss due to 
    ' multiple resizes of the original image.

    Jpeg.Open "c:\path\file.jpg"

    Jpeg.Height = Jpeg.OriginalHeight * iScale / 100
    Jpeg.Width = Jpeg.OriginalWidth * iScale / 100

    'a lower number will mean more iterations
    iScale = iScale - 5             

Loop While LenB(Jpeg.Binary) > 150000   '150 kilobytes

Jpeg.Save ... 

%>

You can also write code to do both size and quality reductions in the same script.

Note that these operations are CPU-intensive. It is recommended that these methods be used when accepting uploaded images or saving images to a database, not for displaying thumbnails.