Search Persits Software Knowledge Base


Article PS031212119

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.


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

Jpeg.Save ...


Method 2: Progressively reduce image size

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

iScale = 100

    ' 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.

Created: 12/12/2003 4:50:18 PM
Last Modified: 3/26/2012 11:14:33 AM

Copyright © Persits Software, Inc. 1998 - 2023
For technical support, write to