4

I have base64 image and I want to return the image preview not the base64 code.

I tried

return response(base64_decode($results->getBase64Image()), 200, ['Content-Type' => 'image/png']);

but it returns a weird output. Result

Kerwin
  • 339
  • 1
  • 7
  • 18

6 Answers6

3

Laravel 5.8 and above...

Just straightaway put the string into response()... and add header('Content-Type', 'image/png')

For example:

$raw_image_string = base64_decode($base64_img_string);

return response($raw_image_string)->header('Content-Type', 'image/png');
Syamsoul Azrien
  • 2,534
  • 4
  • 32
  • 55
1

I just found an answer. imagecreatefromjpeg() php

$image = imagecreatefromstring(base64_decode($results->getBase64Image()));
        header('Content-type: image/png');
        return imagejpeg($image);
Kerwin
  • 339
  • 1
  • 7
  • 18
0

I have used this.. for base 64 images ))))

function store()
{
    $data = $this->request->img;
    list($type, $data) = explode(';', $data);
    list(, $data) = explode(',', $data);

    $directory_bucekts = implode('/',str_split(strtolower(str_random(2))));

    Storage::disk('public')->makeDirectory('images/shopdata/'.$directory_bucekts, true, true);

//        mkdir(storage_path('app/public/images/shopdata/'.$directory_bucekts), 755, true);

    $data         = base64_decode($data);

    $fileName     = time().rand(100,1000).'.jpg';
    $path         = storage_path('app/public/images/shopdata/'.$directory_bucekts);

    file_put_contents($path .'/'. $fileName, $data);

    return response()->make(['path' =>  '/storage/images/shopdata/' . $directory_bucekts. '/' .$fileName]);

}
Etibar
  • 578
  • 6
  • 22
0

You may return the base64 code to a view and in the view, render the image using <img> tag

$base64code = $results->getBase64Image();
return view('preview', compact('base64code'));

Blade File:

<img src="data:image/png;base64, {{ $base64code }}" alt="Image Preview" />
linktoahref
  • 7,812
  • 3
  • 29
  • 51
0

Try this

class ImagesController extends Controller{

  public function store(Request $request, YourImageModel $imageModel){
    
    $image = base64_decode($imageModel->base64Content);
    $path = Storage::putFile('images', $image);
    
    return response()->file($path);

  }

}

You can read the doc for Request File uploading, File Uploading and File Responses, they all are under Laravel's documentation.

Have a nice day :)

-1

Try this:

        $data = base64_decode($results->getBase64Image());
        $image_name= time().'_test_.png';
        $path = public_path() .'/'. $image_name;

        file_put_contents($path, $data);

        //serve the image
       return  response()->file($path);

See Docs.

Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
  • Thank you, but it only saves the image to the public folder, is there a way to create preview of the image? – Kerwin Jan 29 '18 at 08:06