I have already mentioned below that There is answer in stackoverflow but that didn't work for me because that answer is like imagecreatetruecolor($width, $height)
but In my code I don't have width and height. My code is totally different. Please Kindly remove this duplicate tag.
I am trying to compress image during upload, It compress fine for jpg
images but when i upload png transparent
image then it saves with black background, I have googled a lot but didn't find any perfect solution according to my code. There was answer of imagecreatetruecolor($width, $height)
, But there is no width and height variables
in my code, I am totally confused and stuck.
Here is my function code:
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);
}
Updated Code of what you was saying:
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);
}
Please check my code first and then tell me the solution. Please help me