W3docs

PHP - get base64 img string decode and save as jpg (resulting empty image )

To decode a base64 encoded image string and save it as a JPG file in PHP, you can use the following code:

To decode a base64 encoded image string and save it as a JPG file in PHP, you can use the following code:

Example of decoding a base64 encoded image string and saving it as a JPG file in PHP

<?php

// Base64-encoded image data (with data URI prefix)
$img_string = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhQUExMWFhUXGBcaGRgYGBcaGBgZGhgfGxoaHSggGB0lHRgaITEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGxAQGy0lICYtLS0tLS0tLS0tKy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAKgBLAMBIgACEQEDEQH. ..';

// Strip the data URI prefix if present
$img_string = preg_replace('/^data:image\/\w+;base64,/', '', $img_string);

// Decode the base64 string
$img = base64_decode($img_string);

if ($img === false) {
  echo "Failed to decode base64 string.";
  exit;
}

// Save as a file
$result = file_put_contents('image.jpg', $img);

if ($result === false) {
  echo "Failed to save image. Check folder permissions.";
} else {
  echo "Image saved successfully.";
}

Where $img_string is the base64 encoded image string.

Please note that if the resulting image is empty, it's likely that the input string is not a properly formatted base64 encoded image. Also, check the permissions of the folder where you are saving the image and make sure that the folder has write permissions.