How to convert base64 to image/png content-type in php?

by jasen_gottlieb , in category: PHP General , 9 months ago

How to convert base64 to image/png content-type in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 months ago

@jasen_gottlieb 

You can convert a base64 encoded image to an image/png content type in PHP using the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

// Base64 encoded image
$base64_image = "data:image/png;base64,YourBase64EncodedImageHere";

// Extract the image data
list($type, $data) = explode(';', $base64_image);
list(, $data) = explode(',', $data);

// Decode the image data
$decoded_image = base64_decode($data);

// Save the image to a file
$file_name = 'output.png';
file_put_contents($file_name, $decoded_image);

// Output the image
header('Content-Type: image/png');
echo $decoded_image;

?>


This code will decode the base64 image data, save it as a PNG image file, and output the image in the PNG content type.