php gd pixelate太尖锐了

时间:2012-01-24 02:10:25

标签: php gd pixel

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

$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 个答案:

答案 0 :(得分: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 :(得分:1)

使用imagecopyresampled()代替imagecopyresized()

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