基于laravel,一个下载远程图片到本地, 返回 MD5的方法

php

浏览数:2,111

2019-1-7


RemoteImage.php

<?php
    /**
     * 下载远程图片到本地, 返回 MD5
     *
     * @param $url
     *
     * @return string
     */
    public function downloadRemoteImage($url)
    {
        $url = (string)$url;
        $file = request_url($url);
        if (!$file) return '';

        $fileInfo = getimagesizefromstring($file);
        if (!$fileInfo) return '';

        $fileType = explode('/', $fileInfo['mime']);
        if (empty($fileType) || $fileType['0'] != 'image' || !in_array($fileType[1], $this->imageAllowType)) {
            return '';
        }

        // 大小判断
        if (strlen($file) > $this->imageAllowSize) {
            return '';
        }

        // 是否已经上传过
        $md5 = md5($file);
        $path = $this->md52url($md5, 'image', true);
        if (!is_file($path) || getimagesize($path) == false) {
            File::makeDirectory(dirname($path), 0777, true, true);
            File::put($path, $file);
        }

        return $md5;
    }