如何在Laravel 5.4中将base64转换为图像?

7

我正在使用Laravel 5.4开发API。我将以base64格式接收图片。如何在Laravel中将base64转换为图片?


3个回答

5
此解决方案将处理所有类型的图像。
 $image = $request->input('image'); // image base64 encoded
 preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
 $image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
 $image = str_replace(' ', '+', $image);
 $imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
 Storage::disk('public')->put($imageName,base64_decode($image));

$image_extension 是什么?在这里没有定义。 - ahinkle
执行 preg_match 函数后,$image_extension 变量将包含图像扩展名。 - Yehia Salah
太棒了,兄弟,你救了我的一天。愿上帝保佑你。 - Hadayat Niazi

0

1- 使用intervention image包

use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic;
use Illuminate\Support\Str;

$logo      = ImageManagerStatic::make($request->logo)->encode('png');
            $logo_name = Str::random(40) . '.png';

            Storage::disk('s3')->put('products_seller/' . $logo_name, $logo);

0
我找到了解决方案:
use Illuminate\Support\Facades\Storage;

function createImageFromBase64(Request $request)
{
   $file_data = $request->input('image_file');
   $file_name = 'image_' . time() . '.png'; //generating unique file name;

   if ($file_data != "") { // storing image in storage/app/public Folder
       Storage::disk('public')->put($file_name, base64_decode($file_data));
   }
}

你能先尝试使用PNG图像吗? - Simon Shrestha
你是指实际的图像吗?如果是的话,它运行得相当不错。 - Agil
你发送的API中的base64图片可能是jpg格式的。上述代码将其保存为.png格式,因此会损坏。请先将png图片转换为base64,然后再使用上述代码。 - Simon Shrestha
哈哈,我已经尝试过了。我使用了上传之前相同的类型,但它并没有起作用。 - Agil
什么问题? - Simon Shrestha
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接