Search code examples
phpimagemathuploadaspect

PHP Image upload limit aspect ratio and allow only images with dimensions >= 600px


I want to restrict any images uploaded to an aspect ratio of 1. These images should also have a minimum height/width of 600px. My problem is that my javascript cropper(slimimagecropper) sometimes produces images with dimensions of 599x600px or 598x600px. To solve this problem I wanted to allow a tolerance of +-3px. I check the aspect ratio as follows:

if (abs(1 - ($image->width() / $image->height())) <= 0.009) { //... }

But now the greater the image (for example 700x700) the greater is the tolerance (7px).

Does someone know a better way to check for the aspect ratio?


Solution

  • Aspect ratio of 1:1 means width equals height. So you want to check whether the difference between width and height exceeds 3px. Checking minimum dimensions would be a separate check.

    If you want to also have ratios other than 1:1, you need to decide where the difference should apply. For example, for 4:3 a height difference of 3px would correspond to a width difference of 4px. So if you want to be lenitent and allow a 3px difference on the smaller edge, you'd write something like

    abs($img->width()*3/4 - $img->height()) <= 3
    

    whereas if you want to be strict and have the 3px threshold on the larger edge, you'd instead write

    abs($img->width() - $img->height()*4/3) <= 3
    

    Doing the multiplication before the division (i.e. (height*4)/3 instead of height*(4/3) should avoid some of the surprises floating point arithmetic can bestow on you, and should make the case of equality a bit more reliable. If you decide to treat the aspect ratio as a single number, be aware that e.g. 4/3 has no exact representation as a binary floating point number, so do expect rounding errors. Consider changing your threshold to 3.5 or 3.1 or whatever, so that a mathematically exact difference of 3px won't fail due to rounding.