PHP 使用最大宽度或重量按比例调整图像大小 [已关闭]
2022-08-30 18:12:00
是否有任何php脚本可以按比例调整图像大小,最大宽度或高度??
例如:我上传图像,这个原始大小是w:500 h:1000。但是,我想调整这个最大高度是宽度,高度是500...脚本为 w: 250 h: 500 调整图像大小
是否有任何php脚本可以按比例调整图像大小,最大宽度或高度??
例如:我上传图像,这个原始大小是w:500 h:1000。但是,我想调整这个最大高度是宽度,高度是500...脚本为 w: 250 h: 500 调整图像大小
您所需要的只是宽高比。类似如下的内容:
$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);
您需要添加一些错误检查,但这应该可以帮助您入门。
使用由 Colin Verot 编写的 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;
}
}