UploadController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Storage;
  6. use Intervention\Image\Facades\Image;
  7. use function MongoDB\BSON\toJSON;
  8. use yasmuru\LaravelTinify\Facades\Tinify;
  9. class UploadController extends Controller
  10. {
  11. /**
  12. * @param Request $request
  13. * @return \Illuminate\Http\JsonResponse
  14. */
  15. public function image(Request $request)
  16. {
  17. if ($request->hasFile('file')
  18. && $request->file('file')->isValid()
  19. && in_array($request->file->extension(), ["png", "jpg", "jpeg", "gif"])
  20. ) {
  21. $path = $request->file->store(date('Ymd'), config('vienblog.disks.article_image'));
  22. $url = Storage::disk(config('vienblog.disks.article_image'))->url($path);
  23. if (env('TINIFY_APIKEY', '') && in_array($request->file->extension(), ["png", "jpg", "jpeg"])) {
  24. try {
  25. set_time_limit(300);
  26. $oldPath = public_path($url);
  27. $result = Tinify::fromFile($oldPath);
  28. $result->toFile(str_replace('.png', '.jpg', $oldPath));
  29. return response()->json(['filename' => str_replace('.png', '.jpg', $url)]);
  30. } catch (\Exception $e){
  31. return response()->json(['filename' => $url]);
  32. }
  33. }
  34. // $img = Image::make($oldPath);
  35. //
  36. // $thumbnailPath = pathinfo($oldPath, PATHINFO_DIRNAME).'/thumbnail/';
  37. //
  38. // if(!file_exists($thumbnailPath)){
  39. // mkdir ($thumbnailPath);
  40. // }
  41. //
  42. // $newPath = $thumbnailPath.pathinfo($oldPath, PATHINFO_FILENAME).'.jpg';
  43. //
  44. // $img->text('The quick brown fox jumps over the lazy dog.', 120, 100);
  45. //
  46. // $img->save($newPath, 100);
  47. return response()->json(['filename' => $url]);
  48. }
  49. }
  50. }