图像处理动态调整大小

时间:2019-02-09 17:48:17

标签: php image

我在https://gist.github.com/philBrown/880506中使用了Phil Brown出色的图像处理类,下面是我的代码:

if ($fileValidation->passed()) { 
//Upload the file 
$newNamePrefix = time() . '_'; 
//add a time prefic to the front of the file 
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']); //initialise the class 
$newImage = $manipulator->resample(300,300); // resizing to 300x300 
//Check there is space in their uploads dir after upload 
if (checkSpace($accountId, $_FILES['fileToUpload']['size'] == true)) { 
//Save the file 
$manipulator->save($_SERVER['DOCUMENT_ROOT'].'/uploads/'.$accountId.'/'.$newNamePrefix
. $_FILES['fileToUpload']['name']); // saving file to uploads folder 
//Insert a record into the uploads table 
$insertProfile = DB::getInstance()->insert('ym_uploads', array(
'account_id' => $accountId, 
'vessel_id' => $vid, 
'user_id' => $uid, 
'file_linked_table' => 'ym_expenditure',
'file_linked_id' => $item,
'file_name' => $newNamePrefix . $_FILES['fileToUpload']['name']
)); 
} else { Session::flashmessage('danger', 'We were unable to upload your receipt image as you have insuficient storage remaining'); } }

我不确定如何处理是如何动态调整图像大小。例如。用户从手机上传图片。通过将尺寸设置为300 x 300,如果上传的图片并非一开始就可以得到缩小的图像。

有人能指出我正确的方法吗?本质上,我正在尝试减少上载占用的文件大小。

我在想找到要上传的图像大小,然后将其设置为百分比,然后添加到代码的重采样部分中?

我目前正在研究...

list($width, $height, $type, $attr) = getimagesize($manipulator);
if ($width >= 4000) {
$width = $width / 8;
$height = $height / 8;
} elseif ($width >= 2000) {
$width = $width / 4;
$height = $height / 4;
} elseif ($width >= 500) {
$width = $width / 2;
$height = $height / 2;
}
$newImage = $manipulator->resample($width, $height); // resizing to 300x300

这将引发Uncaught UnexpectedValueException:不幸的是,资源无效,因此它向类发送了错误的信息。 任何帮助将不胜感激!

致谢

马特

1 个答案:

答案 0 :(得分:0)

我有一些工作要做,尽管这可能不是进行该过程的最佳方法。

使用...

$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']); //initialise the class
list($width, $height, $type, $attr) = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($width >= 4000) {
$width = $width / 8;
$height = $height / 8;
} elseif ($width >= 2000) {
$width = $width / 4;
$height = $height / 4;
} elseif ($width >= 500) {
$width = $width / 2;
$height = $height / 2;
}
$newImage = $manipulator->resample($width, $height); // resizing to 300x300

允许我根据上传的图片动态缩小文件大小,并将调整后的大小传递给类。