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
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'
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With