php gd 像素化太锐利

2022-08-31 01:03:20

我有这个脚本来像素化我的图像脚本正在工作,但我想要更平滑的边缘:

$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

我错过了什么吗?


答案 1

这是你需要的(我目前使用的脚本)。此脚本基于 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


答案 2

请代替 使用 。imagecopyresampled()imagecopyresized()

http://php.net/manual/en/function.imagecopyresampled.php


推荐