【发布时间】:2016-12-10 20:13:52
【问题描述】:
我正在使用 PHP 处理 .png 文件上传,该文件被裁剪然后上传。无论出于何种原因,我的第一次尝试是用黑色交换透明。在阅读了多个堆栈溢出问题并尝试了解决方案之后,我现在处于文件被上传但不可读且为 0 字节的阶段。出了什么问题? (我正在关注其他问题的确切答案......)
.jpeg 工作正常,.png 不是这样
我正在使用的代码:
$dest_image = ImageCreateTrueColor($target_width, $target_height);
switch ($search->found_extension()) {
case 'PNG':
case 'png':
imagealphablending($dest_image, false);
imagesavealpha($dest_image, true);
$source_image = imagecreatefrompng($image);
$transparent = imagecolorallocatealpha($dest_image, 255, 255, 255, 127);
imagefilledrectangle($dest_image, 0, 0, $target_width, $target_height, $transparent);
imagecopyresampled($dest_image, $source_image, 0, 0, $x, $y, $target_width, $target_height, $w, $h);
header('Content-type: image/png');
imagepng($dest_image, "../../" . $folder . "/" . cleanstring($userdata->id) . $hasher . ".png", $quality);
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
imagealphablending($dest_image, false);
imagesavealpha($dest_image, true);
$source_image = imagecreatefromjpeg($image);
imagecopyresampled($dest_image, $source_image, 0, 0, $x, $y, $target_width, $target_height, $w, $h);
header('Content-type: image/jpeg');
imagejpeg($dest_image, "../../" . $filename, $quality);
break;
}
尝试过的解决方案:
【问题讨论】:
-
1.为什么要输出图像标题,2.为什么您用于 png 和 jpg 图像的路径存在如此大的差异和 3.
imagepng()的返回值是多少? -
@jeroen 我认为保存文件时图像标题是必须的,路径的差异只是因为扩展名“.png / .jpg”(一旦工作就会重写)。如何获得
imagepng()的返回值?此代码由 ajax 调用调用。 -
由于您的 ajax 调用将期望返回 text / html / json,因此您不应该设置图像标题,只有当您想直接从脚本输出图像到浏览器时才这样做。由于您的代码非常重复,我会为 jpg 和 png 使用相同的代码,以便您可以轻松缩小问题所在。
-
@jeroen 查看我自己的解决方案答案,感谢您的帮助