I get images as base64 encoded string front end and I have to decode them and save them as images in server. Image can be of any format- png,gif or jpeg. This part works fine. But sometimes the images uploaded by the users can be of very large size, so I'm trying to compress them from backend and this part failed miserably.
I have two functions. One for converting base64 string to image and other one for compressing it.
This is the function that converts the string to an image.
function uploadTimelineImage($base64Img)
{
$data= array();
$upAt=date('YmdHis');
if (strpos($base64Img, 'data:image/png;base64') !== false)
{
$img = str_replace('data:image/png;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'png';
}
if (strpos($base64Img, 'data:image/gif;base64') !== false)
{
$img = str_replace('data:image/gif;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'gif';
}
if (strpos($base64Img, 'data:image/jpeg;base64') !== false)
{
$img = str_replace('data:image/jpeg;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'jpeg';
}
$fileName = 'img'.$upAt.$extension;
$filePath = 'foldername/'.'img'.$upAt.$extension;
//upload image to folder
$success = file_put_contents($filePath, $data);
$result = $success ? 1 : 0;
//call to compression function
$compressThisImg= $filePath;
$d = compress($compressThisImg, $fileName, 80);
if($result==1)
{
return $fileName;
}
else
{
return null;
}
}
And this is the function that does compressing:
//Function to compress an image
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
But the above function does not do any compression, it throws error:
failed to open stream: No such file or directory
and my function uploads the original image.