【问题标题】:PHP resize image proportionally with max width or weight [closed]PHP根据最大宽度或重量按比例调整图像大小[关闭]
【发布时间】:2013-05-19 02:46:58
【问题描述】:

是否有任何 php 脚本可以根据最大宽度或高度按比例调整图像大小??

例如:我上传图片,原始尺寸为 w:500 h:1000。但是,我想调整这个最大高度是宽度和高度是 500...脚本调整图像的大小为 w: 250 h: 500

【问题讨论】:

  • 此链接可能会满足您的需求:white-hat-web-design.co.uk/blog/resizing-images-with-php
  • 嗨!!!我认为这可以帮助我。我不明白我是如何获得原始高度或宽度的。可以帮我吗?
  • 我会这样做,但我实际上认为 Kolink 的答案对 SO 社区最有用,因为它在不依赖库或其他依赖项的情况下解决了问题,并且几乎不需要更多代码行,如果使用我指向你的图书馆。我建议你接受那个(我不知道为什么它被否决了)
  • 因不具建设性而关闭,观看次数超过 12k...lol
  • 非常有建设性的回答。 :)

标签: php


【解决方案1】:

您所需要的只是纵横比。大致如下:

$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
    $width = 500;
    $height = 500/$ratio;
}
else {
    $width = 500*$ratio;
    $height = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$target_filename_here); // adjust format as needed
imagedestroy($dst);

您需要添加一些错误检查,但这应该可以帮助您入门。

【讨论】:

  • 我相信您需要“比例”而不是比率。您必须计算最小比例以适应您的限制,我手上有一段 Javascript: var scale = Math.min($window.width() / item.width, $window.height() / item.height) ; var itemWidth = scale * item.width; var itemHeight = scale * item.height;
  • 我相信你的条件应该是if( $ratio < 1) {。我说的对吗?
  • $ratio > 1 表示宽度大于高度,因此应该是钳制到500的那个,高度再除以它(结果数变小了)。跨度>
【解决方案2】:

使用 Colin Verot 编写的上传类。它有各种用于调整大小、编辑、水印等的选项……太棒了!!

该课程由互联网上的网站维护和使用,因此您可以信赖它!

here

即使这称为上传类,您也可以将相同的方法应用于服务器上已有的文件

如何使用

按照网站上的安装说明,非常简单,下载课程并将其放置在您的网站中。

您的脚本将如下所示:

// Include the upload class
include('class.upload.php');

// Initiate the upload object based on the uploaded file field
$handle = new upload($_FILES['image_field']);

// Only proceed if the file has been uploaded
if($handle->uploaded) {
    // Set the new filename of the uploaded image
    $handle->file_new_name_body   = 'image_resized';
    // Make sure the image is resized
    $handle->image_resize         = true;
    // Set the width of the image
    $handle->image_x              = 100;
    // Ensure the height of the image is calculated based on ratio
    $handle->image_ratio_y        = true;
    // Process the image resize and save the uploaded file to the directory
    $handle->process('/home/user/files/');
    // Proceed if image processing completed sucessfully
    if($handle->processed) {
        // Your image has been resized and saved
        echo 'image resized';
        // Reset the properties of the upload object
        $handle->clean();
    }else{
        // Write the error to the screen
        echo 'error : ' . $handle->error;
    }
}

【讨论】:

  • 这似乎适用于横向图像,但是如果源图像是 100px 宽和 3,000px 高呢?
  • @Kolink 然后它不会调整大小!该代码只是如何使用该类的示例。该类可用于以您希望的任何方式调整图像大小。如果你愿意,你可以设置最大宽度和高度......为什么不赞成???
  • 处理后如何获取带扩展名的完整文件名?
猜你喜欢
  • 2012-05-06
  • 2011-12-29
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
相关资源
最近更新 更多