如何从数据库中获取图像以在laravel中查看文件

fzsnzjdm  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(462)
<img  src="{{$post->image}}"  width="140" height="140">

这是我用来从数据库获取图像以查看文件的行
我用贝娄控制器得到这个图像

public function show($id)
{

    $post=Clients::find($id);
    return view('pet.shw',['post'=>$post,'pets'=>$post->pets]); }

迁移文件如下所示

public function up()
{
    Schema::create('clients', function (Blueprint $table) {
        $table->increments('id');
        $table->string('ename');
        $table->string('mobile');
        $table->string('mail');
        $table->binary('image') ; //image that i wanna use 
        $table->mediumText('Discription');
        $table->timestamps();
    });
}

这种方法不起作用视图显示这样我如何解决这个问题,建议新的方法更好,我不能使用公共/存储文件夹,因为所有的图像都应该保存在数据库中

ecfdbz9o

ecfdbz9o1#

试试这个

$img = base64_encode($post->image);

<img src="data:image/jpg;charset=utf8;base64,<?php echo $img ?>"/>

或者,您可以用以下内容替换图像行

<img src="data:image/jpg;charset=utf8;base64,{{base64_encode($post->image)}}"/>

要动态设置mime类型,请创建一个helper函数并使用它

function constructImageFromBinary($file, $mime) 
{  
  $contents = file_get_contents($file);
  $base64   = base64_encode($contents); 
  return ('data:' . $mime . ';charset=utf8;base64,' . $base64);
}

并使用blade模板中的帮助功能,如下所示

<img src="@php echo constructImageFromBinary($post->image,'image/png'); @endphp"/>

相关问题