首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理不同尺寸的上传图片

处理不同尺寸的上传图片
EN

Stack Overflow用户
提问于 2012-10-22 02:03:38
回答 2查看 168关注 0票数 0

我希望能够允许用户上传图片。使用GD库,我将为一个图库创建/存储三个不同大小的图像,并展示产品。问题是为上传了不同大小的图片的人缩放尺寸。例如,一张4000 x 3000的图片可以缩放到我想要的240 x 180,但是我注意到有些用户的图片尺寸不同,比如3008 x 2000和3837 x 2551。

有没有人可以指导我如何处理这些不同的图像尺寸,以便将它们缩放到一个共同的大小。

EN

回答 2

Stack Overflow用户

发布于 2012-10-22 02:13:33

您必须设置最终尺寸,例如: 300x300像素

然后将这两个因子除以原始尺寸,例如

代码语言:javascript
复制
factor1=300/4000 <- Width
factor2=300/3000 <- Heigth

现在,您可以按较小的因子缩放图像。你现在应该有一个300像素的高度或宽度的图像。现在,您可以剪切大于最终尺寸的所有内容。完成了!

希望这能有所帮助

票数 1
EN

Stack Overflow用户

发布于 2012-10-22 02:18:48

我认为您正在寻找这样一个函数:

代码语言:javascript
复制
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
    $srcWidth = imagesx($img);
    $srcHeight = imagesy($img);

    // Determine new width / height preserving aspect ratio
    $srcRatio = $srcWidth / $srcHeight;
    $targetRatio = $targetWidth / $targetHeight;
    if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
    {
        $imgTargetWidth = $srcWidth;
        $imgTargetHeight = $srcHeight;
    }
    else if ($targetRatio > $srcRatio)
    {
        $imgTargetWidth = (int) ($targetHeight * $srcRatio);
        $imgTargetHeight = $targetHeight;
    }
    else
    {
        $imgTargetWidth = $targetWidth;
        $imgTargetHeight = (int) ($targetWidth / $srcRatio);
    }

    // Creating new image with desired size
    $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);

    // Add transparency if your reduced image does not fit with the new size
    $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
    imagefill($targetImg, 0, 0, $targetTransparent);
    imagecolortransparent($targetImg, $targetTransparent);

    // Copies image, centered to the new one (if it does not fit to it)
    imagecopyresampled(
       $targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
       ($targetHeight - $imgTargetHeight) / 2, // centered
       0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
    );

    return $targetImg;
}

使用示例:

代码语言:javascript
复制
$gd = imagecreatefromjpeg("images/image5.jpg");
$resized = resizePreservingAspectRatio($gd, 100, 100);
header("Content-type: image/png");
imagepng($resized);

这将转换这样的图像:

对于那一个:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13000595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档