调整图像大小以近似像素数

问题描述 投票:0回答:2

我想阻止添加到电子邮件附件的JPG图像为250kB或更小。我发现,对于JPG图像,这是非线性的,所以我做了一些测试,并确定2000000像素是我可以允许的最大值。

所以现在,我需要将每个图像的大小调整为2000000pixels或尽可能接近值。但这听起来很不可能:

x2*y2 = 2000000
x2/y2 = x/y      //The aspect ratio must be the same

那么这个解决方案是什么?

我对这个问题的看法:

  1. 对于NxN图像,比率等于1.(当然N = N
  2. 对于9像素和比例1:x = y = sqrt(9) = 3
  3. 对于NxM图像,其中N!=MM∨N=1的比率为1 / M或N / 1。对于p像素,图像将具有x=p y=1,反之亦然。

从第3点开始。我知道X和Y都是1sqrt(p)之间的值。

php image-processing resize
2个回答
0
投票

所以,毕竟,another board有一个答案(因为你们这里的人们显然不做数学)。

这就是程序实现方程式如下:

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
}

0
投票

根据您的喜好制作一个具有太多像素和太多字节的随机图像:

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

检查尺寸,是的,超过10MB

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

现在,要么减少到250kB,同时保留像素尺寸:

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

检查文件大小,以字节为单位,是,现在大约250kB:

-rw-r--r--@  1 mark  staff    259356  9 Jan 12:08 result.jpg

或者,将像素尺寸减小到2,000,000以下的总像素数:

convert image.jpg -resize 2000000@ result.jpg

检查尺寸,是2,000,000像素,仍然是3:1的相同比例

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

看,我们可以做数学 - 慢慢来!什么是5年?

© www.soinside.com 2019 - 2024. All rights reserved.