Hi Kostas
There are multiple ways to reduce the file size of an image:
- Save to a more compressed format: If your images are PNG, then the easiest way to reduce file size is to save to lossy format like JPEG (if you don't need transparency) or WebP (if you need transparency)
- Improve compression: Many formats support compression options, including PNG, optimize these: http://www.imageen.com/help/TIOParams.html
- Resample the image to make it smaller (e.g. reducing the size of an image by 50% will make it around 75% smaller on disk)
- Reduce the colors: Generally not a recommended method
If you have a strict maximum size (e.g. due to database constraints) and you are using a format that supports compression (so cannot quickly calculate the final file size), then you will need to create a method that saves a temporary file (you should just save to a TMemoryStream for speed) and keeps optimizing the options above until it does not exceed the maximum size, e.g.
// Keep reducing the quality of the image until it matches our size constraint
jpegQ := 95;
sz := MaxInt;
While sz > Maximum_Size do
begin
BMP.Params.JPEG_Quality := jpegQ;
BMP.SaveToStream( ms, ioJPEG );
sz := ms.Size;
dec( jpegQ, 5 );
if jpegQ < 10 ) then
raise EException.create( 'cannot optimize this image enough' );
end;
// Do something with ms, e.g. output to file or database
Nigel
Xequte Software
www.imageen.com