Centering Image on Uploaded Image in PHP

2019-09-06 14:10发布

问题:

I have users uploading always-square images (of variable dimensions, but always square), and I would like to overlay my own image (also, as it was, a square and of fixed dimensions) in the middle of the square image, regardless of the size.

I know I could use GD and play with the dimensions, but is there an way to auto-center it with fewer lines of code?

I don't need anything fancy, just an image put into the center of another image.

回答1:

I'm confused whether you're asking how to do this in GD, or an alternative to GD. If you wanted to use the GD library, you could use the imagecopy() function and attempt something like the following:

<?php
$uploaded = imagecreatefrompng("../image.png"); //user uploaded
$watermark = imagecreatefrompng("../logo.png"); //watermark or logo

$x = imagesx($uploaded) / 2 - imagesx($watermark) / 2;
$y = imagesy($uploaded) / 2 - imagesy($watermark) / 2;

imagecopy($uploaded, $watermark, $x, $y, 0, 0, imagesx($watermark), imagesy($watermark));

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

imagedestroy($uploaded);
imagedestroy($watermark);

Otherwise, could you be a bit more specific on what you want? I mean, you could do it with different libraries like ImageMagick, but there aren't necessarily better ways to do it.



标签: php image gd