R
R
rusgayfer2021-11-17 10:29:27
PHP
rusgayfer, 2021-11-17 10:29:27

How to make correct aspect ratio through ImageMagick?

You need to make the correct aspect ratio so that Instagram accepts the upload of a photo in a post.

Facebook's documentation says the following:

Photo requirements

Maximum file size: 8 MB.
Aspect ratio: ranging from 4:5 to 1.91:1.
Minimum width: 320 (increase to minimum if necessary).
Maximum width: 1440 (reduced to maximum if necessary).
Height: depends on the width and aspect ratio.
Formats: JPEG.


My code:

$photo_original = 'https://sun9-57.userapi.com/impg/c4h_LxUAm3LtkUQrTxjLn63uWYvrEf2qZ4rBHg/47dyzCaV5D4.jpg?size=960x960&quality=96&sign=ec216b9dd8224b8b02670d6e8f0f9fac&type=album';

   $bg = new Imagick($photo_original);
      
   if($bg->getImageWidth() < 320 && $bg->getImageHeight() <= 168) {
      $bg->adaptiveResizeImage(320,168);
   }
   elseif($bg->getImageWidth() > 320 && $bg->getImageHeight() < 168) {
      $bg->adaptiveResizeImage($bg->getImageWidth(), $bg->getImageWidth()/1.9);
   }
   elseif($bg->getImageWidth() < 320 && $bg->getImageHeight() > 168) {
      $bg->adaptiveResizeImage($bg->getImageHeight()*1.9, $bg->getImageHeight());
   } else {
      $bg->adaptiveResizeImage($bg->getImageWidth(), $bg->getImageWidth()/1.9);
   }

   $bg->blurImage(0, 6);
           
   $img_url = new Imagick($photo_original);
   $img_url->optimizeImageLayers(); // Оптимизируем изображение

   $deltaX = $bg->getImageWidth() - $img_url->getImageWidth();
   $deltaY = $bg->getImageHeight() - $img_url->getImageHeight();
            
   $bg->compositeImage($img_url, Imagick::COMPOSITE_ATOP, $deltaX / 2, $deltaY / 2); // Накладываем на фон по центру

   header("Content-Type: image/jpeg");
   echo $bg->getImageBlob();


I need to crop images for Instagram if the original image is not suitable. My example works well, but I'm not cropping the dimensions correctly, how can I make it more correct?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question