简体   繁体   中英

How to display Blob image in Laravel blade template file?

I want to display images from my database which are stored as blob images. I do the following:

echo '<img src="data:image/JPG;base64,'.base64_encode($item->image).'"/>'; ?>

It gives me the error:

The image cannot be displayed because it contains errors

This is how I upload

$base64 = base64_encode($img);

DB::table('items')->InsertGetId([
        'item'=>$item,
        'des'=>$des,
        'unit_sel'=>$sell,
        'unit'=>$unit,
        'stock'=>$stock,
        'weight'=>$weight,
        'cat'=>$cat,
        'image'=>$base64
    ]);

I use laravel 5.5. How can I resolve this issue?

I already replied in Reddit , but I will summarize 3 points:

  • You're saving images into the database, which should be avoided unless you know what are you doing, and don't care about scalability, resources, performance, for sake of tight image control.
  • You're using echo instead of double curly braces {{ }} in Blade templates, which can allow Persistent XSS atacks .
  • You have already encoded your image to base64 when you stored it. In your view code, you must use the already-base64-encoded string instead of encoding or decoding it again.

If you need to store the images in database I recommend to make separate route for image retrieving, because in this way the browsers cache the image and avoid querying the database each time the image has to be shown, and speeds up pages with a lot of images.

I store the image as BLOB in MYSQL PRODUCT table identified by product_id

BLADE:

<img src="/dbimage/{{$product->id}}.png" >

ROUTE:

Route::get('/dbimage/{id}',[ProductImageController::class, 'getImage']);

CONTROLLER:

class ProductImageController extends Controller
{

    public function getImage($prodcutImageID){
        $productID=explode(".",$prodcutImageID);
        $rendered_buffer= Product::all()->find($productID[0])->image;

        $response = Response::make($rendered_buffer);
        $response->header('Content-Type', 'image/png');
        $response->header('Cache-Control','max-age=2592000');
        return $response;
    }

}

This makes the browsers cache the images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM