skip to Main Content

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.

2

Answers


  1. When you remove the first 27 characters it means you remove all this: data:image/jpeg;base64,/9j/, so you remove not only the Data-URL part, but also the first 4 bytes (/9j/) of the jpeg header. No surprise that the format can’t be recognized anymore.
    You just have to remove everything until and including the ,. Everything after the comma is Base64 encoded jpeg image data.

    You should generally avoid "magic" numbers, like the 27 in substr($imageCode, 27);. Instead find the position using a certain logic. In this case find the position of the , in the string and use the position instead of the fixed number.

    And of course, as @HonkderHase points out in his comment, the Data-URL part contains some valuable information.
    First you can check the the type of the contained data. In your case it’s a JPEG-image (image/jpeg), but it could also be a PNG (image/png) or any other format, not necessarily an image. After the ; you find the encoding, which here is Base64. Data type and encoding should be evaluated in by your code. I recommend following the link above to learn more about the format as this is a bit beyond the scope of this question.

    Login or Signup to reply.
  2. The issue might be caused by one of the following:

    Incomplete or Corrupted Base64 String
    Ensure the Base64 string is complete and correctly formatted. If it starts with a prefix like data:image/jpeg;base64,, you need to remove this before decoding.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search