David David - 1 year ago 102
PHP Question

Centering Image on Uploaded Image in PHP

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.

Answer Source

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:

$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");


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download