PHP使用最大宽度或重量按比例调整图像大小

PHP使用最大宽度或重量按比例调整图像大小,php,Php,有任何php脚本可以按最大宽度或高度按比例调整图像大小 例如:我上传的图像,这个原始尺寸是w:500 h:1000。但是,我想调整它的最大高度是宽度,高度是500。。。使用Colin Verot编写的Upload类,脚本调整图像的大小,使其达到w:250 h:500。它有各种各样的调整大小、编辑、水印等选项。。。太棒了 该课程由互联网上的所有网站维护和使用,因此您可以信赖它的可靠性 看 即使这被称为Upload类,您也可以对服务器上已有的文件应用相同的方法 如何使用 按照站点上的安装说明进行操作

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


例如:我上传的图像,这个原始尺寸是w:500 h:1000。但是,我想调整它的最大高度是宽度,高度是500。。。使用Colin Verot编写的Upload类,脚本调整图像的大小,使其达到w:250 h:500。它有各种各样的调整大小、编辑、水印等选项。。。太棒了

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

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

如何使用 按照站点上的安装说明进行操作,非常简单,下载类并将其放置在站点中

您的脚本将如下所示:

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

你所需要的就是纵横比。大致如下:

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

您需要添加一些错误检查,但这应该可以让您开始。

此链接可能会提供您所需的信息:您好!!!我想这对我有帮助。我看不出我是如何得到原始高度或宽度的。可以帮我吗?我会的,但我实际上认为Kolink的答案对SO社区最有用,因为它解决了问题,而不依赖库或其他依赖项,并且几乎不涉及更多的代码行,如果使用我指给您的库,那么将需要更多的代码行。我建议你接受一个(我不知道为什么它被否决)以不具建设性的12k+观点关闭…非常有建设性的回答。:)这似乎适用于横向图像,但如果源图像宽100px,高3000px怎么办?@Kolink则不会调整大小!该代码只是如何使用该类的一个示例。该类可用于以任何方式调整图像大小。如果需要,可以改为设置最大宽度和高度。。。为什么是向下投票???更好的答案是:在处理后如何获得扩展名为的完整文件名?我相信你需要的是“比例”而不是比例。你必须计算最小比例以满足你的限制,我手上有一块Javascript:var scale=Math.min($window.width()/item.width,$window.height()/item.height);var itemWidth=比例*item.width;var itemHeight=比例*item.height;我相信你的条件应该是
如果($ratio<1){
。我说的对吗?
$ratio>1
意味着宽度大于高度,因此应该是固定到500的高度。然后将高度除以它(得到一个较小的数字)。