我正在开发一个减少图像文件大小的PHP脚本,它可以很好地处理JPEG图像。但是,在上传PNG图像时,结果图像中会出现一些奇怪的黑条。
以下是一个例子:
这是函数调用:
compress_image($_FILES["pic"]["tmp_name"], $folder_path . "/" . $pic_new_name, 50);
这是功能代码:
//function for compressing and storing image
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return;
} ?>
这个问题是否有任何解决方案或解决方法?
答案 0 :(得分:0)
我希望它会让其他人受益。
这是一个完整的功能,将压缩&正确处理PNG图像并将其转换为白色背景的JPEG:
//function for compressing and storing image
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
$w = $info[0];
$h = $info[1];
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source_url);
imagejpeg($image, $destination_url, $quality);
}
elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source_url);
imagejpeg($image, $destination_url, $quality);
}
elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source_url);
$image_p = imagecreatetruecolor($w, $h);
$white = imagecolorallocate($image_p, 0xFF, 0xFF, 0xFF);
imagealphablending($image_p, false);
ImageSaveAlpha($image_p, true);
ImageFill($image_p, 0, 0, $white);
imagealphablending($image_p, true);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $w, $h, $w, $h);
imagejpeg($image_p, $destination_url, $quality);
}
return;