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

发布于 2024-07-17 05:21:15 字数 435 浏览 7 评论 0原文

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

假设我想将图片大小从 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

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

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

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.

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

Do I need to crop? If so how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

把梦留给海 2024-07-24 05:21:16

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

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

终难遇 2024-07-24 05:21:16

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

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

  1. 从原始图像到最终尺寸两倍的中间图像,使用快速调整大小
  2. 从中间图像到最终图像 如果使用高质量的重新采样生成缩略图,

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

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

If you do the thumbnail generation in two stages:

  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

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.

月牙弯弯 2024-07-24 05:21:16

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

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.

宣告ˉ结束 2024-07-24 05:21:16

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

出于这个原因,我倾向于要么从基于 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 "$1" "$SAFE/$1" && \
   convert "$SAFE/$1" -resize $MAXSIZE\x$MAXSIZE\> "$1"

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

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.

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.

# 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 "$1" "$SAFE/$1" && \
   convert "$SAFE/$1" -resize $MAXSIZE\x$MAXSIZE\> "$1"

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

月光色 2024-07-24 05:21:16

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

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!

回心转意 2024-07-24 05:21:16

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

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

否则,如果前缀newWidth和newHeight无法改变,而拇指比例与原来比例不同,唯一的办法就是裁剪或添加边框到拇指。

如果你想采取剪切方式,这个函数可以帮助你(我几年前在 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");
      }
    }

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.

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

    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");
      }
    }
贱人配狗天长地久 2024-07-24 05:21:16

该技术是:

  1. 调整图像大小,使一个尺寸匹配,而另一个尺寸超出所需尺寸,
  2. 从调整大小图像的中心取出所需尺寸的图像。

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

SourceWidth / SourceHeight = DestinationWidth / DestinationHeight

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

我写了一篇关于此的文章:
裁剪以适合图像使用ASP/PHP

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.

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

沐歌 2024-07-24 05:21:16

您必须从顶部和底部裁剪 5 像素才能达到目标尺寸,但这可能会破坏图片。

实际上,您应该有一个目标宽度或高度,然后按相同比例调整其他尺寸。

You'll have to crop 5 px off the top and bottom to get to your target size, however this could ruin the picture.

Really you should have a target width or height, then adjust the other dimension by the same proportion.

只是我以为 2024-07-24 05:21:15

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

此函数创建的缩略图与您指定的大小完全相同。
图像的大小会调整为最适合缩略图的大小。 如果它在两个方向上不完全适合,则会在缩略图中居中。 大量评论解释了正在发生的事情。

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

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.

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);
俯瞰星空 2024-07-24 05:21:15

这不会裁剪图片,但如有必要,会在新图像周围留下空间,我认为这是创建缩略图时更好的方法(比裁剪)。

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

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);
霊感 2024-07-24 05:21:15

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

在这里您可以跳过任一参数(高度或宽度),它将正确调整大小。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文