在php

时间:2019-02-14 09:22:19

标签: php php-gd

我必须创建动态的学生证图像。添加此图像对象放入学生资料照片中。但是,学生图像的颜色已更改。

如何用原始颜色放置学生个人资料照片?

这是我的代码:

header("Content-Type: image/jpeg");
$im = @imagecreate(602, 980)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);

$card_header = imagecreatefromjpeg('img/card/card-header.jpg');
imagecopy($im, $card_header, 0, 0, 0, 0, 602, 253);

$card_footer = imagecreatefromjpeg('img/card/card-footer.jpg');
imagecopy($im, $card_footer, 0, 834, 0, 0, 602, 146);

$student_photo = 'img/card/girls-profile.jpg'; //imagecreatefromjpeg($studentlist[0]->getCardPhoto());
// Get new sizes
list($width, $height) = getimagesize($student_photo);
$newwidth = 180;
$newheight = 220;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($student_photo);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagecopy($im, $thumb, 220, 220, 0, 0, $newwidth, $newheight);

imagejpeg($im, "uploads/card/test.jpeg");
imagedestroy($im);

标题图片:

enter image description here

脚注:

enter image description here

个人资料图片:

enter image description here

这是我的输出图像:

enter image description here

1 个答案:

答案 0 :(得分:1)

主要问题是您的$im也必须是真彩色图像。 其次,您必须实际填补您的背景。 您也可以跳过创建$thumb并将其直接调整大小的操作复制到$im中。

这里有一个有效的版本(我更改了在我的机器上对其进行测试的路径)

<?php

    header('Content-Type: image/jpeg');

    $im = @imagecreatetruecolor(602, 980) // you want to create a truecolorimage here
    or die("Cannot Initialize new GD image stream");

    $background_color = imagecolorallocate($im, 255, 255, 255);
    imagefill($im, 0, 0, $background_color); // you have to actually use the allocated background color

    $card_header = imagecreatefromjpeg('card-header.jpg');
    imagecopy($im, $card_header, 0, 0, 0, 0, 602, 253);

    $card_footer = imagecreatefromjpeg('card-footer.jpg');
    imagecopy($im, $card_footer, 0, 834, 0, 0, 602, 146);

    $student_photo = 'girls-profile.jpg';

    // Get new sizes
    list($width, $height) = getimagesize($student_photo);
    $newwidth = 180;
    $newheight = 220;

    // Load
    //$thumb = imagecreatetruecolor($newwidth, $newheight); // you can skip allocating extra memory for a intermediate thumb
    $source = imagecreatefromjpeg($student_photo);

    // Resize
    imagecopyresized($im, $source, 220, 220, 0, 0, $newwidth, $newheight, $width, $height); // and copy the thumb directly

    imagejpeg($im);

    imagedestroy($im);
    // you should also destroy the other images
    imagedestroy($card_header);
    imagedestroy($card_footer);
    imagedestroy($source);

请记住,您的个人资料图片电流会失真,但您可能无法确保个人资料图片始终具有正确的宽高比,或者可能想要裁剪图像。有关更多详细信息,请参见此处:PHP crop image to fix width and height without losing dimension ratio