用PHP裁剪图像

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


想法是,在裁剪之前,我将能够使每个图像的大小大致相同,以便每次都能获得良好的效果


代码是


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


动漫人物
浏览 387回答 3
3回答

宝慕林4294392

如果要生成缩略图,则必须首先使用调整图像大小imagecopyresampled();。您必须调整图像的大小,以使图像较小侧的尺寸等于拇指的相应侧。例如,如果源图像为1280x800px,拇指为200x150px,则必须将图像的尺寸调整为240x150px,然后将其裁剪为200x150px。这样一来,图像的长宽比就不会改变。这是创建缩略图的一般公式:$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 ){&nbsp; &nbsp;// If image is wider than thumbnail (in aspect ratio sense)&nbsp; &nbsp;$new_height = $thumb_height;&nbsp; &nbsp;$new_width = $width / ($height / $thumb_height);}else{&nbsp; &nbsp;// If the thumbnail is wider than the image&nbsp; &nbsp;$new_width = $thumb_width;&nbsp; &nbsp;$new_height = $height / ($width / $thumb_width);}$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );// Resize and cropimagecopyresampled($thumb,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$image,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 - ($new_width - $thumb_width) / 2, // Center the image horizontally&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 - ($new_height - $thumb_height) / 2, // Center the image vertically&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0, 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$new_width, $new_height,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$width, $height);imagejpeg($thumb, $filename, 80);还没有测试过,但是应该可以。编辑现在经过测试并可以工作。
打开App,查看更多内容
随时随地看视频慕课网APP