0

アップロードされた画像を受け取るこの PHP スクリプトがあります。アップロードされた画像は一時フォルダーに保存され、このスクリプトは画像を再サンプリングして正しいフォルダーに保存します。ユーザーは、JPG、PNG、または GIF ファイルのいずれかをアップロードできます。ただし、このスクリプトは JPG ファイルのみに対応しています。

このスクリプトを変更して、透過性を失わずに PNG と GIF の両方のサイズを変更するにはどうすればよいですか?

$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = $_POST['n'];
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

$new_src = str_replace('/temp','',$_POST['n']);

imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);

imagejpeg($dst_r,$new_src,$jpeg_quality);
4

2 に答える 2

1

JPEG 画像の背景を透明にすることはできません。

代わりに、以下に基づいて画像を作成できますimagesavealpha()

$targ_w = $targ_h = 150;
$newImage = imagecreatetruecolor($targ_w, $targ_h);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $targ_w, $targ_h, $transparent);

$src = $_POST['n'];
$img_r = imagecreatefromstring(file_get_contents($src));
$img_r_size = getimagesize($src);

$width_r = $img_r_size[0];
$height_r = $img_r_size[1];
if($width_r > $height_r){
    $width_ratio = $targ_w / $width_r;
    $new_width   = $targ_w;
    $new_height  = $height_r * $width_ratio;
} else {
    $height_ratio = $targ_h / $height_r;
    $new_width    = $width_r * $height_ratio;
    $new_height   = $targ_h;
}

imagecopyresampled($newImage, $img_r, 0, 0, 0, 0, $new_width, $new_height, $width_r, $height_r);

$new_src = str_replace('/temp','',$_POST['n']);
imagepng($newImage, $new_src);

PNGとGIFの両方からPNGを作成します(背景が透明で、サイズが150x150に変更されます.

これは一例であり、プロポーションを拘束するものではありません。

于 2012-09-28T08:02:28.620 に答える
0

数か月前にこの問題が発生し、以下のコードを使用して解決しました。

imagealphablending($target_image, false);
imagesavealpha($target_image, true);
于 2012-09-28T08:03:13.413 に答える