微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Unisharp Laravel处理文件上传并调整图像大小

如何解决使用Unisharp Laravel处理文件上传并调整图像大小

我正在为Laravel项目使用Unisharp文件上传。包装正常。现在我想要的是,我想要具有以下文件类型的数组:

[name] => MyFile.jpg      
[type] => image/jpeg
[tmp_name] => /tmp/PHP/PHP6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
Unisharp文件管理器的图像URL的

。假设如果我从Unisharp filemanager中选择http://example.com/storage/files/42/lace-up.png,我想得到上面的文件数组。

我想要这个,因为我想相应地调整图像大小并将其存储到其他文件夹中。

我创建了以下功能上传和调整图像大小:

function uploadImage($file,$dir,$thumb_dimension=null){

  $path = public_path().'/uploads/'.$dir;

  if(!File::exists($path)){
      File::makeDirectory($path,0777,true,true);
  }

  $file_name = ucfirst($dir).'-'.date('Ymdhis').rand(0,999).".".$file->getClientOriginalExtension();
  $success = $file->move($path,$file_name);
  if($success){
      $file_path = $path.'/'.$file_name;
      if($thumb_dimension){
          list($width,$height) = explode('x',$thumb_dimension);
          Image::make($file_path)->resize($width,$height,function($const){
              $const->aspectRatio();
          })->save($path.'/Thumb-'.$file_name);
      }
      return $file_name;
  } else {
      return null;
  }
}

有可能吗?

修改

获取图像细节后,我想使用以下功能

function uploadImage($file,true);
  }
  
  $file_name = ucfirst($dir).'-'.date('Ymdhis').rand(0,function($const){
              $const->aspectRatio();
          })->save($path.'/Thumb-'.$file_name);
      }
      return $file_name;
  } else {
      return null;
  }
}

解决方法

如果您只想从链接中提取图像,则只需创建一个小函数即可处理它。

public function getImageViaLink($link){
    try {
        $info = pathinfo($link);
        $image = file_get_contents($link);
        $arr['basename'] = $info['basename'];
        $file_info = new \finfo(FILEINFO_MIME_TYPE);
        $mime_type = $file_info->buffer($image);
        $arr['size'] = strlen($image);
        $arr['mime_type'] = $mime_type;
        $path = public_path() .'/'. $arr['basename'];
        
        // You can save contents of link in your file directly or store it in tmp
        file_put_contents($path,$image);
        $arr['path'] = $path;
        return $arr;
    }
    catch (Exception $e) {
        echo $e->getMessage();
    }
        
}

对于数组中error的情况,您基本上想要file upload errors,但可以很容易地由Exception处理。

作为旁注,如果在使用unisharp存储图像时具有request变量,则可以在$ request中访问所有这些详细信息。

// dd() of a request containing image file.
array:2 [▼
  "_token" => "e7v7ZxaKoIFGIYOscCAFwsoB8olw8lrNjwx8Azyi"
  "attachment_1_0" => UploadedFile {#229 ▼
    -test: false
    -originalName: "db.png"
    -mimeType: "image/png"
    -size: 86110
    -error: 0
     path: "C:\xampp\tmp"
     filename: "phpF4F4.tmp"
     basename: "phpF4F4.tmp"
     pathname: "C:\xampp\tmp\phpF4F4.tmp"
     extension: "tmp"
     realPath: "C:\xampp\tmp\phpF4F4.tmp" 
    
 ... and many more

您可以创建一个侦听器,无论何时存储图像,您都可以创建包含所有详细信息的另一个副本,以将其保存到其他位置。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。