在 php 中使用 imagecreate 更改了图像颜色

Image color changed with imagecreate in php

我必须创建动态学生证图像。添加将此图片 object 放入学生个人资料照片中。但是,学生图像颜色发生了变化。

如何将学生头像置为原色?

这是我的代码:

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

Header 图片:

页脚图片:

个人资料图片:

这是我的输出图像:

主要问题是您的 $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