force download image as response lumen + intervention image

Juliver Galleto

I'm using intervention image on my Lumen project and everything works until I come across on making the encoded image as a downloadable response which upon form submit that contains the image file that will be formatted unto specific format e.g. webp, jpg, png will be sent back as a downloadable file to the user, below is my attempt.

public function image_format(Request $request){
    $this->validate($request, [
        'image' => 'required|file',
    ]);

    $raw_img = $request->file('image');

    $q = (int)$request->input('quality',100);
    $f = $request->input('format','jpg');

    $img = Image::make($raw_img->getRealPath())->encode('webp',$q);

    header('Content-Type: image/webp');

    echo $img;
}

but unfortunately, its not my expected output, it just did display the image.

from this post, I use the code and attempt to achieve my objective

public function image_format(Request $request){
        $this->validate($request, [
            'image' => 'required|file',
        ]);

        $raw_img = $request->file('image');

        $q = (int)$request->input('quality',100);
        $f = $request->input('format','jpg');

        $img = Image::make($raw_img->getRealPath())->encode('webp',$q);
        $headers = [
            'Content-Type' => 'image/webp',
            'Content-Disposition' => 'attachment; filename='. $raw_img->getClientOriginalName().'.webp',
        ];

        $response = new BinaryFileResponse($img, 200 , $headers);
        return $response;
    }

but its not working, instead it showed me this error

enter image description here

any help, ideas please?

Rwd

In Laravel you could use the response()->stream(), however, as mentioned in the comments, Lumen doesn't have a stream method on the response. That being said the stream() method is pretty much just a wrapper to return a new instance of StreamedResponse (which should already be included in your dependencies).

Therefore, something like the following should work for you:

$raw_img = $request->file('image');

$q = (int)$request->input('quality', 100);
$f = $request->input('format', 'jpg');

$img = Image::make($raw_img->getRealPath())->encode($f, $q);

return new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($img) {
    echo $img;
}, 200, [
    'Content-Type'        => 'image/jpeg',
    'Content-Disposition' => 'attachment; filename=' . 'image.' . $f,
]);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related