1

I found out that images can be compressed by a certain percentage. For example:

$compressed_img = compress($source_img, $destination_img, 90);

In this case, the size of $source_img will be reduced to 90% of the original size. If the original size is of $source_img 100kb, that of $compressed_img will be 90kb.

What I've been trying to do is to determine whether the target file is compressed based on the original size, and determine how much size is going to be reduced by byte.

For example, what if you need to ensure that all the uploaded files are under 200kb but you must not change the size if the uploaded size is already lighter than that?

Here is a pseudo code.

if($source > 200kb){
    $compressed = compressByByte($source, 200kb);
}//Again, this is a sude code!

Since the size of the source file varies, it's not going to be practical to use the compress() function.

Any advice will be appreciated. (I'm using php with Laravel 5.2)

Ian
  • 3,539
  • 4
  • 27
  • 48
Hiroki
  • 3,893
  • 13
  • 51
  • 90

1 Answers1

0

I think that you start from the wrong assumption, when you compress image you can specify a compress factor but it doesn't mean that the output is 90% of the original size it vastly depends from the content of the image, some images can be compressed better the others (a mono color image can be smaller than a normal photo).

That said what you can do is to

  1. cycle all the images
  2. check if the images is larger than a threshold size that you define (for example 200k
  3. for every image save a compressed version of the image as a temp file
  4. confront the original image size with the temp size and you can choose to maintain the original one or use the new compressed one.

Remember that increasing the compression in JPEG lowers the quality of the image and you start seeing low ugly errors in your images if the compression is too high, usually we don't use compression under 85.

wezzy
  • 5,897
  • 3
  • 31
  • 42
  • Thank you for your reply. Just confirmation, by "cycle all the images", did you mean iterating all the uploaded images in a forloop (or something like that), so that I could check the size of the images? – Hiroki Apr 11 '16 at 07:29
  • Yes, exactly something like this http://stackoverflow.com/a/3738315/87407 this will takes some time you can create a script that do this for every image and run it on the command line the first time. Then modify your upload logic to check all the images uploaded then they will be uploaded (or just run your script periodically, like every night) – wezzy Apr 11 '16 at 09:58