Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in Writing to Image file from PHP

I am attempting to write to an image file from a blob.

 if($_POST['logoFilename'] != 'undefined'){
  $logoFile = fopen($_POST['logoFilename'], 'w') or die ("Cannot create ".$_POST['logoFilename']);

  fwrite($logoFile, $_POST['logoImage']);

  fclose($logoFile);
}

In the previous code snippet, $_POST['logoImage'] is a BLOB. The file is correctly written to the root directory, however the file cannot be opened. In ubuntu 11.04 I receive the following error:

Error interpreting JPEG image file (Not a JPEG file: starts with 0x64 0x61).

The BLOB does correctly display if I create an img and set its src=blob

Included below is the first snippet of the BLOB:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAgGBgcGBQgHBwcJCQ
like image 326
GAgnew Avatar asked Dec 28 '22 17:12

GAgnew


1 Answers

Your "Blob" is really a Data URI:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

Since you only want the decoded data part, you have to do

file_put_contents(
    'image.jpg',
    base64_decode( 
        str_replace('data:image/jpeg;base64,', '', $blob)
    )
);

But since PHP natively supports data:// streams, you can also do (thanks @NikiC)

file_put_contents('image.jpg', file_get_contents($blob));

If the above doesnt work, you can try with GDlib:

imagejpg(
    imagecreatefromstring(
        base64_decode( 
            str_replace('data:image/jpeg;base64,', '', $blob)
        )
    ), 
    'image.jpg'
);
like image 113
Gordon Avatar answered Jan 10 '23 16:01

Gordon