0

I am trying to generate an image using base64_decode with png extension, but generated png image is wrong, it is showing "invalid image".

my code is below

$base_64 = $this->input->post('base_64');
$decoded_base_64 = base64_decode($base_64);
$result = file_put_contents('directory/toSaveImage/' . $id . '.png', $decoded_base_64);

While searching for the solution i also tried adding before the $result variable.

    header("Content-type: image/png");

I also did try this line though

    $decoded_base_64 = base64_decode(base64_encode($base_64));

Can anyone please help me?

xdazz
  • 158,678
  • 38
  • 247
  • 274
rafi
  • 1,493
  • 3
  • 31
  • 43
  • Possible Duplicate: http://stackoverflow.com/questions/8252925/how-to-save-a-base64-decoded-image-in-the-filesystem-using-php – Dan Barzilay May 19 '13 at 12:52
  • This line $decoded_base_64 = base64_decode(base64_encode($base_64)); no make sense – Sam May 19 '13 at 12:54
  • If you `cat` an image does it return base64 or an error or anything? – Jordan Doyle May 19 '13 at 12:54
  • @JordanDoyle yes it does – rafi May 19 '13 at 12:57
  • @rafi_ccj what does it return? EDIT: lets rewind a little bit, what does `var_dump($this->input->post('base_64'));` return? Pastebin it if it's too big. – Jordan Doyle May 19 '13 at 13:00
  • @JordanDoyle - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABdQAAASACAYAAAD22c+oAAAgAElEQVR4nOzd+3PW9Z338eyMs60HIJDrmCtXIFG27iy17Qr2BtxtRa0VMAwGMEQQEA................. http://pastebin.com/G7qA7nAQ – rafi May 19 '13 at 13:12
  • @rafi_ccj that's not a raw image file. Do you need it to be a raw image file? If not you can echo it in the `src` attribute of an `img` tag. - this is your image, right? http://i.imgur.com/fHFHYxl.png – Jordan Doyle May 19 '13 at 13:14
  • @JordanDoyle i am decoding it into base64 ... shouldn't that work? – rafi May 19 '13 at 13:18
  • Answered your question – Jordan Doyle May 19 '13 at 13:22

1 Answers1

1

Here's your answer:

<?php
    $base64 = $this->input->post('base_64');
    $base64 = str_replace('data:image/png;base64,', '', $base64);
    file_put_contents("directory/toSaveImage/{$id}.png", base64_decode($base64));

You weren't removing data:image/png;base64,

Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38