How to display an image stored in the mysql BLOB field in a php page?

Asked

Viewed 8,239 times

3

I have an image saved in my mysql blob encoded in base 64. However, I cannot display the image in a simple php page. In reality what I want is for the user to click on a product category, be returned a search performed in php that returns the field values and also the images of each product. Follow my php code that is returning a broken image on my page and not the image that is stored in my database. Please, I’d like to find out where the bug is in my code.

    <?php

        require "conexao.php";

                    $sql = "SELECT * FROM produtos WHERE idProduto = 17;";

                    $result = mysqli_query($conexao, $sql) or die(mysql_error());  
                    $row = mysqli_fetch_array($result);

                    echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['imagemProduto1'] ) . '" />';

        mysqli_close($conexao);
    ?>

1 answer

4

I found the bug. didn’t need to decode back. The image is already coming ready to be displayed.

This way, the line that was like this:

 echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['imagemProduto1'] ) . '" />';

gets like this:

 echo '<img src="data:image/jpeg;base64,' . $row['imagemProduto1'] . '" />';

Solved!

  • 2

    I have the impression that you "solved" the wrong side. The ideal would be to fix the DB to store without Base64. In fact, in your case, Base64 is bad for everything. You’re just spending band for nothing. It would be wiser to have a separate PHP serving the original image straight from DB, no conversion.

  • It’s just that I’m working on a cross-platform project and my partner who’s doing it on the other side needs the data to be stored this way.

  • This doesn’t seem to make much sense to me: "it needs the data to be stored in this way", even because Base64 is not a storage format, but I understand that the project is yours, and you have the freedom to do as you wish. Just commented to not fail to alert to the problem of architecture, and for eventually other readers have the opportunity to read the counterpoint.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.