V
V
Volodymyr Palamar2020-09-30 15:30:44
PHP
Volodymyr Palamar, 2020-09-30 15:30:44

How to prepare an image for Instagramram?

I have a wonderful

function
function SquareImage($imgSrc, $imgDes, $thumbSize = 1000){
    list($width, $height) = getimagesize($imgSrc);
    $myImage = imagecreatefromjpeg($imgSrc);
    if ($width > $height) {
        $y = 0;
        $x = ($width - $height) / 2;
        $smallestSide = $height;
    } else {
        $x = 0;
        $y = ($height - $width) / 2;
        $smallestSide = $width;
    }
    $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
    imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
    if (file_exists($imgSrc)) {
        unlink($imgSrc);
    }
    imagejpeg($thumb, $imgDes, 100);
    @imagedestroy($myImage);
    @imagedestroy($thumb);
}
which crops the image (you need 400x400.jpg)
If I give for example 400x500 as an input, everything is OK, but the problem is if the photo is for example 300x400 The essence
of the question:
SquareImage();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Gnevyshev, 2020-09-30
@iResource

Adding margins (white/black/grey, etc.) is one option.
Another option is to first enlarge the image proportionally so that the dimensions are at least 400.
And then crop it to a square.
I would add a size check and an increase (if necessary) immediately after the line:
list($width, $height) = getimagesize($imgSrc);
The image will lose a little quality (or maybe a lot - if one of the sizes is very small),
but there will be no extra margins.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question