1

我正在尝试构建一个函数,该函数采用 PHP 图像资源并将其放置在预定大小的新图像的中心。我不想缩放图像;相反,我想将它按原样放置在放大的“画布”的中心。

$img是一个有效的图像资源 - 如果我返回它,我会收到正确的原始(未处理)图像。$canvas_w并且$canvas_h是所需新画布的宽度和高度。它正在创建正确大小的画布,但是当我返回所需的“已校正”图像资源 ( $newimg) 时,文件的内容出乎意料地是纯黑色。

// what file?
$file = 'smile.jpg';

// load the image
$img = imagecreatefromjpeg($file);

// resize canvas (not the source data)
$newimg = imageCorrect($img, false, 1024, 768);

// insert image
header("Content-Type: image/jpeg");
imagejpeg($newimg);
exit;

function imageCorrect($image, $background = false, $canvas_w, $canvas_h) {
    if (!$background) {
        $background = imagecolorallocate($image, 255, 255, 255);
    }
    $img_h = imagesy($image);
    $img_w = imagesx($image);

    // create new image (canvas) of proper aspect ratio
    $img = imagecreatetruecolor($canvas_w, $canvas_h);

    // fill the background
    imagefill($img, 0, 0, $background);

    // offset values (center the original image to new canvas)
    $xoffset = ($canvas_w - $img_w) / 2;
    $yoffset = ($canvas_h - $img_h) / 2;

    // copy
    imagecopy($img, $image, $xoffset, $yoffset, $canvas_w, $canvas_h, $img_w, $img_h);

    // destroy old image cursor
    //imagedestroy($image);
    return $img; // returns a black original file area properly sized/filled
    //return $image; // works to return the unprocessed file
}

这里有任何提示或明显的错误吗?感谢您的任何建议。

4

1 回答 1

3

代替imagecopy(),这似乎有效:

imagecopymerge($img, $image, $xoffset, $yoffset, 0,0, $img_w, $img_h, 100);
于 2012-05-19T11:25:22.073 回答