php - Resize image to approximate number of pixels


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:


So what is the solution for this?

My thoughts about the problem:

  1. ForNxN image, ratio equals to 1. (N=N of course)
  2. For 9 pixels and ratio 1:x = y = sqrt(9) = 3
  3. ForNxM image, whereN!=M andM∨N=1 the ratio is either 1/M or N/1. Forp pixels the image will then havex=p{-code-11} or vice versa.

From point 3. I do know that both X and Y are values between1 andsqrt(p).




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



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?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.