使用PHP GD将图像放置到另一个图像的中心 [英] Place an image to the center of another image using PHP GD

查看:131
本文介绍了使用PHP GD将图像放置到另一个图像的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图像放置在另一个图像的中心(水平和垂直),尺寸为700 * 350。我正在尝试使用以下代码。但是我的图像已经拉长了。

I need to place an image to the center of another image(both horizontally and vertically) with dimension 700*350. I'm trying with the following code. But I'm getting image as stretched.

@header("Content-Type: image/png");
$imageURL = "flower.jpg";

// create a transparent background image for placing the $imageURL image
$imageResource  = imagecreatetruecolor(700, 350);
imagesavealpha($imageResource, true);

$transparentColor  = imagecolorallocatealpha($imageResource, 0, 0, 0, 127);
imagefill($imageResource, 0, 0, $transparentColor);
$backgroundImage = imagecreatefromjpeg($imageURL);
list($width, $height) = getimagesize($imageURL);
imagecopyresampled($imageResource, $backgroundImage, 350, 175, 0, 0, 700, 350, $width, $height);
imagepng($imageResource, "newimage.jpg");

这不是图像的中心,而且当我运行此代码时,文件flower.jpg也会被删除。我在这做错了什么?

This is not centering the image and also the file flower.jpg is getting deleted when I run this code. What I'm doing wrong in this?

任何人都可以帮我解决这个问题吗?在此先感谢。

Can anyone please help me to fix this? Thanks in advance.

推荐答案

所以你需要这样的东西吗?

So you need something like this?

@header("Content-Type: image/png");
$imageURL = "flower.jpg";

// create a transparent background image for placing the $imageURL image
$imageResource  = imagecreatetruecolor(700, 350);
imagesavealpha($imageResource, true);

$transparentColor  = imagecolorallocatealpha($imageResource, 0, 0, 0, 127);
imagefill($imageResource, 0, 0, $transparentColor);
$backgroundImage = imagecreatefromjpeg($imageURL);
list($width, $height) = getimagesize($imageURL);

imagecopyresampled($imageResource, $backgroundImage, 175, 85, 0, 0, 350, 175, $width, $height);
imagepng($imageResource, "newimage.jpg");
imagedestroy($imageResource);
imagedestroy($backgroundImage);

您已将目标图像的中心指定为目标坐标和整个目标图像大小,而不是将要调整源图像大小的中心矩形的所需尺寸。

You had specified the center of the destination image as the destination coordinates and the whole destination image size instead of needed dimentions of the center rectangle into which the source image would be resized.

你还没有做 imagedestroy ,你完全应该这样做。

Also you didn't do imagedestroy, which you totally should.

这篇关于使用PHP GD将图像放置到另一个图像的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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