【发布时间】:2020-02-17 04:43:46
【问题描述】:
我已经在下面提到过 stackoverflow 中有答案,但这对我不起作用,因为该答案类似于 imagecreatetruecolor($width, $height) 但在我的代码中我没有宽度和高度。我的代码完全不同。请删除此重复标签。
我正在尝试在上传过程中压缩图像,它可以很好地压缩jpg 图像但是当我上传png transparent 图像时它会以黑色背景保存,我已经用谷歌搜索了很多,但根据我的代码没有找到任何完美的解决方案。有imagecreatetruecolor($width, $height)的答案,但我的代码中没有width and height variables,我完全糊涂了。
这是我的功能代码:
public function updateProfilePic($file, $userid) {
$filename = $file['user_img']['name'];
$filetmp = $file['user_img']['tmp_name'];
$valid_ext = array('png', 'jpeg', 'jpg');
$location = "user/profilepic/" . $filename;
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extensionstr = strtolower($file_extension);
if(!empty($filename)){
if (in_array($file_extensionstr, $valid_ext)) {
$this->compressImage($filetmp, $location, 50);
// Here I am trying to compress image
return $this->updateProfilePicture($filename, $userid);
} else {
$msg = 'Invalid file type. You can upload only:-' . implode(', ', $valid_ext) . '';
return $msg;
}
} else {
$msg = 'Please upload your profile picture.';
return $msg;
}
}
public function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
}
更新了你所说的代码:
public function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
$width_new = $info[0];
$height_new = $info[1];
$dimg = imagecreatetruecolor($width_new, $height_new);
$background = imagecolorallocate($dimg , 0, 0, 0);
imagecolortransparent($dimg, $background);
imagealphablending($dimg, false);
imagesavealpha($dimg, true);
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
}
请先检查我的代码,然后告诉我解决方案。 请帮帮我
【问题讨论】:
标签: php compression image-compression