在PHP中裁剪图像

时间:2009-12-06 17:39:59

标签: php gd crop

下面的代码可以很好地裁剪图像,这正是我想要的,但对于较大的图像,它也可以正常工作。有没有办法'缩小图像'

想象一下,我可以在裁剪前让每张图像的大小大致相同,这样每次都能获得好成绩

代码是

<?php

$image = $_GET['src']; // the image to crop
$dest_image = 'images/cropped_whatever.jpg'; // make sure the directory is writeable

$img = imagecreatetruecolor('200','150');
$org_img = imagecreatefromjpeg($image);
$ims = getimagesize($image);
imagecopy($img,$org_img, 0, 0, 20, 20, 200, 150);
imagejpeg($img,$dest_image,90);
imagedestroy($img);
echo '<img src="'.$dest_image.'" ><p>';

9 个答案:

答案 0 :(得分:119)

如果您要尝试生成缩略图,则必须先使用imagecopyresampled();调整图像大小。您必须调整图像大小,使图像较小边的大小等于拇指的相应边。

例如,如果源图像为1280x800像素且拇指为200x150像素,则必须将图像大小调整为240x150像素,然后将其裁剪为200x150像素。这样可以使图像的宽高比不会改变。

以下是创建缩略图的通用公式:

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';

$thumb_width = 200;
$thumb_height = 150;

$width = imagesx($image);
$height = imagesy($image);

$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;

if ( $original_aspect >= $thumb_aspect )
{
   // If image is wider than thumbnail (in aspect ratio sense)
   $new_height = $thumb_height;
   $new_width = $width / ($height / $thumb_height);
}
else
{
   // If the thumbnail is wider than the image
   $new_width = $thumb_width;
   $new_height = $height / ($width / $thumb_width);
}

$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

// Resize and crop
imagecopyresampled($thumb,
                   $image,
                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                   0, 0,
                   $new_width, $new_height,
                   $width, $height);
imagejpeg($thumb, $filename, 80);

尚未对此进行测试,但工作。

修改

现在已经过测试和工作。

答案 1 :(得分:13)

imagecopyresampled()将从位置$src_image的{​​{1}}宽度$src_w和高度$src_h取一个矩形区域,并将其放置在{{($src_x, $src_y)的矩形区域中位于$dst_image的宽度$dst_w和高度$dst_h的1}}。

如果源和目标坐标以及宽度和高度不同,将执行图像片段的适当拉伸或收缩。坐标指的是左上角。

此功能可用于复制同一图像中的区域。但如果区域重叠,结果将无法预测。

- 编辑 -

如果($dst_x, $dst_y)$src_w分别小于$src_h$dst_w,则会放大拇指图像。否则会缩小。

$dst_h

答案 2 :(得分:1)

动态改进了PHP中的Crop图像功能。

http://www.example.com/cropimage.php?filename=a.jpg&newxsize=100&newysize=200&constrain=1

cropimage.php中的代码

$basefilename = @basename(urldecode($_REQUEST['filename']));

$path = 'images/';
$outPath = 'crop_images/';
$saveOutput = false; // true/false ("true" if you want to save images in out put folder)
$defaultImage = 'no_img.png'; // change it with your default image

$basefilename = $basefilename;
$w = $_REQUEST['newxsize'];
$h = $_REQUEST['newysize'];

if ($basefilename == "") {
    $img = $path . $defaultImage;
    $percent = 100;
} else {
    $img = $path . $basefilename;

    $len = strlen($img);
    $ext = substr($img, $len - 3, $len);
    $img2 = substr($img, 0, $len - 3) . strtoupper($ext);
    if (!file_exists($img)) $img = $img2;
    if (file_exists($img)) {
        $percent = @$_GET['percent'];
        $constrain = @$_GET['constrain'];
        $w = $w;
        $h = $h;
    } else if (file_exists($path . $basefilename)) {
        $img = $path . $basefilename;
        $percent = $_GET['percent'];
        $constrain = $_GET['constrain'];
        $w = $w;
        $h = $h;
    } else {

        $img = $path . 'no_img.png';    // change with your default image
        $percent = @$_GET['percent'];
        $constrain = @$_GET['constrain'];
        $w = $w;
        $h = $h;

    }

}

