我之前尝试将多个文件上传到我的bucket中,效果很好,但现在我尝试在上传之前调整图像大小并压缩图像,它会抛出错误imagesx() expects parameter 1 to be resource, string given
,代码如下:
foreach($_FILES as $ind => $filegroup){
$count=0;
foreach($_FILES[$ind]['name']as $actfile){
$tmp=$_FILES[$ind]['tmp_name'][$count];
$count=$count + 1;
$newind= str_replace('_',' ',$ind);
$filenamenew= $insertedids[0].$newind."_".$count.".jpg";
$temp='menu_images/'.$filenamenew;
$im = imagecreatetruecolor(700, 700);
$bg = imagecolorallocate ( $im, 255, 255, 255 );
imagefilledrectangle($im,0,0,700,700,$bg);
$max_width=700;
$max_height= 700;
$width = imagesx($tmp);
$height = imagesy($tmp);
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$im2 = imagescale($tmp, $width, $height);
imagecopy($im, $im2, (imagesx($im)/2)-(imagesx($im2)/2), (imagesy($im)/2)-(imagesy($im2)/2), 0, 0, imagesx($im2), imagesy($im2));
imagejpeg($im, NULL , 70);
我正在尝试将这个最终的$im
上传到bucket,我已经在我的cent-os-中安装了gd库
imagesx()
需要一个图像资源作为参数,由一个图像创建函数(例如imagecreatetruecolor()
(返回。如果您需要图像的高度或宽度,可以使用getimagesize()
,如下所示。
list( $width, $height ) = getimagesize( 'filepath' );
试试这个:
...
foreach($_FILES[$ind]['name'] as $fid => $actfile){ // add $fid in here!
...
list($width, $height) = getimagesize($tmp=$_FILES[$ind]['tmp_name'][$fid]);
echo "width: $width; height: $height<br />n";
...
}
...
关键问题是将sourcefile
发布到s3 bucket,我将其更改为body
,还更改了php设置,允许文件上传到5 mb
以下是解决方案:
$im = imagecreatetruecolor(700, 700);
$bg = imagecolorallocate ( $im, 255, 255, 255 );
imagefilledrectangle($im,0,0,700,700,$bg);
list( $width, $height , $image_type ) = getimagesize($tmp);
$max_width=700;
$max_height= 700;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
switch ($image_type)
{
case 1: $im3 = imagecreatefromgif($tmp); break;
case 2: $im3 = imagecreatefromjpeg($tmp); break;
case 3: $im3 = imagecreatefrompng($tmp); break;
default: return ''; break;
}
$im2 = imagescale($im3, $width, $height);
imagecopy($im, $im2, (imagesx($im)/2)-(imagesx($im2)/2), (imagesy($im)/2)-(imagesy($im2)/2), 0, 0, imagesx($im2), imagesy($im2));
$imgdata = image_data($im);
function image_data($gdimage)
{
ob_start();
imagejpeg($gdimage,NULL,70);
return(ob_get_clean());
}
并且在上传到桶时
$result = $s3->putObject([
'Bucket' => 'yourbucket',
'Key' => 'filename',
'Body' => $imgdata
]);