当前位置: 首页 > 面试题库 >

用PHP裁剪图像

易宣
2023-03-14
问题内容

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

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

代码是

<?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();。您必须调整图像的大小,以使图像较小侧的尺寸等于拇指的相应侧。

例如,如果源图像为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 )
{
   // 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);

还没有测试过,但是 应该 可以。

编辑

现在经过测试并可以工作。



 类似资料:
  • 我试图在从图库中选择图像后使用intent来裁剪图像。以下是我的代码片段 在这里,我使用PICK_IMAGE_REQUEST意图句柄调用上面的代码段 由于我在裁剪后使用了相同的意图,即PICK_IMAGE_REQUEST,可能会出现什么问题

  • 问题内容: 我想用PHP裁剪图像并保存文件。我知道您应该使用GD库,但我不确定如何使用。有任何想法吗? 谢谢 问题答案: 您可以用来裁剪图像的必需部分。该命令如下所示: 来自PHP.net的代码- 从源图像中裁剪出一个80x40像素的图像

  • 我将<code>背景 1.back_xml: 2.瓷砖.xml 现在,我将back.xml设置为< code >背景以< code>LinearLayout工作正常。 我需要有一个圆角,以及它的边框。但是我只有圆角的边框,而不是图像,我的代码中有什么问题吗? 这是我的照片:

  • 本节,我们将裁剪图像的一部分,然后把其结果绘制到画布上。 图3-2 裁剪图像 绘制步骤 按照以下步骤,裁剪图像的一部分,再把结果绘制到画布: 1. 定义画布上下文: window.onload  = function(){ var canvas  = document.getElementById("myCanvas"); var context  = canvas.getContext

  • 问题内容: 是否可以在PHP中删除图像周围的空格? 注意:澄清一下,我的意思是像photoshops装饰功能。 谢谢。 问题答案: 要修剪所有空白,就像您所说的那样,围绕图像的有趣部分,首先我们找出“空白”在哪里停止,然后我们复制这些边界内的所有内容。 我的旧示例假设图像的所有侧面都具有相同的“边框”,只是为了澄清注释:)

  • 问题内容: 我正在尝试裁剪图像,然后将裁剪后的图像粘贴到另一个图像的中心。理想情况下,我希望裁切后的图像小于粘贴的图像,以便在粘贴的图像周围有一个边框,但我不知道这样是否可行。 这是我尝试过的方法(以及由此产生的错误消息): 我可以看到“区域”的大小已设为(0,0),但我不明白为什么。 任何对此的帮助将非常感谢 问题答案: 裁剪方法的PIL文档指出: 返回当前图像的矩形区域。该框是一个四元组,定义