在PHP中裁剪图像 [英] Crop image in PHP

查看:82
本文介绍了在PHP中裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below crops the image well, which is what i want, but for larger images, it wotn work as well. Is there any way of 'zooming out of the image'

理想情况下,我可以在裁剪之前使每张图像的大小大致相同,这样每次都可以获得良好的效果

Idealy i would be able to have each image roughly the same size before cropping so that i would get good results each time

代码为

<?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>';

推荐答案

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

If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.

例如,如果源图像为1280x800px,拇指为200x150px,则必须将图像的尺寸调整为240x150px,然后将其裁剪为200x150px.这样一来,图像的长宽比就不会改变.

For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.

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

Here's a general formula for creating thumbnails:

$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);

还没有测试过,但是应该有效.

Haven't tested this but it should work.

编辑

现在已测试并且可以正常工作.

Now tested and working.

这篇关于在PHP中裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