iftekhs's avatar
Level 13

How to turn uploaded svg image into base64 png image?

Hi, I am receiving an SVG image from the user and I want to turn that image into a base64 encoded image. how can I do that?

0 likes
8 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102
$content = $request->file('image')->getContent();
$base64  = base64_encode($content);
iftekhs's avatar
Level 13

@Sinnbeck I did this ->

  $custom_logo = 'data:image/' . 'png' . ';base64,' . base64_encode($request->file('custom_logo')->getContent());

but when I put it in an image tag it doesn't work.

kokoshneta's avatar

@iftekhs Of course that won’t work. You can’t convert an SVG image to a valid PNG image just by base64-encoding it with the prefix png.

You’ll need to use ImageMagick or some similar image library to load the SVG file and convert that to a PNG file. That’s not particularly a Laravel issue, though, you can use any plain PHP for that (Googling “PHP convert SVG to PNG” will give you plenty of ways to do it).

But is there a reason why you want to turn an SVG into a PNG? If it’s a logo, and the original is SVG, why do you need a PNG?

iftekhs's avatar
Level 13

@kokoshneta Actually I was using a kind of package and I thought that it only accepted base64 png image but I was wrong I was doing this ->

data:image/svg;base64

I forgot the +xml part ->

data:image/svg+xml;base64
1 like

Please or to participate in this conversation.