如何为Base64解码图像保存在laravel公用文件夹

问题描述 投票:-1回答:2

我与格式字符串的base64图像,我想该字符串解码为图像并将其保存到公用文件夹中laravel。

这是我的控制器:

//decode string base64 image to image 
$image = base64_decode($request->input('ttd'));
//create image name
$photo_name = time().'.png';
$destinationPath = public_path('/uploads');
//save image to folder
$image->move($destinationPath, $photo_name);
$img_url = asset('/uploads'.$photo_name);


$data = new Transaction();
$data->transaction_id = $request->input('fa_transaction_id');
$data->user_id = $request->input('userid');
$data->photo_name = $photo_name;
$data->photo_url = $img_url;
$data->save();

当我尝试回声$形象,我得到解码值,同时还为$ PHOTO_NAME我得到的值太大,但是当函数运行我得到这个错误

Call to a member function move() on string

如何解决这个问题?

php laravel laravel-4 php-7
2个回答
3
投票
//Controller

use Illuminate\Support\Facades\Storage;

//Inside method

    $image = $request->image;  // your base64 encoded
    $image = str_replace('data:image/png;base64,', '', $image);
    $image = str_replace(' ', '+', $image);
    $imageName = str_random(10) . '.png';

    Storage::disk('local')->put($imageName, base64_decode($image));

此外,请确保您的local磁盘配置一样,在/config/filesystems.php

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
    ]

就这样,文件将被保存在/storage/app/public目录。

不要忘了写php artisan storage:link使从该目录中的文件目录/public可用,这样用户就可以检索它们。


0
投票

在数据库中不保存的图像存储在数据库图像的推荐方法,原因是内存速度的提升,正确的方法链接只是保存到它。 无论如何,你可以在base64与这些行代码保存图像。 获得从路径正确的图像在您的服务器不从$path链接。

<?php
    // Base 64 transform image
    $path = __DIR__ .'/myfolder/myimage.png';
    $type = pathinfo($path, PATHINFO_EXTENSION);
    $data = file_get_contents($path);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    echo $base64;
© www.soinside.com 2019 - 2024. All rights reserved.