PHP将PNG覆盖在JPG上,然后调整JPG的大小并将其定位为PNG的掩码


PHP Overlay PNG over JPG then resize and position JPG to mask of PNG

我需要拍摄背景和头盔的PNG,头盔是透明的,在中间。在PHP中,我将传递它的顶部和左侧坐标,以及JPG的宽度和高度。我想把JPG放在PNG下面,让它成为我发送的大小(根据我给它的大小调整大小),把它放在PNG下方的X和Y位置,让PNG最前面。换句话说,JPG的任何部分在PNG边界之外都会被剪切掉,生成的图像是以PNG宽度和高度覆盖在JPG上的PNG。

这是我目前拥有的,但它只是保存了头部应该在的黑色背景的头盔。

$photo1 = imagecreatefromjpeg($_POST['photo']);
    $foto1W = imagesx($photo1);
    $foto1H = imagesy($photo1);
    $photoFrameW = $res['width'];
    $photoFrameH = $res['height'];
    $photoFrame = imagecreatetruecolor($photoFrameW,$photoFrameH);
    imagecopyresampled($photoFrame, $photo1, 0, 0, 0, 0, $photoFrameW, $photoFrameH, $foto1W, $foto1H);
    $photo2 = imagecreatefrompng('images/casco.png');
    $foto2W = imagesx($photo2);
    $foto2H = imagesy($photo2);
    $photoFrame2W = '500';
    $photoFrame2H = '556';
    $photoFrame2    = imagecreatetruecolor($photoFrame2W,$photoFrame2H);
    $trans_colour   = imagecolorallocatealpha($photoFrame2, 0, 0, 0, 127);
    imagefill($photoFrame2, 0, 0, $trans_colour);
    imagecopyresampled($photoFrame2, $photo2, 0, 0, 0, 0, $photoFrame2W, $photoFrame2H, $foto2W, $foto2H);
    imagecopy($photoFrame2, $photoFrame, $res['left']+556, $res['top'], 0, 0, imagesx($photoFrame), imagesy($photoFrame));
    imagejpeg($photoFrame2, "fb_images/$codigo2.jpg");

我自己以以上为出发点解决了这个问题。问题是两倍,它把错误的图像放在上面,而我没有使用正确的位置来重新定位图像。在插入之前,我最终重新调整了图像的大小并重新定位了图像。然后在JPG的顶部插入PNG。

    $photo1 = imagecreatefromjpeg($_POST['photo']);
    $foto1W = imagesx($photo1);
    $foto1H = imagesy($photo1);
    $photoFrameW = $res['width'];
    $photoFrameH = $res['height'];
    $photoFrame = imagecreatetruecolor(500,556);
    imagecopyresampled($photoFrame, $photo1, $res['left'], $res['top']+556, 0, 0, $photoFrameW, $photoFrameH, $foto1W, $foto1H);
    $photo2 = imagecreatefrompng('images/casco.png');
    $foto2W = imagesx($photo2);
    $foto2H = imagesy($photo2);
    $photoFrame2W = '500';
    $photoFrame2H = '556';
    $photoFrame2    = imagecreatetruecolor($photoFrame2W,$photoFrame2H);
    $trans_colour   = imagecolorallocatealpha($photoFrame2, 0, 0, 0, 127);
    imagefill($photoFrame2, 0, 0, $trans_colour);
    imagecopyresampled($photoFrame2, $photo2, 0, 0, 0, 0, $photoFrame2W, $photoFrame2H, $foto2W, $foto2H);
    imagecopy($photoFrame, $photoFrame2, 0, 0, 0, 0, imagesx($photoFrame2), imagesy($photoFrame2));
    imagejpeg($photoFrame, "fb_images/$codigo2.jpg");