# php - Resize image to approximate number of pixels

212

I want to prevent JPG images added to email attachment be 250kB or smaller. I have discovered, that for JPG images, this is very non-linear, so I did some tests and decided that 2000000 pixels is maximum that I can allow.

So now, I need to resize every image to 2000000pixels or a value as close as possible. This sounds quite impossible however:

``````{-code-1}
``````

So what is the solution for this?

1. For`NxN` image, ratio equals to 1. (`N`=`N` of course)
2. For 9 pixels and ratio 1:`x = y = sqrt(9) = 3`
3. For`NxM` image, where`N!=M` and`M∨N=1` the ratio is either 1/M or N/1. For`p` pixels the image will then have`x=p``{-code-11}` or vice versa.

From point 3. I do know that both X and Y are values between`1` and`sqrt(p)`.

967

#### Solution:

So, after all, there is an answer on another board (since you guys here on SO don't do math obviously).

And this is how the program implementation of the equation looks like:

``````function image_resize_to_pixel_count(\$im, \$pixels) {
\$x = imagesx(\$im);
\$y = imagesy(\$im);

\$S = \$pixels; //I use S here to remind you, that it's analogic to rectangle area

//Define the coefficient for \$x, \$y (old image dimensions)
\$h = sqrt(\$S/(\$x*\$y));

\$x2 = round(\$h*\$x);
\$y2 = round(\$h*\$y);

//Standard resize to x, y procedure follows from here
}
``````
413

#### Solution:

Make a random image that has too many pixels and too many bytes for your liking:

``````convert -size 3000x1000 xc:red +noise random image.jpg
``````

Check the size, yes, over 10MB

``````-rw-r--r--   1 mark  staff  10454067  9 Jan 12:03 image.jpg
``````

Now, either reduce to 250kB whilst retaining pixel dimensions:

``````convert image.jpg -define jpeg:extent=250k result.jpg
``````

Check file size in bytes, yes, now around 250kB:

``````[email protected]  1 mark  staff    259356  9 Jan 12:08 result.jpg
``````

Or, reduce pixel dimensions till total number of pixels under 2,000,000:

``````convert image.jpg -resize [email protected] result.jpg
``````

Check dimensions, yes under 2,000,000 pixels and still in same ratio of 3:1

``````identify result.jpg
result.jpg JPEG 1732x1154 1732x1154+0+0 8-bit sRGB 2.70352MiB 0.000u 0:00.000
``````

See, we can do maths - just slowly!!! What's 5 years?

People are also looking for solutions to the problem: php - When to modify and secure variables passed to a URL?

Source