调整大小然后裁剪PHP

好吧,基本上我希望所有图像都是170x170px的正方形.
因此,如果图像不是正方形,我希望它被调整大小,然后在中间裁剪..

我花了很多时间玩这个,我无处可去..我已经得到它来裁剪更大图像的一部分等,但我特别需要图像调整大小,然后裁剪..

任何帮助将不胜感激.

// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];

if($sw > $sh) // Horizontal Rectangle?
{
  $newwidth = ($sw/$sh)*170;
  $newheight=170;   
  $x_pos = ($sw - $sh) / 2;
  $x_pos = ceil($x_pos);
  $y_pos=0;
}

else if($sh > $sw) // Vertical Rectangle?
{
  $newheight = ($sh/$sw)*170;
  $newwidth=170;
  $y_pos = ($sh - $sw) / 2;
  $y_pos = ceil($y_pos);
  $x_pos=0;
}
else //Already Square
{
  $newheight=170;
  $newwidth=170;
}

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
  // We get errors from PHP's ImageCreate functions...
  // So let's echo back the contents of the actual image.
  readfile ($img);
} else {
  // Create the resized image destination
  $thumb = @ImageCreateTrueColor (170, 170);
  // Copy from image source, resize it, and paste to image destination
  imagecopyresampled($thumb, $im, 0, 0, 180, $y_pos, 170, 170, $newwidth, 
    $newheight);
}

解决方法:

需要一些工作,但它应该给你足够的开始.

function crop($filename, $width, $height)
{
    // image resource, assuming it's PNG
    $resource = imagecreatefrompng($filename);
    // resource dimensions
    $size = array(
        0 => imagesx($resource),
        1 => imagesy($resource),
    );
    // sides
    $longer  = (int)($size[0]/$width > $size[1]/$height);
    $shorter = (int)(!$longer);
    // ugly hack to avoid condition for imagecopyresampled()
    $src = array(
        $longer  => 0,
        $shorter => ($size[$shorter]-$size[$longer])/2,
    );
    // new image resource
    $new = imagecreatetruecolor($width, $height);
    // do the magic
    imagecopyresampled($new, $resource,
        0,  0,
        $src[0], $src[1],
        $width, $height,
        $size[$longer], $size[$longer]
    );

    // save it or something else :)
}

编辑:试图解释上面的“丑陋的黑客”.

有两个参数是$src_x和$src_y,取自manual

imagecopyresampled() will take an rectangular area from src_image of
width src_w and height src_h at position (src_x,src_y) and place it in
a rectangular area of dst_image of width dst_w and height dst_h at
position (dst_x,dst_y).

意思是如果$filename的宽度更长,src_x必须为0,如果height更长,src_y必须为0.转换为代码,它看起来像这样:

$src = ($size[$shorter]-$size[$longer])/2;

if ( $longer === 1 )
{
    imagecopyresampled($new, $resource,
        0,  0,
        $src, 0,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}
else
{
    imagecopyresampled($new, $resource,
        0,  0,
        0, $src,
        $width, $height,
        $size[$longer], $size[$longer]
    );
}
上一篇:想要渲染图像而不使用PHP GD库将其保存到磁盘


下一篇:PHP GD文本不流畅