Laravel return image preview from base64

走远了吗. 提交于 2020-07-09 04:17:17

问题


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.


回答1:


I have been use 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]);

}



回答2:


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.




回答3:


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" />



回答4:


I just found an answer. imagecreatefromjpeg() php

$image = imagecreatefromstring(base64_decode($results->getBase64Image()));
        header('Content-type: image/png');
        return imagejpeg($image);



回答5:


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');


来源:https://stackoverflow.com/questions/48496474/laravel-return-image-preview-from-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!