为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Laravel 中从公共文件夹检索图像并转换为 base64?

如何在 Laravel 中从公共文件夹检索图像并转换为 base64?

PHP
动漫人物 2023-08-06 15:54:35
我想从我存储所有图像的公共文件夹中获取图像文件,然后将其转换为base64. 我将使用该base64图像在 dataTables 中使用 PDF 来查看它pdfmake,因为我的 dataTable 单元格有一个名为 的图像avatar,并且正如我所搜索的那样,它需要将图像转换为 base64 才能在 PDF 中查看。现在我用来file_get_contents检索我的图像,但我的页面加载太多,我猜大约需要 5 分钟,并且在 throws 和 error 之后Maximum execution time of 60 seconds exceeded。{{ file_get_contents( asset('files/user_avatar.png') ) }}
查看完整描述

3 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

当您编码为 base64 时,svg 和 (jpg-png-jpeg) 之间存在差异。当您处理 png 图像时,您基本上可以使用 png 扩展名。但是你基本上不能使用svg。使用 svg 时需要 svg+xml。


function img_enc_base64 ($filepath){   // img_enc_base64() is manual function you can change the name what you want.


    if (file_exists($filepath)){


        $filetype = pathinfo($filepath, PATHINFO_EXTENSION);


        if ($filetype==='svg'){

            $filetype .= '+xml';

        }


        $get_img = file_get_contents($filepath);

        return 'data:image/' . $filetype . ';base64,' . base64_encode($get_img );

    }

}

所以现在


echo img_enc_base64('file_path');  // is your base64 code of image


<img src="<?php echo img_enc_base64('file_path');?>" alt="">  // is your image

文件路径示例:pics/my_book.png


查看完整回答
反对 回复 2023-08-06
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

我不友好,Laraval但我有一个经过测试的答案写在PHP


<?php

    $path = "files/user_avatar.png";

    $type = pathinfo($path, PATHINFO_EXTENSION);

    $data = file_get_contents($path);

    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

    # print to make sure that it is working or not

    echo $base64."<br>";

    # Or, show it as a clean image

    echo '<img scr="'.$base64.'" height="150" width="150">';

?>

上面的代码片段仅仅因为功能而不起作用file_get_contents

解决方案:

使用curl_get_contents()而不是file_get_contents

curl_get_contents()

function curl_get_contents($url){

$ch = curl_init();


curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_URL, $url);


$data = curl_exec($ch);

curl_close($ch);


return $data;

}

file_get_contents替换成后curl_get_contents


$path = "files/user_avatar.png";

$type = pathinfo($path, PATHINFO_EXTENSION);

$data = curl_get_contents($path);

$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

# print to make sure that it is working or not

echo $base64."<br>";

# Or, show it as a clean image

echo '<img scr="'.$base64.'" height="150" width="150">';

加载时间仍然太长? 尝试检查您的文件大小或尝试检查Server-Configuration


希望对你有帮助😊


查看完整回答
反对 回复 2023-08-06
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

我认为应该是:


$path = 'files/user_avatar.png';

$type = pathinfo($path, PATHINFO_EXTENSION);

$data = file_get_contents($path);

$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

请记住,这会将数据扩大 33%,并且文件大小超过内存限制时会出现问题。


查看完整回答
反对 回复 2023-08-06
  • 3 回答
  • 0 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信