N
N
Nikita Sokolov2019-11-15 18:26:26
Layout
Nikita Sokolov, 2019-11-15 18:26:26

How to scale and crop an image using PHP?

Hello! I have a form in which any picture is uploaded for (roughly speaking) an avatar of an employee of an enterprise. You need to scale the image up to 100 pixels in one of the dimensions and then crop the excess in the other dimension. In short, the picture should be .jpg 100x100. It is done immediately on the fly... I put the first parameter simply $_FILES["image"]. Before that, I made the code myself, it turned out to be cut, but I could not figure out how to scale it and I spied on ready-made solutions on the Internet. It turned out here:

function prepare_e_photo($image, $save_to, $quality = 100) {
        unlink($save_to);
        $w = $_CONFIG["EMPLOYEES"]["IMAGE_W"];
        $h = $_CONFIG["EMPLOYEES"]["IMAGE_H"];
        list($width, $height) = getimagesize($image);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $src = imagecreatefromjpeg($image);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg($dst, $save_to, $quality);
        imagedestroy($src);
    
        return $dst;
    }

But this code just turns the picture into a black square, even though it is 100x100. I can't figure out what's wrong here...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arseny, 2018-11-03
Matytsyn @ArsenyMatytsyn

Clear your browser cache

J
JorJeG, 2018-11-03
@JorJeG

This is the shit that confuses me
5bdcc5f9501ee745224541.png

S
Sergey Bro, 2019-11-15
@ssenj

Wouldn't it be easier to use a PHP extension like GD2 , which is what it's designed for?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question