Search code examples
phplaravellaravel-9

Laravel 9: Converting An Image From Bytes To Jpeg From Storage Directory


I'm using Laravel 9 and I wanted to show an image which is stored at storage/app/avatars.

So I tried this at the Blade:

{{ \App\Http\HelperClasses\ImageHelper::admAvatar() }}

And this is the ImageHelper Class:

namespace App\Http\HelperClasses;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;

class ImageHelper
{
    public static function admAvatar()
    {
        $content = Storage::get('avatars/profile.png');

        return Response::make($content)->header('content-type','image/jpeg');
    }
}

So I tried making an image from the profile.png and return it after all.

But the problem is it does not show anything!

And when I dd(Response::make($content)->header('content-type','image/jpeg')), I get this:

enter image description here

And the result of dd($content) also goes like this:

enter image description here

So how can I convert this properly into an image?


Solution

  • I did it like this

    Controller:

    public function getFile($type, $id) {
        $attachment = Attachment::where([['parent_type', $type], ['parent_id', $id]])->latest()->firstOrFail();
        $headers = ['content-type' => 'image/jpeg'];
        $contents = Storage::get($attachment->file_path); 
        return response($contents, 200, $headers); 
    }
    

    Routes:

    Route::get('/attachments/display/{type}/{id}', [App\Http\Controllers\AttachmentController::class, 'getFile']);
    

    HTML:

    <img src="/attachments/display/avatar/1" />