PHP imagecreate真彩色中心图像


PHP imagecreatetruecolour center image

我正在尝试将图像居中到

$thumbnail_gd_image = imagecreatetruecolor(600, 300);

命令。如果用户上传一张100x50的图片,我会生成一张600x300的大版本,背景为白色。现在,实际的图像被放置在左上角。我想把这张图片放在600x300的生成图片的中间。

另一方面,如果用户上传的图像大于600x300,那么我将调整大小以保持在这些参数范围内。

我正在构建一个图像上传/裁剪工具,但是可裁剪的区域总是宽度的两倍,所以我需要可用的裁剪区域在600x300以内,以便进行任何详细的裁剪。

这能做到吗?小于600x300的图像的中心?

感谢编辑:

尝试了下面的代码,但是它不喜欢它。

这是我的代码(可能不是最干净的,但它需要半工作快)。

if($source_image_width < 600 && $source_image_height < 300){
    $x = (600 / 2) - ($source_image_width / 2);
    $y = (300 / 2) - ($source_image_height / 2);
}else if($source_image_width > 600){
    $x = 0;
    if($source_image_height < 300){
        $y = (300 / 2) - ($source_image_height / 2);
    }else{
        $y = 0; 
    }
}else if($source_image_height > 300){
    if($source_image_width < 600){
        $x = (600 / 2) - ($source_image_width / 2);
    }else{
        $x = 0;
    }
    $y = 0;
}else{
    $x = 0;
    $y = 0;
}

上面的代码将一个400宽x 800高的图像放置在中心的左边(大约100px)。任何图像的高度都可以正常工作,但宽度不行。

你可以试试:

$W = 600;
$H = 300;
$im = imagecreatefromjpeg($filename);
list($w,$h) = getimagesize($filename);
$x = ($W / 2) - ($w/2);
$y = ($H / 2) - ($h/2);
$newIm = imagecreatetruecolor($new_w, $new_h);
// i know I could have used a better function for this, but...
imagecopyresampled($newIm, $im, $x, $y, 0, 0, $w, $h, $w, $h);
header("Content-type: image/jpeg");
imagejpeg($thumb);

我没有时间去测试它(抱歉),但是它应该可以工作,如果不能,告诉我,我会调试它。

编辑1:

对于大图像,必须从中裁剪。你所要做的可能只是

$W = 600;
$H = 300;
$im = imagecreatefromjpeg($filename);
list($w,$h) = getimagesize($filename);
$x = ($W / 2) - ($w/2);
$y = ($H / 2) - ($h/2);
$x = sqrt($x * $x);
$y = sqrt($y * $y);
$newIm = imagecreatetruecolor($new_w, $new_h);
// i know I could have used a better function for this, but...
imagecopyresampled($newIm, $im, $W > $w ? $x : 0, $W > $w ? $y : 0, $W > $w ? 0 : $x, $W > $w ? 0 : $y, $w, $h, $w, $h);
header("Content-type: image/jpeg");
imagejpeg($thumb);
试一试,让我知道结果。然而,我没有测试它,它可能会以史诗般的方式失败。