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

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

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

  1. public function show($id)
  2. {
  3. $post=Clients::find($id);
  4. return view('pet.shw',['post'=>$post,'pets'=>$post->pets]); }

迁移文件如下所示

  1. public function up()
  2. {
  3. Schema::create('clients', function (Blueprint $table) {
  4. $table->increments('id');
  5. $table->string('ename');
  6. $table->string('mobile');
  7. $table->string('mail');
  8. $table->binary('image') ; //image that i wanna use
  9. $table->mediumText('Discription');
  10. $table->timestamps();
  11. });
  12. }

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

ecfdbz9o

ecfdbz9o1#

试试这个

  1. $img = base64_encode($post->image);
  2. <img src="data:image/jpg;charset=utf8;base64,<?php echo $img ?>"/>

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

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

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

  1. function constructImageFromBinary($file, $mime)
  2. {
  3. $contents = file_get_contents($file);
  4. $base64 = base64_encode($contents);
  5. return ('data:' . $mime . ';charset=utf8;base64,' . $base64);
  6. }

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

  1. <img src="@php echo constructImageFromBinary($post->image,'image/png'); @endphp"/>
展开查看全部

相关问题