How can I estimation the file size of an image using its width and height?

1k Views Asked by At

I have recently written an image resizing program using php, which works by downloading images off another server, resizing them and saving them to our own.

The bad news is that my Hosting account only allows a php memory limit of 64M, and this is just not set up to resize the HUUUUGE file sizes that my client is uploading (3 - 4mb). It spits out a fatal error if it meets these images and breaks the script.

Even though I have notified said client of this drawback, said client continues to upload large images and script keeps breaking.

I can obtain the width and the height of the image before downloading it using getimagesize(), and if I could use this info to work out the total file size I could break out before the image resizer gets going and suppliment the image with a nice "no image available" alternative.

How can I make an accurate estimation of an images file size using its width and height, assuming it has a bit depth of 24?

4

There are 4 best solutions below

1
On

A multiplication. Just multiply height by width by 3. and throw in some spare memory to process all these bytes. say, twice the image size.

It has nothing to do with file size though.

2
On

An image in memory always weights the same weight compressed in JPEG or GIF or BMP. It's called a BIT-MAP. So, if you want to calculate the size of an image in memory, take the width, the height and the bit size to get the bit weight, divide by 8 and you get the bytesite.

$ByteSize = Width*Heigh*(24/8)

Note that it is possible to get more weight from an image in some parts such as a paletized image, it will have to store the image color palette in memory but most of the time this should weight less than a bitmap.

3
On

before the upload on the server you can't with php, but you can use javascript!

https://developer.mozilla.org/en/DOM/File

will work in conjunction of and will instantly provide the filesize using

fileInput.files[0].fileSize

read these:

https://developer.mozilla.org/en/Using_files_from_web_applications http://hacks.mozilla.org/2009/12/multiple-file-input-in-firefox-3-6/

hope this helps!

0
On

The size will always depend on the format. When compressing images, the size of the image itself won't have any effect on the filesize. The only way that you can get a good readout of the filesize is if you use a Bitmap (or simmilar) format.

Example, A JPEG could be 10MB in size, and then when rotated only 1 MB in size because of how the compression works.