微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 将图片调整大小/裁剪/填充到固定大小

我需要将图片大小调整为固定大小.但它必须保持宽度和高度之间的因素.

假设我想将图片从238(w)X 182(h)调整为210/150

我现在做的是:

Original width / target width = 1.333333
Original Height / target Height = 1.213333

现在我采取最小的因素.

现在我总是有正确的宽度,因为238 / 1.333333 = 210.
但身高仍然是160.

如何在不破坏照片的情况下将高度降低到160?

我需要裁剪吗?如果是这样的话?

解决方法:

这个解决方案与CanBerkGüder的解决方案基本相同,但在花了一些时间写作和评论之后,我觉得要张贴.

功能创建的缩略图与您提供的缩放尺寸完全一样大.
调整图像大小以最适合缩略图的大小.如果它不完全适合两个方向,它会在thumnail中居中.广泛的评论解释了这些事情.

function thumbnail_Box($img, $Box_w, $Box_h) {
    //create the image, of the required size
    $new = imagecreatetruecolor($Box_w, $Box_h);
    if($new === false) {
        //creation Failed -- probably not enough memory
        return null;
    }


    //Fill the image with a light grey color
    //(this will be visible in the padding around the image,
    //if the aspect ratios of the image and the thumbnail do not match)
    //Replace this with any color you want, or comment it out for black.
    //I used grey for testing =)
    $fill = imagecolorallocate($new, 200, 200, 205);
    imagefill($new, 0, 0, $fill);

    //compute resize ratio
    $hratio = $Box_h / imagesy($img);
    $wratio = $Box_w / imagesx($img);
    $ratio = min($hratio, $wratio);

    //if the source is smaller than the thumbnail size, 
    //don't resize -- add a margin instead
    //(that is, dont magnify images)
    if($ratio > 1.0)
        $ratio = 1.0;

    //compute sizes
    $sy = floor(imagesy($img) * $ratio);
    $sx = floor(imagesx($img) * $ratio);

    //compute margins
    //Using these margins centers the image in the thumbnail.
    //If you always want the image to the top left, 
    //set both of these to 0
    $m_y = floor(($Box_h - $sy) / 2);
    $m_x = floor(($Box_w - $sx) / 2);

    //copy the image data, and resample
    //
    //If you want a fast and ugly thumbnail,
    //replace imagecopyresampled with imagecopyresized
    if(!imagecopyresampled($new, $img,
        $m_x, $m_y, //dest x, y (margins)
        0, 0, //src x, y (0,0 means top left)
        $sx, $sy,//dest w, h (resample to this size (computed above)
        imagesx($img), imagesy($img)) //src w, h (the full size of the original)
    ) {
        //copy Failed
        imagedestroy($new);
        return null;
    }
    //copy successful
    return $new;
}

用法示例:

$i = imagecreatefromjpeg("img.jpg");
$thumb = thumbnail_Box($i, 210, 150);
imagedestroy($i);

if(is_null($thumb)) {
    /* image creation or copying Failed */
    header('HTTP/1.1 500 Internal Server Error');
    exit();
}
header('Content-Type: image/jpeg');
imagejpeg($thumb);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