1. 程式人生 > >php wangeditor編輯器,base64圖片儲存為檔案

php wangeditor編輯器,base64圖片儲存為檔案

php 字串圖片轉為檔案儲存

   /**
     * 編輯器base64_decode圖片匹配
     *
     * @author Eric
     * @param $str
     * @return mixed
     */
    public function nei_rong_img($str)
    {
        preg_match_all('/data:\S+/',$str,$res);
        $url = env('APP_URL').'/';
        $res = $res[0];
        if(count($res) > 0)
        {
            admin_toastr('圖片儲存中,請稍等', 'info');
            foreach ($res as $k => $v)
            {
                $path = $this->images_save(substr($v,0, strlen($v)-1));
                $str = str_replace(
                    $v,
                    $url.$path.'"',
                    $str);
            }
        }
        return $str;
    }

    /**
     * base64_decode圖片儲存到目錄
     *
     * @author Eric
     * @param $imgBase64
     * @return string
     */
    public function images_save($imgBase64)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/',$imgBase64,$res)) {
            //獲取圖片型別
            $type = $res[2];

            //圖片儲存路徑
            $new_file = 'upload/'.date('Y').'/'.date('m').'/'.date('d').'/';

            if (!file_exists($new_file)) {

                mkdir($new_file,0755,true);
            }

            //圖片名字
            $new_file = $new_file.time().Str::uuid().'.'.$type;
            file_put_contents($new_file,base64_decode(str_replace($res[1],'', $imgBase64)));
            return $new_file;
        }
    }