Convert Base64 string to an image file?
To convert a Base64 string to an image file in PHP, you can use the base64_decode() function to decode the Base64 string and then save it as an image file using file_put_contents().
To convert a Base64 string to an image file in PHP, you can use the base64_decode() function to decode the Base64 string and then save it as an image file using file_put_contents(). Here's an example:
How to convert a Base64 string to an image file in PHP?
<?php
$base64_image = "YOUR_BASE64_STRING";
// Strip Data URI prefix if present (e.g., data:image/png;base64,)
$base64_image = preg_replace('/^data:image\/\w+;base64,/', '', $base64_image);
$image = base64_decode($base64_image);
if ($image === false) {
die('Invalid Base64 string.');
}
file_put_contents('image.jpg', $image);This will create a new image file called "image.jpg" and save the decoded image data.
You can also specify the file type by replacing "jpg" with the desired file extension. For example, you could use "png" or "gif" instead.
Keep in mind that the Base64 string should contain the raw image data. If you are using a Data URI format (e.g., data:image/png;base64,...), you must strip the prefix before decoding.