Dinesh Kumar
Dinesh Kumar

Reputation: 147

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?

Upvotes: 1

Views: 6956

Answers (2)

Gerrlt
Gerrlt

Reputation: 39

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

Upvotes: 1

DarkGhostHunter
DarkGhostHunter

Reputation: 1550

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.

Upvotes: 1

Related Questions