Laravel+Intervention Implementation of Upload Picture Function Example

  • 2021-12-12 08:13:04
  • OfStack

In this paper, an example is given to describe the function of uploading pictures by Laravel+Intervention. Share it for your reference, as follows:

Problem

Upload pictures using Laravel

Solve

Installing Intervention

Follow this link to install https://packagist.org/packages/intervention/image

Using Intervention

Use http://image.intervention.io/getting_started/introduction according to this document

Simple modification

Use the following code to upload pictures


Image::make(Input::file('photo'))->resize(300, 200)->save('foo.jpg');

Because Intervention save time need to specify the image saved file name, so I wrote a tool class to generate a random file name.


<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/2 0002
 * Time: 17:34
 */
namespace App\Libs;
class UploadUtils {
  /**
   *  Random file name 
   * @param int $len  Length of random file name 
   * @return str  Random string 
   */
  private static function randName($len = 10) {
    return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234565789'), 0, $len);
  }
  /**
   *  Create the path to upload the file 
   * @return str  Path to upload files 
   */
  private static function createDir() {
    $dir = env('UPLOADPATH') . date('Ymd', time());
    if (is_dir($dir) || mkdir($dir, 0777, true)) {
      return $dir;
    }
  }
  /**
   *  Get the path of the uploaded file 
   * @return str  Full path of file 
   */
  public static function getUploadPath($ext = 'jpg') {
    return self::createDir() . '/' . self::randName() . '.' . $ext;
  }
}

Upload processing


// Upload thumbnails 
if ($request->hasFile('thumb')) {// There are pictures 
   $file = $request->file('thumb');
   $path = UploadUtils::getUploadPath($file->guessExtension());// Get the saved file path 
   Image::make($file)->resize(env('THUMB_WIDTH'), env('THUMB_HEIGHT'))->save($path);// Save 
   ...
   #save database
   ...
}

More readers interested in Laravel can check the topics of this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: