如何在添加叠加层之前裁剪和成像? (GD)(PHP)

时间:2011-05-10 08:15:27

标签: php gd

到目前为止我的代码(它为youtube缩略图创建了一个叠加层):

<?php
header("Content-type:image/png");
$background=imagecreatefromjpeg("http://img.youtube.com/vi/".$_GET['v']."/default.jpg");
$insert=imagecreatefrompng("play.png");
imagecolortransparent($insert,imagecolorat($insert,0,0));
$insert_x=imagesx($insert);
$insert_y=imagesy($insert);
imagecopymerge($background,$insert,5,57,0,0,$insert_x,$insert_y,100);
imagepng($background,NULL);

输出图像是120x90px,但我需要它有90x90px。

任何人都知道这有可能吗?

提前致谢!

2 个答案:

答案 0 :(得分:3)

http://www.johnconde.net/blog/cropping-an-image-with-php-and-the-gd-library/

<?php

header("Content-type:image/png");

$background = imagecreatefromjpeg("http://img.youtube.com/vi/".$_GET['v']."/default.jpg");

$insert = imagecreatefrompng("play.png");

imagecolortransparent($insert,imagecolorat($insert,0,0));

list($current_width, $current_height) = getimagesize($background);

$left = 0;
$top = 0;

$crop_width = 90;
$crop_height = 90;

$canvas = imagecreatetruecolor($crop_width, $crop_height);

$current_image = $background;

imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);

imagecopymerge($canvas,$insert,5,57,0,0,$current_width,$current_height,100);

imagepng($canvas);

?>

如果不对其进行评论,请尝试它应该有效。

答案 1 :(得分:0)

这是从我写的用于创建方形缩略图的函数中获取的。您可能会发现我为自己写的评论很有帮助。根据您的需要(即,如果您无法承担关于传入图像的类型和尺寸的假设),您可能需要添加其他检查。为了避免碎片或拉伸的缩略图,我们采用图像的中心部分,最有可能包含可区分为源坐标的东西。

基本思路是:由于imagecopyresampledimagecopyresized也允许您指定目标和源坐标,因此您只能将原始图像的一部分复制到新的画布并保存(或直接输出到浏览器)。为了避免粉碎或拉伸尺寸,我们采用原始图像的中心部分,最有可能包含可区分的内容。

//assuming you have already merged your $background image with your overlay at this point

//original dimensions
$original_width = imagesx($background);
$original_height = imagesy($background);

//new dimensions
$new_width = 90;
$new_height = 90;

//the center of the rectangular image
$center = $original_width/2, $original_height/2

//the coordinates from where to start on the original image 
//assuming you want to crop the center part
$src_x = floor(($original_width/2) - ($new_width/2)); 
$src_y = floor(($original_height/2) - ($new_height/2)); 

//create a new canvas with the new desired width, height
$temp = imagecreatetruecolor(90,90);

//copy the large image to this new canvas
imagecopyresampled($temp,$background,0,0,$src_x,$src_y,$new_width,$new_height,$original_width,$original_height);
//from right to left: source image, destination image, dest x, dest y,
//source x, source y, new width, new height, original width, original height

//save the canvas as an image
imagepng($temp);

这可以通过首先取一个相对于它的大小的中心部分然后然后将其缩小到新画布来改进处理更大的图像。