I found the solution myself. I am posting here for someone who comes searching for it in the future. If you are using Croppie.js and your file size is too large the first thing you need to do is to set your image format to format: "jpeg"
. JPEG uses a compression technology itself compared to PNG files resulting in low sizes files without doing anything. Now if you want better quality set your size: "original"
and quality: 1
. Basically your Croppie settings should look like this:
resize.croppie('result', {
type: "canvas",
size: "original",
format: "jpeg",
quality: 1
})
Now, with this setting the file size should be less compared to PNG but still would be large enough to indicate a red flag for a web app. Therefore, the solution is compressing the image using PHP during upload. Now here I had to face a challenge. All the examples I found on internet was given using $_FILES
method that is normally used while uploading images. However, as you can see in my question above the PHP coding was different. Therefore, I had to find a way to overcome this problem as no relevant example was given on the web considering uploads using Croppie.js. Therefore, I went on to figure out the things myself using the trial and error method and was able to replicate the solution commonly used with $_FILES
method for image compression. I wrote my own function for it. However, the function below only contains the solution for JPEG image type. If you want it for any other format please feel free to use my function as an example and modify it accordingly.
function compressImage($image, $imageDirectory, $quality) {
return imagejpeg(imagecreatefromstring($image), $imageDirectory, $quality);
}
$image_array_1 = explode(";", $image);
$image_array_2 = explode(",", $image_array_1[1]);
$image = base64_decode($image_array_2[1]);
$imageName = $user['id'][0] . "_" . time() . '.jpg';
if(!file_exists("../images/users/".$user['id'][0]."/"."avatar/")) {
$dir = mkdir("../images/users/".$user['id'][0]."/"."avatar/", 0777, true);
}else{
$dir = "../images/users/".$user['id'][0]."/"."avatar/";
}
$imageDirectory = $dir.$imageName;
compressImage($image, $imageDirectory, 50);
Enjoy!