wenus
wenus

Reputation: 1515

php img thumbs are not resized

I have code to make a thumbs from original image form user. I need to have hardcore width and height for thumb and it is 160 x 160. My problem is not perfect picture. I mean when user want to add img witch is wider than higher then my thumbnail looks bad and is stretched - and similary is happened when original img is higher than wider - then thumb is badly compressed. I thought that I have to manipulate with function imagecopyresampled() but I think It was bad choice. My question is: what to do to make thumbs to be not compressed or stretched and cut them f.e. from center of original image? My code looks like this now:

$imgOrginalsize = getimagesize($file);
        $ratio = $imgOrginalsize[0] / $imgOrginalsize[1];
        $h = 160;
        $w = 160;

 $file_name = basename($file);

        switch (strtolower($imgOrginalsize['mime'])) {
            case 'image/jpeg':
                $img = imagecreatefromjpeg($file);
                $new = imagecreatetruecolor($w, $h);
                imagecopyresampled($new, $img, 0, 0, 0, 0, $w, $h, $imgOrginalsize[0], $imgOrginalsize[1]);
                imagejpeg($new, $pathToSave . $file_name, 100);
                imagedestroy($new);
                break;
            case 'image/png':
                $img = imagecreatefrompng($file);
                $new = imagecreatetruecolor($w, $h);
                imagecopyresampled($new, $img, 0, 0, 0, 0, $w, $h, $imgOrginalsize[0], $imgOrginalsize[1]);
                imagepng($new, $pathToSave . $file_name, 100);
                imagedestroy($new);
                break;
            default:
                var_dump('error default');
                exit();
        }

Now thumbs looks bad and for example is compressed - original img is much higher oyu know what I mean I don't need in thumbnail all picture - I can have croped from left top corner ( or from center of original img )but I don't want to have compressed it or stretched:

enter image description here

Upvotes: 0

Views: 52

Answers (1)

Eleonora Ivanova
Eleonora Ivanova

Reputation: 813

Try imagecrop($img, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size ]);

See http://php.net/manual/en/function.imagecrop.php

Replace $size with your desired width/height

The link also has an example how to centre it.

Upvotes: 1

Related Questions