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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/747101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:44:55  来源:igfitidea点击:

Resize/crop/pad a picture to a fixed size

phpresizecrop

提问by sanders

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 (h)to 210 / 150

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

What I do now is:

我现在要做的是:

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

Now I take the smallest factor.

现在我取最小的因素。

Now I always have the right width since 238 / 1.333333 = 210. But the height is still 160.

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

How do I get the height down to 160without ruining the pic?

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

Do I need to crop? If so how?

我需要裁剪吗?如果是这样怎么办?

回答by gnud

This solution is basically the same as Can Berk Güder's, but after having spent some time writing and commenting, I felt like posting.

这个解决方案与 Can Berk Güder 的解决方案基本相同,但在花了一些时间写作和评论之后,我想发帖。

This function creates a thumbnail that is exactly as big as the size you give it. The image is resized to best fit the size of the thumbnail. If it does not fit exactly in both directions, it's centered in the thumnail. Extensive comments explain the goings-on.

此功能创建一个与您提供的大小完全一样大的缩略图。调整图像大小以最适合缩略图的大小。如果它在两个方向上都不完全适合,则它会在缩略图中居中。广泛的评论解释了正在发生的事情。

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;
}

Example usage:

用法示例:

$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);

回答by Can Berk Güder

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);

回答by ólafur Waage

Do you have Imagick? If so you can load the image with it and do something like thumbnailimage()

你有Imagick吗?如果是这样,您可以使用它加载图像并执行类似的操作thumbnailimage()

There you can skip either of the parameters (height or width) and it will resize correctly.

在那里你可以跳过任何一个参数(高度或宽度),它会正确调整大小。

回答by TheHippo

Maybe take look at PHPThumb(it works with GD and ImageMagick)

也许看看PHPThumb(它适用于 GD 和 ImageMagick)

回答by Jason S

Just a tip for high-quality fast thumbnail generation from large images: (from the php.net site)

只是从大图像快速生成高质量缩略图的一个技巧:(来自 php.net 站点

If you do the thumbnail generation in twostages:

如果您分两个阶段生成缩略图:

  1. From original to an intermediate image with twice the final dimensions, using a fast resize
  2. From the intermediate image to the final thumbnail using a high-quality resample
  1. 从原始图像到最终尺寸两倍的中间图像,使用快速调整大小
  2. 使用高质量重采样从中间图像到最终缩略图

then this can be much faster; the resize in step 1 is relatively poor quality for its size but has enough extra resolution that in step 2 the quality is decent, and the intermediate image is small enough that the high-quality resample (which works nicely on a 2:1 resize) proceeds very fast.

那么这可以快得多;步骤 1 中的调整大小相对于其大小而言质量相对较差,但具有足够的额外分辨率,因此在步骤 2 中质量不错,并且中间图像足够小,可以进行高质量的重新采样(在 2:1 调整大小时效果很好)进展非常快。

回答by Salman A

The technique is to:

该技术是:

  1. resize the image so that one dimension matches while the other exceeds the desired dimensions
  2. take out the desired size image from the center of resized image.
  1. 调整图像大小,使一个尺寸匹配,而另一个尺寸超过所需尺寸
  2. 从调整大小的图像的中心取出所需大小的图像。

Lastly if you are puzzled about how to do the resize math, remember that if proportions of source and destination images are same, this relation holds:

最后,如果您对如何进行调整大小数学感到困惑,请记住,如果源图像和目标图像的比例相同,则此关系成立:

SourceWidth / SourceHeight = DestinationWidth / DestinationHeight

If you know three parameters, you can calculate the fourth one easily.

如果您知道三个参数,则可以轻松计算第四个参数。

I wrote an article about this:
Crop-To-Fit an Image Using ASP/PHP

我写了一篇关于这个的文章:
Crop-To-Fit an Image Using ASP/PHP

回答by Ickmund

I'd much rather resize so that the image is contained within your limit and then fill out the blank parts. So in the above example you would resize so that the height is OK, then fill up (7 pixels on each end I think) to the left and right with a background color.

我宁愿调整大小,使图像包含在您的限制范围内,然后填写空白部分。因此,在上面的示例中,您将调整大小以使高度正常,然后用背景颜色向左侧和右侧填充(我认为每端 7 个像素)。

回答by Alister Bulman

Resizing images from within a PHP-sourced webpage can be problematic. Larger images (approaching 2+MB on disk) can be so large that they need more than 32MB of memory to process.

从 PHP 来源的网页中调整图像大小可能会出现问题。较大的图像(在磁盘上接近 2+MB)可能非常大,需要超过 32MB 的内存来处理。

For that reason, I tend to either do it from a CLI-based script, with up-to 128MB of memory available to it, or a standard command line, which also uses as much as it needs.

出于这个原因,我倾向于使用基于 CLI 的脚本来执行此操作,它具有高达 128MB 的可用内存,或者使用标准命令行,它也可以根据需要使用。

# where to put the original file/image. It gets resized back 
# it was originally found (current directory)
SAFE=/home/website/PHOTOS/originals
# no more than 640x640 when finished, and always proportional
MAXSIZE=640
# the larger image is in /home/website/PHOTOS/, moved to .../originals
# and the resized image back to the parent dir.
cd $SAFE/.. && mv "" "$SAFE/" && \
   convert "$SAFE/" -resize $MAXSIZE\x$MAXSIZE\> ""

'convert' is part of the ImageMagick command line tools.

'convert' 是 ImageMagick 命令行工具的一部分。

回答by stefs

are these thumbnails? if they are, cropping is not a huge problem. we do it all the time. i don't even shy away from cropping arbitrary ratios into crippled quadratic thumbnails, completely messing up the image (yes, i'm that hardcore), if it just looks good. this is a designers answer to a technical question, but still. don't fear the crop!

