我最终设法让用户上传的图片保持透明,当它们是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();
}
}
?>
黑框在透明区域返回。
答案 0 :(得分:0)
如果您已经有一个只想发送到浏览器的PNG,那么就不需要GD了。
header('Content-Type: image/png');
fp = fopen($fileDir . $file, "r");
fpassthru($fp);
fclose($fp); /* this is not necessary, but I prefer to keep it */
exit();
由于您以相同的方式导出JPEG(顺便说一句,您在该部分中有错误:标题显示为image/jpeg
,而您发送了带有@imagepng()
的PNG),我会重写您的代码像这样:
<?php
$allowedMimes = array("png", "gif", "jpeg");
$fileDir = '/home/funkydic/noaccess/avatars/';
$file = basename(urldecode($_GET['img']));
$file = str_replace("../", "", $file); /* what's this for? you already have basename() */
if (file_exists($fileDir . $file)) {
$mime = strtolow(pathinfo($file, PATHINFO_EXTENSION));
if ($mime == "jpg") $mime = "jpeg";
if (in_array($mime, $allowedMimes)) {
header("Content-Type: image/$mime");
fp = fopen($fileDir . $file, "r");
fpassthru($fp);
fclose($fp);
exit();
}
/* if you get here, extension in the GET request was wrong */
}
/* if you get here, extension in the GET request was wrong or the file doesn't exist */
?>