Resize/crop/pad a picture to a fixed size

前端 未结 11 1771
孤城傲影
孤城傲影 2020-11-27 14:58

I need to resize a picture to a fixed size. But it has to keep the factors between the width and height.

Say I want to resize a picture from 238 (w) X 182 (

11条回答
  •  攒了一身酷
    2020-11-27 15:33

    This doesn't crop the picture, but leaves space around the new image if necessary, which I think is a better approach (than cropping) when creating thumbnails.

    $w = 210;
    $h = 150;
    
    $orig_w = imagesx($original);
    $orig_h = imagesy($original);
    
    $w_ratio = $orig_w / $w;
    $h_ratio = $orig_h / $h;
    
    $ratio = $w_ratio > $h_ratio ? $w_ratio : $h_ratio;
    
    $dst_w = $orig_w / $ratio;
    $dst_h = $orig_h / $ratio;
    $dst_x = ($w - $dst_w) / 2;
    $dst_y = ($h - $dst_h) / 2;
    
    $thumbnail = imagecreatetruecolor($w, $h);
    
    imagecopyresampled($thumbnail, $original, $dst_x, $dst_y,
                       0, 0, $dst_w, $dst_h, $orig_w, $orig_h);
    

提交回复
热议问题