I am trying to convert an image stored in a MySQL Database to a real image.
I am able to download the image, decode it and transfer it to a folder. However, when I try to open the image I get the following message:
The file could not be opened.
It may be damaged or use a file format that Preview doesn’t recognise.
I followed the tutorial: base64.guru/developers/php/examples/decode-image
This is the shorten image code downloaded from database:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz
ODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj [...] mrvQEGtri5gD2AEvEfhbUD//2Q==
The first thing I did was remove the first bit of code and then ran bas64_decode. Thereafter i moved the file:
// removed first bit of code.
$img = substr($imageCode, 27);
// base 64 decode the image
$image = base64_decode($img);
// got directory to store image
$file = public_path('app/public/images') . uniqid() . '.jpg';
// move the file to the stored location
file_put_contents($file, $image);
I was expecting to see a full image. I can see the file in the specified location but I cannot open it.