【问题标题】:Crop a Square Image of 450x450 into 9 pieces of 150x150 each, using PHP使用 PHP 将 450x450 的方形图像裁剪成 9 块,每块 150x150
【发布时间】:2014-09-13 10:57:41
【问题描述】:

我有一个 450x450 像素的源图像。我想使用 PHP 将它裁剪成 9 个 150x150 的片段。
我正在使用以下代码。
我得到 9 张图像,但裁剪不合适。 这是屏幕截图:



最后一张是我正在使用的源图像。
这是我的代码。

<?php

$targ_w = $targ_h = 150;
$jpeg_quality = 25;

$src = "puzzleimages/puzzle2.jpg";

$y = 0;
$y2 = 150;
$x = 0;
$x2 = 150;

$i = 3;
$name = 0;
while( $i-- ){
    $j = 3;

    while( $j-- ){


        $img_r = imagecreatefromjpeg($src);
        $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

        imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$x2,$y2);

        //header('Content-type: image/jpeg');
        imagejpeg($dst_r,'puzzleimages/'.++$name.'.jpg', $jpeg_quality);

        $x += 150;
        $x2 += 150;

    }


    $y += 150;
    $y2 += 150;
    $x = 0;
    $x2 = 150;

}

?>

谁能指出出了什么问题?

【问题讨论】:

  • exec(sprintf("convert -crop 150x150 %s", escapeshellarg($fn))) 将是生成图块的更简单替代方法。
  • 我在 imagemagick 中做了一些非常相似的事情,你有那个库吗?
  • 我从未使用过任何外部库,所以我避免使用 imagemagick。

标签: php imagecreatefrompng


【解决方案1】:

我认为您不需要不断更改源宽度/高度,它应该一直是 150。试试这个:

imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$targ_w,$targ_h);

【讨论】:

    【解决方案2】:
    bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int$dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
    

    参考Php文档,唯一需要更改的参数是src_xsrc_y。由于您更改了 x2y2,因此将应用以下内容:

    如果源和目标坐标以及宽度和高度不同,则会对图像片段进行适当的拉伸或收缩。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 2013-02-16
      相关资源
      最近更新 更多