A
A
Andrew2016-11-09 21:43:28
PHP
Andrew, 2016-11-09 21:43:28

What is the correct way to create a thumbnail from a fixed size image?

I found several different ready-made functions in php that do this (for me this is a dark forest, for all the years I could not figure out how to properly process images in php in general), but the problem is that all scripts work in such a way that it creates some substrate of a certain size, on which my picture is superimposed, reduced proportionally, it turns out that if the picture does not match the proportions of the substrate, then empty stripes remain along the edges. For me, these stripes are superfluous at all. Is there any way to make the image shrink and crop to fit the background? Well, or maybe some other script can offer that does what I need.
PS Here is what I use now (found somewhere on the Internet)

function img_resize($src, $dest, $width, $height, $rgb=0xFFFFFF, $quality=100) {
    if (!file_exists($src)) return false;
 
    $size = getimagesize($src);
 
    if ($size === false) return false;
 
    $format = strtolower(substr($size['mime'], strpos($size['mime'],'/')+1));
 
    $icfunc = "imagecreatefrom" . $format;
    if (!function_exists($icfunc)) return false;
 
    $x_ratio = $width / $size[0];
    $y_ratio = $height / $size[1];
 
    $ratio       = min($x_ratio, $y_ratio);
    $use_x_ratio = ($x_ratio == $ratio);
 
    $new_width   = $use_x_ratio  ? $width  : floor($size[0] * $ratio);
    $new_height  = !$use_x_ratio ? $height : floor($size[1] * $ratio);
 
    $new_left    = $use_x_ratio  ? 0 : floor(($width - $new_width) / 2);
    $new_top     = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);
 
    $isrc = $icfunc($src);
    $idest = imagecreatetruecolor($width, $height);
 
    imagefill($idest, 0, 0, $rgb);
    imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]);
 
    imagejpeg($idest, $dest, $quality);
 
    imagedestroy($isrc);
    imagedestroy($idest);
 
    return true;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2016-11-09
@ntzch

class.upload.php - verot.net

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question