# 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:

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

So what is the solution for this?

My thoughts about the problem:

- For
`NxN`

image, ratio equals to 1. (`N`

=`N`

of course) - For 9 pixels and ratio 1:
`x = y = sqrt(9) = 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)`

.

## Answer

## 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:

## Answer

## Solution:

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

Check the size, yes, over 10MB

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

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

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

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

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