Wai Yan Hein
Wai Yan Hein

Reputation: 14811

Serving PHP image resource as response in Laravel

I am developing a web application. In my application, I need to work with some images and display it on the browser. But I am not saving the image as a file and access the file from the path. I am not doing it for some reason. Instead, I am creating an image resource from some kind of byte data and then serving it.

This is my code in the controller.

function serveS3Image(Request $request)
{
    $image_data = Storage::disk('s3')->get($request->get('identifier'));
    $data = imagecreatefromstring($image_data);
    header('Content-Type: image/png');
    imagepng($data);
}

When I access the action from the browser, it is displaying me correct image. But I want to do it in more Laravel way. Something like this:

function serveS3Image()
{
     return Response::ImageResource($data);
}

How can I return the PHP image resource?

Upvotes: 2

Views: 4723

Answers (3)

Levente Otta
Levente Otta

Reputation: 795

I found same question on Laracast like your. Look at this thread. I hope it will help to you.

EDIT: add code from laracast

public function downloadAsset($id)
{
    $asset = Asset::find($id);
    $assetPath = Storage::disk('s3')->url($asset->filename);

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . basename($assetPath));
    header("Content-Type: " . $asset->mime);

    return readfile($assetPath);
}

Upvotes: 2

Wai Yan Hein
Wai Yan Hein

Reputation: 14811

Finally, I have got the solution based on some answers. I just needed to return like this.

return response(Storage::disk('s3')->get($request->get('identifier')))->header('Content-Type', 'image/png');

In the response, I passed image data, not the file path. Then I set the content type in the header. Thanks eveyone.

Upvotes: 2

Dezigo
Dezigo

Reputation: 3256

https://laravel.com/docs/5.5/responses#file-responses

The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.

This method accepts the path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Upvotes: 0

Related Questions