这些是缩略图吗?如果是这样,裁剪不是一个大问题。我们一直这样做。我什至不回避将任意比例裁剪成残缺的二次缩略图,完全弄乱图像(是的,我就是那个铁杆),如果它看起来不错的话。这是设计师对技术问题的回答,但仍然如此。不要害怕庄稼!

回答by Strae

I think there is a little confusion.. If you only want to resize it, keeping the original ratio, the right operation is:

我觉得有点混乱..如果你只想调整它的大小,保持原来的比例,正确的操作是:

$ratio = $originalWidth / $originalHeight;
if(//you start from the width, and want to find the height){
 $newWidth = $x;
 $newHeight = $x / $ratio;
}else if(//you start from the height, and want to find the width){
 $newHeight = $x;
 $newWidth = $x * $ratio;
}

Else, if the prefixed newWidth and newHeight cant be changed, and the thumb ratio is different from the original ratio, the only way is to crop or add borders to the thumb.

否则,如果前缀 newWidth 和 newHeight 无法更改,并且缩略图比例与原始比例不同,则唯一的方法是对缩略图进行裁剪或添加边框。

If your'e on to take the cut way, this function can help you (i wrote years ago in 5 minutes, maybe need some improvement.. it works only with jpg, for example ;):

如果你想采取削减的方式,这个功能可以帮助你(我多年前在 5 分钟内写的,可能需要一些改进..它只适用于 jpg,例如;):

    function thumb_cut($nomeimage, $source_path, $destination_path, $new_width, $new_height){
      list($width, $height, $type, $attr) = getimagesize($source_path.$nomeimage);
      if($type == 2){
        if($width > $new_width){
          $new_width = $width;
          $new_height = $height;
        }
        $compression = 100;
        $destimg = imagecreatetruecolor($new_width,$new_height) or die("Problems creating the image");
        $srcimg = ImageCreateFromJPEG($source_path.$nomeimage) or die("problem opening the image");
        $w = ImageSX($srcimg);
        $h = ImageSY($srcimg);
        $ro = $new_width/$new_height;
        $ri = $w/$h;
        if($ro<$ri){
          $par = "h";
        }else{
          $par = "w";
        }
        if($par == "h"){
          $ih = $h;
          $conv = $new_width/$new_height;
          $iw = $conv*$ih;
          $cw = ($w/2)-($iw/2);
          $ch = ($h/2)-($ih/2);
        }else if($par == "w"){
          $iw = $w;
          $conv = $new_height/$new_width;
          $ih = $conv*$iw;
          $cw = ($w/2)-($iw/2);
          $ch = ($h/2)-($ih/2);
        }
        ImageCopyResampled($destimg,$srcimg,0,0,$cw,$ch,$new_width,$new_height,$iw,$ih) or die("problems with resize");
        ImageJPEG($destimg,$destination_path.$nomeimage,$compression) or die("problems with storing new image");
      }
    }