使用Laravel将图像转换为Base64字符串

21

我想用Laravel将图像转换为base64编码。我从表单中获取图像。 我在我的控制器中尝试了以下代码:

public function newEvent(Request $request){
    $parametre =$request->all();

    if ($request->hasFile('image')) {
        if($request->file('image')->isValid()) {
            try {
                $file = $request->file('image');
                $image = base64_encode($file);
                echo $image;


            } catch (FileNotFoundException $e) {
                echo "catch";

            }
        }
    }
我只得到了这个:

L3RtcC9waHBya0NqQlQ=


2
$request->file() doesn't return the actual file content but an instance of UploadedFile. You need to load the actual file to convert it. Try: $image = base64_encode(file_get_contents($request->file('image')->path())); - M. Eriksson
对于第一个,我认为这个工作是将$file(即$request->file('image'))的内容进行base64编码。 - Pondikpa Tchabao
现在我想解码并保存,但这不起作用 file(base64_decode($image))->move("images", $name); - Pondikpa Tchabao
我已将我的评论添加为答案,以便您可以接受它,因为它解决了您的主要问题。 - M. Eriksson
我不确定你想做什么。你的变量 $image 包含了经过 base64 编码的图像数据。如果你解码它,它只是二进制数据,而不是 PHP 类。 - M. Eriksson
显示剩余7条评论
4个回答

43

Laravel的$request->file()方法不会返回实际的文件内容,而是返回一个UploadedFile类的实例。

你需要加载实际的文件才能进行转换:

$image = base64_encode(file_get_contents($request->file('image')->pat‌​h()));

这个是什么目的?我只是想知道,我有点困惑为什么你需要转换它? - Biax20
@Biax20 他们可能希望将其存储在数据库中,例如以字符串形式。 - Healyhatman
@Biax20 他们可能希望将其存储为字符串形式在数据库中,这只是一个例子。 - undefined

26

这对我有帮助的方法如下:

$image = base64_encode(file_get_contents($request->file('image')));

我删除了这部分代码 ->pat‌​h();


当我尝试这个时,我得到了这个错误:"file_get_contents(): Filename cannot be empty"。 - Sreekuttan

2

不要忘记添加文件类型。

pdf 的示例:

$file = "data:@file/pdf;base64,".base64_encode(file_get_contents($request->file('image')));

图片示例:

$file = "data:image/png;base64,".base64_encode(file_get_contents($request->file('image')));

0
//html code
<input type="file" name="EmployeeImage">

//laravel controller or PHP code
$file = $request->file('EmployeeImage');
$image = base64_encode(file_get_contents($file)); 

// display base64 image
echo '<img src="data:image/png;base64,' . $image . '" />'; exit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接