计算最接近的可能维度值 PHP(保持比率)

Calculate nearest possible dimension value PHP (keeping ratio)

我正在尝试实现 API 以调整图像大小。它的创建并不完全是为了图像处理,这只是 API 中的一个 part/feature。

我想实现的。

我有 url 从服务器检索图像它看起来像

 mywebpage.com/api/product/42/image

此 url 将 return URL 为 ID 为 42 的产品的完整图像。
一切正常。
我们可以使用 GET 参数指定所需的大小

 mywebpage.com/api/product/42/image?width=200&height=300

看起来也不错

但是我的问题是跟不上。
由于我们可以在服务器上使用不同尺寸和纵横比的不同图像,因此我需要在调整大小时保持这个比例。

例如,我需要适合 200x300 容器的图片,但服务器上有 1024x576 (16:9) 的图片。我需要调整此图像的大小但保持初始纵横比 (16:9) 但要适合所需的容器。

如何根据传入的所需尺寸和当前图像纵横比有效地将新图像大小计算为 return。

我想提前感谢大家的帮助或建议。

好吧,如果您需要始终适合 200x300 的容器(或任何通过 URL 传递的容器),您可能无法简单地调整它的大小,因为正如您所知,它会影响图像宽高比。

如果是这种情况,您可以将图像调整为最接近的大小,然后裁剪图像的其余部分。

我假设您将为此使用 imagemagick。你检查过文档了吗? cropThumbnailImage 方法执行我刚才解释的操作。

用法示例:

/* Read the image */
$im = new imagick( "test.png" );
/* create the thumbnail */
$im->cropThumbnailImage( 80, 80 );
/* Write to a file */
$im->writeImage( "th_80x80_test.png" );

http://php.net/manual/en/imagick.cropthumbnailimage.php

这是我用来制作类似东西的脚本。很旧,所以可能不是最新的。

<?php

    if( isset($_GET["width"]) && is_numeric($_GET["width"]))
        $target_width = intval($_GET["width"]);
    else
        $target_width= 200;//default value

    if( isset($_GET["height"]) && is_numeric($_GET["height"]))
        $target_height = intval($_GET["width"]);
    else
        $target_height= 300;//default value

    if( isset($_GET["id"]) && is_numeric($_GET["id"]))//prevent any unwanted filesystem access 
        $original_image_path = "img/products/$id.jpg";
    else
        $original_image_path = "placeholder.png"

    //http://php.net/manual/fr/function.getimagesize.php
    $image_size = getimagesize($original_image_path);

    //get the ratio of the original image
    $image_ratio=  $image_size[1]/ $image_size[0];

    $original_image = imagecreatefromjpeg($original_image_path);
    $new_image = imagecreatetruecolor($target_width, $image_ratio * $target_width);

    //paints the image in white
    //http://php.net/manual/en/function.imagefill.php
    //http://php.net/manual/en/function.imagecolorallocatealpha.php
    imagefill( $new_image, 0, 0, imagecolorallocatealpha($new_image, 255,255,255,127) ); 
    imagesavealpha($new_image, TRUE);

    /*
     Copies the original to the new, preserving the ratio. 
     The original image fills all the width of the new, 
     and is placed on the top of the new.
     http://php.net/manual/en/function.imagecopyresized.php
    */
    imagecopyresized(
                        $new_image,$original_image,
                        0,0,
                        0,0,
                        $target_width,$image_ratio * $target_width,
                        $image_size[0],$image_size[1]
                    ); 

    //image is returned in response to the request
    header ("Content-type: image/png");
    imagepng( $new_image ); 

?>