1

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?

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

1 Answers1

0

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,
]);
Rwd
  • 34,180
  • 6
  • 64
  • 78
  • What class am I to import for the Image class to work. Lumen – richard4s Jun 28 '20 at 17:32
  • @richard4s As in you're wanting to know the fully qualified namespace for the `Image` class? – Rwd Jun 28 '20 at 21:16
  • @richard4s It should be the same as the [Intervention Image Docs](http://image.intervention.io/getting_started/installation): `Intervention\Image\Facades\Image`. – Rwd Jun 29 '20 at 21:17