Generate image extension from mimetype

2019-09-03 00:42发布

问题:

I have been trying image uploading in Laravel 5 (upload generated through laravelcollective/forms, and processed using Intervention Image library). What I wanna do is when user uploads any photo, I want to set the extension based on its mimetype. There should be some basic check to protect against spurious data injection.

$file_profile_image->getClientMimeType();

To do that, should I simply be mapping like so ?

['image/jpeg' => 'jpg', 'image/gif'=> 'gif']

回答1:

I would use the Intervention package to check if you're loading a valid image and get the mime from there.

Something like this:

/**
 * Store a file
 *
 * @return Response
 */
public function store(Filesystem $filesystem)
{
    // check if file was posted

    $uploadedFile = Request::file('file');

    // other checks here, ->isValid() && filesize

    try {
        $image = Image::make(\File::get($uploadedFile));
    } catch (\Intervention\Image\Exception\NotReadableException $e) {
        \Log::error('Unsupported filetype');
        dd('Unsupported filetype');
        // return proper error here
    }

    // mime as returned by Intervention
    $mime = $image->mime();

    // other stuff
    // store @ fs
}


回答2:

This is how I would do it:

$source_file = $request->file('image')->getRealPath();
$info = get_image_details($source_file);

The get_image_details($path) function can be defined as follows:

function get_image_details($path)
{
    $details = @getimagesize( $path );

    if ( is_array($details) && count($details) > 2 ) {

        $info = [
            'width' => $details[0],
            'height' => $details[1],
            'mime' => $details['mime'],
            'size' => @filesize($path),
            'path' => $path,
        ];

        switch ($details['2']) {
            case IMG_PNG:
            case 3:
                $info['type'] = 'png';
            break;

            case IMG_JPG:
            case 2:
                $info['type'] = 'jpg';
            break;

            case IMG_GIF:
            case 1:
                $info['type'] = 'gif';
            break;

            default:
                $info['type'] = $details[2];
            break;
        }

        return $info;
    }
    return false;
}