// get image size of img
$x = @getimagesize($img);

// image width
$sw = $x[0];
// image height
$sh = $x[1];

if ($percent > 0) {
    // calculate resized height and width if percent is defined
    $percent = $percent * 0.01;
    $w = $sw * $percent;
    $h = $sh * $percent;
} else {
    if (isset ($w) AND !isset ($h)) {
        // autocompute height if only width is set
        $h = (100 / ($sw / $w)) * .01;
        $h = @round($sh * $h);
    } elseif (isset ($h) AND !isset ($w)) {
        // autocompute width if only height is set
        $w = (100 / ($sh / $h)) * .01;
        $w = @round($sw * $w);
    } elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
        // get the smaller resulting image dimension if both height
        // and width are set and $constrain is also set
        $hx = (100 / ($sw / $w)) * .01;
        $hx = @round($sh * $hx);

        $wx = (100 / ($sh / $h)) * .01;
        $wx = @round($sw * $wx);

        if ($hx < $h) {
            $h = (100 / ($sw / $w)) * .01;
            $h = @round($sh * $h);
        } else {
            $w = (100 / ($sh / $h)) * .01;
            $w = @round($sw * $w);
        }
    }
}

$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($w, $h);
    // Copy from image source, resize it, and paste to image destination
    @ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);

    //Other format imagepng()

    if ($saveOutput) { //Save image
        $save = $outPath . $basefilename;
        @ImageJPEG($thumb, $save);
    } else { // Output resized image
        header("Content-type: image/jpeg");
        @ImageJPEG($thumb);
    }
}

答案 3 :(得分:0)

$image = imagecreatefromjpeg($_GET['src']);

需要替换为:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

因为imagecreatefromjpeg()期待一个字符串 这对我有用。

<强> REF:
http://php.net/manual/en/function.imagecreatefromjpeg.php

答案 4 :(得分:0)

php 5.5有一个imagecrop函数http://php.net/manual/en/function.imagecrop.php

答案 5 :(得分:0)

  

有没有办法'缩小图像'。

对于较小的服务器端/ PHP 方法,这是一个不错的jQuery plugin

可以进行所有必要的调整 - 客户端上的缩放和宽高比,种类 - ,并将最终的裁剪区域位置和大小发送到服务器端用于最终操作和保存。 docs说得足以让你摇摆不定。

答案 6 :(得分:0)

HTML代码: -

enter code here
  <!DOCTYPE html>
  <html>
  <body>

  <form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="image" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
 </form>

 </body>
 </html>

upload.php的

enter code here
<?php 
      $image = $_FILES;
      $NewImageName = rand(4,10000)."-". $image['image']['name'];
      $destination = realpath('../images/testing').'/';
      move_uploaded_file($image['image']['tmp_name'], $destination.$NewImageName);
      $image = imagecreatefromjpeg($destination.$NewImageName);
      $filename = $destination.$NewImageName;

      $thumb_width = 200;
      $thumb_height = 150;

      $width = imagesx($image);
      $height = imagesy($image);

      $original_aspect = $width / $height;
      $thumb_aspect = $thumb_width / $thumb_height;

      if ( $original_aspect >= $thumb_aspect )
      {
         // If image is wider than thumbnail (in aspect ratio sense)
         $new_height = $thumb_height;
         $new_width = $width / ($height / $thumb_height);
      }
      else
      {
         // If the thumbnail is wider than the image
         $new_width = $thumb_width;
         $new_height = $height / ($width / $thumb_width);
      }

      $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

      // Resize and crop
      imagecopyresampled($thumb,
                         $image,
                         0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                         0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                         0, 0,
                         $new_width, $new_height,
                         $width, $height);
      imagejpeg($thumb, $filename, 80);
      echo "cropped"; die;
      ?>  

答案 7 :(得分:0)

您可以在(PHP 5> = 5.5.0,PHP 7)

中使用imagecrop函数

示例:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

答案 8 :(得分:-1)

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg'

必须替换为:

$image = imagecreatefromjpeg($_GET['src']);

然后它会起作用!