PHP GD像素化太锐利

16

我有一个用于像素化图像的脚本,脚本能正常运行,但我想要更加平滑的边缘:

$imgfile = 'batman.jpg';
$image = ImageCreateFromJPEG($imgfile);
$imagex = imagesx($image);
$imagey = imagesy($image);
$pixelate_amount = 10;
$tmpImage = ImageCreateTrueColor($imagex, $imagey);
imagecopyresized($tmpImage, $image, 0, 0, 0, 0, round($imagex / $pixelate_amount), round($imagey / $pixelate_amount), $imagex, $imagey);
$pixelated = ImageCreateTrueColor($imagex, $imagey);
imagecopyresized($pixelated, $tmpImage, 0, 0, 0, 0, $imagex, $imagey, round($imagex / $pixelate_amount), round($imagey / $pixelate_amount));
header("Content-Type: image/jpeg");
imageJPEG($pixelated, "", 100);

我有:

before

这个会产生:

after

我是否遗漏了什么?

2个回答

20

这是你需要的内容(我目前使用的脚本)。这个脚本基于http://www.talkphp.com/19670-post1.html上的脚本:

function convertToPixel($im, $size) {
  $size = (int)$size;
  $sizeX = imagesx($im);
  $sizeY = imagesy($im);

  if($sizeX < 3 && $sizeX < 3) { // or you can choose any size you want
    return;
  }
  for($i = 0;$i < $sizeX; $i += $size) {
    for($j = 0;$j < $sizeY; $j += $size) {
      $colors = Array('alpha' => 0, 'red' => 0, 'green' => 0, 'blue' => 0, 'total' => 0);
      for($k = 0; $k < $size; ++$k) {
        for($l = 0; $l < $size; ++$l) {
          if($i + $k >= $sizeX || $j + $l >= $sizeY) {
            continue;
          }
          $color = imagecolorat($im, $i + $k, $j + $l);
          imagecolordeallocate($im, $color);
          $colors['alpha'] += ($color >> 24) & 0xFF;
          $colors['red'] += ($color >> 16) & 0xFF;
          $colors['green'] += ($color >> 8) & 0xFF;
          $colors['blue'] += $color & 0xFF;
          ++$colors['total'];
        }
      }
      $color = imagecolorallocatealpha($im,  $colors['red'] / $colors['total'],  $colors['green'] / $colors['total'],  $colors['blue'] / $colors['total'],  $colors['alpha'] / $colors['total']);
      imagefilledrectangle($im, $i, $j, ($i + $size - 1), ($j + $size - 1), $color);
    }
  }
}
header('Content-type: image/jpg');
$im = imagecreatefromjpeg($imgfile);
convertToPixel($im, 15);
imagejpeg($im, '', 100);

这将产生:

smooth

您还可以更改传递给convertToPixel的值以修改像素大小。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接