我只是最终设法让用户上传的图像在它们是 png 时保持透明,通过这样做:
$image_p = imagecreatetruecolor($fixed_width, $fixed_height);
if ($_FILES[$fileName]["type"] == "image/x-png" || $_FILES[$fileName]["type"] == "image/png") {
$background = imagecolorallocate($image_p, 0, 0, 0);
imagecolortransparent($image_p, $background);
imagealphablending($image_p, false);
imagesavealpha($image_p, true);
}
// PNG or JPG
if ($_FILES[$fileName]["type"] == "image/jpeg" || $_FILES[$fileName]["type"] == "image/jpg" || $_FILES[$fileName]["type"] == "image/pjpeg") {
$image = imagecreatefromjpeg($imageFile);
} else {
$image = imagecreatefrompng($imageFile);
}
// check if img is bigger then max width
$manipulated = 0;
if ($width_orig > $fixed_width) {
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $fixed_width, $fixed_height, $width_orig, $height_orig); // reduce in width / height
$manipulated = 1;
} else {
$image_p = $image; // leave as is
}
// Output PNG or JPG
if ($_FILES[$fileName]["type"] == "image/jpeg" || $_FILES[$fileName]["type"] == "image/jpg" || $_FILES[$fileName]["type"] == "image/pjpeg") {
imagejpeg($image_p, $newfile, 65);
} else {
imagepng($image_p, $newfile, 6);
}
但是现在我将它们显示为 .png 时出现问题,当我从 Cpanel 字典中打开文件时,它是透明的,但是当我使用以下命令显示时:
<?php
$file = basename(urldecode($_GET['img']));
$file = str_replace("../", "", $file);
$fileDir = '/home/funkydic/noaccess/avatars/';
$jpg = strpos($file, '.jpg');
$jpeg = strpos($file, '.jpeg');
$png = strpos($file, '.png');
if ($jpg != false || $jpeg != false) {
if (file_exists($fileDir . $file)) {
$imageRes = imagecreatefromjpeg($fileDir . $file);
header('Content-Type: image/jpeg');
// Output the image
@imagepng($imageRes);
// Free up memory
@imagedestroy($imageRes);
die();
}
}
elseif ($png != false) {
if (file_exists($fileDir . $file)) {
$imageRes = imagecreatefrompng($fileDir . $file);
header('Content-Type: image/png');
// Output the image
@imagepng($imageRes);
// Free up memory
@imagedestroy($imageRes);
die();
}
}
?>
黑匣子在透明区域返回。