php laravel 图片保存

这是一个简单的图片保存功能,其中包括原图片和压缩图片两种,目录结构是/images/year/month/xxx.png和/images/thumbnail/year/month/xxx.png;具体上传结果如下图所示:

upload_icon.png
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;

public function uploadImage(Request $request)
{
    $inputData = $request->all();

    if ($request->hasFile('file')) {
        try {
            $year = date("Y");
            $month = "/images/$year/" . date("m");
            $directory = Storage::exists($month);
            if (!$directory) {
                Storage::makeDirectory($month);
            }
            $apath = "/images/thumbnail/$year/" . date("m");
            $thumbnail = Storage::exists($apath);
            if (!$thumbnail) {
                Storage::makeDirectory($apath);
            }
            $carid = strtoupper(md5(uniqid(mt_rand(), true)));
            $uuid = substr($carid, 0, 8) . substr($carid, 8, 4) . substr($carid, 12, 4) . substr($carid, 16, 4) . substr($carid, 20, 12);
            $file = $request->file('file');
            $extension = strtolower($file->getClientOriginalExtension());
            $photo = $inputData['file'];
            $file_name = $uuid . "." . $extension;
            $file_relative_path = 'storage/' . $month;
            $file_path = public_path($file_relative_path);
            if (!is_dir($file_path)) {
                mkdir($file_path);
            }
            $relative_path = 'storage/' . $apath;
            $thumbnail_path = public_path($relative_path);
            $thumbnail_file_path = $thumbnail_path . '/' . $file_name;
            $image = Image::make($photo)->resize(150, 150, function ($constraint) {
                $constraint->aspectRatio();
            })->save($thumbnail_file_path);
            $file_path .= '/' . $file_name;
            $image = Image::make($photo)->save($file_path);
            $path = $month . "/" . $file_name;
            if ($path) {
                return ['success' => true, 'path' => $path];
            } else {
                return ['errors' => ['file' => 'uploaderror']];
            }
        } catch (\Exception $e) {
            Log::error($e);
            return ['errors' => ['file' => $e->getMessage()]];
        }
    } else {
        return ['success' => false];
    }
 }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 7,334评论 0 13
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,173评论 1 45
  • 如以上DEMO截图所示效果,我们对于这种类似的功能肯定不算陌生,因为这可以说是实际开发中一类非常常见的功能需求了。...
    Machivellia阅读 7,227评论 1 13
  • 文/深小申 从离开家乡开始就在各种都市里混迹。在深夜有各种滋味的徘徊。漂泊感、孤独感,有时候也窃喜占有欲的实现。深...
    深小申阅读 2,325评论 1 1
  • 如果在这篇文章的开头,我大声说出:“完美世界本来就不存在!” 你有没有点崩溃的赶脚?哈哈 因为我们人类的内心都是向...
    绯姐养颜经阅读 4,101评论 0 2

友情链接更多精彩内容