我如何在PHP中使用imagick?(调整大小和裁剪)

new*_*roo 14 php resize crop imagick

我使用imagick作为缩略图裁剪,但有时裁剪的缩略图缺少图像的顶部(头发,眼睛).

我想要调整图像大小然后裁剪它.另外,我需要保持图像大小比例.

下面是我用于裁剪的php脚本:

$im = new imagick( "img/20130815233205-8.jpg" );
$im->cropThumbnailImage( 80, 80 );
$im->writeImage( "thumb/th_80x80_test.jpg" );
echo '<img src="thumb/th_80x80_test.jpg">';
Run Code Online (Sandbox Code Playgroud)

谢谢..

Mar*_*ler 30

这项任务并不容易,因为"重要"部分可能并不总是在同一个地方.仍然,使用这样的东西

$im = new imagick("c:\\temp\\523764_169105429888246_1540489537_n.jpg");
$imageprops = $im->getImageGeometry();
$width = $imageprops['width'];
$height = $imageprops['height'];
if($width > $height){
    $newHeight = 80;
    $newWidth = (80 / $height) * $width;
}else{
    $newWidth = 80;
    $newHeight = (80 / $width) * $height;
}
$im->resizeImage($newWidth,$newHeight, imagick::FILTER_LANCZOS, 0.9, true);
$im->cropImage (80,80,0,0);
$im->writeImage( "D:\\xampp\\htdocs\\th_80x80_test.jpg" );
echo '<img src="th_80x80_test.jpg">';
Run Code Online (Sandbox Code Playgroud)

(测试)

应该管用.cropImage参数(0和0)确定裁剪区域的左上角.因此,使用这些功能可以获得保留在图像中的不同结果.


Sta*_*pov 6

根据Martin的回答,我做了一个更通用的功能,可以调整Imagick图像大小并裁剪图像以适合给定的宽度和高度(即,行为完全符合CSS background-size: cover声明):

/**
 * Resizes and crops $image to fit provided $width and $height.
 *
 * @param \Imagick $image
 *   Image to change.
 * @param int $width
 *   New desired width.
 * @param int $height
 *   New desired height.
 */
function image_cover(Imagick $image, $width, $height) {
  $ratio = $width / $height;

  // Original image dimensions.
  $old_width = $image->getImageWidth();
  $old_height = $image->getImageHeight();
  $old_ratio = $old_width / $old_height;

  // Determine new image dimensions to scale to.
  // Also determine cropping coordinates.
  if ($ratio > $old_ratio) {
    $new_width = $width;
    $new_height = $width / $old_width * $old_height;
    $crop_x = 0;
    $crop_y = intval(($new_height - $height) / 2);
  }
  else {
    $new_width = $height / $old_height * $old_width;
    $new_height = $height;
    $crop_x = intval(($new_width - $width) / 2);
    $crop_y = 0;
  }

  // Scale image to fit minimal of provided dimensions.
  $image->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 0.9, true);

  // Now crop image to exactly fit provided dimensions.
  $image->cropImage($new_width, $new_height, $crop_x, $crop_y);
}
Run Code Online (Sandbox Code Playgroud)

希望这可以对某人有所帮助。

  • ``imagick::FILTER_LANCZOS`` 应该是 ``\Imagick::FILTER_LANCZOS`` (2认同)
  • 最后一行 `$image-&gt;cropImage($new_width, $new_height, ...` 应该是 `$image-&gt;cropImage($width, $height, ...` (2认同)