0

I'm using below code

Here $data is a byte array.

$decoded_data = base64_decode($data);
$im = imagecreatefromstring($decoded_data);

if ($im !== false) {
   header('Content-Type: image/png');
   $image_nam = "png_".time().".png";
    imagepng($im, $image_nam);
    imagedestroy($im);
}

But I don't get the exact output

Vincy Joseph
  • 223
  • 1
  • 3
  • 15
  • _“Here $data is a byte array”_ - base64_decode expects a string, not an array. And imagepng with the second parameter set writes the image to disk, it does not output the image data in that case - so you basically promised the browser an image via the Content-Type header, and then you failed to deliver any actual image data after that. – CBroe Jan 10 '18 at 10:53
  • try file_put_contents("png_".time().".png", $decoded_data); – Abhinav Jan 10 '18 at 11:18

2 Answers2

0

try this simple code for save image into directory

file_put_contents('/myfolder/imageName.jpg', base64_decode($img));

you can also try this

$base_to_php = explode(',', $base64Img);
$data = base64_decode($base_to_php[1]);
$filepath = "/path/imageName.png"; // or image.jpg
file_put_contents($filepath,$data);
Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42
0

I would suggest you to refer link -

This could be possible an issue with metadata present in base64 string.

As per source the problem could be due to data:image/png;base64, is included in binary string.

The metadata present in the binary string results in invalid image data when the decoded back. Can you try it by removing metadata in the function before decoding the string.

You may use function and write output to a new file.

$position_s= strpos($base64_string , "data:image/png;base64,");

substr($base64_string, 0, $position_s) . substr($base64_string, $position_s+ strlen("data:image/png;base64,");

Note: If you are preferring explode function, it would be best to set limits:

explode(',',$base64_string,2)
Jatish
  • 352
  • 1
  • 2
  • 10