imagick resize base64 image to base64 image in php
March 4, 2025 in Laravel, Php
$PostImage = $_POST['PostImage'];
$imageBlob = base64_decode(str_ireplace('data:image/png;base64,','',$PostImage));
$im = new Imagick();
$im->readImageBlob($imageBlob);
//$im = new Imagick($_FILES['imageForPost']["tmp_name"]);
$imageprops = $im->getImageGeometry();
$finalWidth = 512;
$finalHeight = 512;
$ext = '.png';
$size = 40;
$width = $imageprops['width'];
$height = $imageprops['height'];
if($height > $finalHeight){
$newHeight = $finalHeight;
$newWidth = ($finalHeight / $height) * $width;
}else{
$newWidth = $imageprops['width'];
$newHeight = $imageprops['height'];
}
$im->scaleImage($finalWidth,$finalHeight,true,true);
$canvas = new Imagick();
$canvas->newImage($finalWidth, $finalHeight, 'white', 'png');
$canvas->blurImage(25, 5);
$imageprops = $im->getImageGeometry();
$newWidth = $imageprops['width'];
$newHeight = $imageprops['height'];
if($finalWidth == $finalHeight){
$pos = 0;
$posh = ($finalHeight - $newHeight)/2;
}else{
$pos = ($finalWidth - $newWidth)/2;
$posh = ($finalHeight - $newHeight)/2;
}
$canvas->compositeImage($im, Imagick::COMPOSITE_OVER, $pos, $posh);
$canvas->setOption('jpeg:extent', $size.'kb');
$canvas->setImageFormat( "jpeg" );
$thumbnail = $im->getImageBlob();
$PostImage = $thumbnail;
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnail)."' />";
