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
}
ここにヒントや明らかなエラーはありますか? 提案をありがとう。