PHP show image as BLOB mysqli

2020-04-11 04:03发布

问题:

I read all possible questions on StackOverflow, I asked all people who I know and no one can help me. I have table in database:

CREATE TABLE IF NOT EXISTS `zdjecia` (
`id` int(11) NOT NULL,
  `imie_wlasciciela` varchar(50) NOT NULL,
  `zdjecie` blob NOT NULL,
  `nazwa` varchar(50) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=16

I'm sorry for no English variables, but I want to keep all source without changes. imie_wlasciciela and nazwa aren't important in my problem. So zdjecie is a binary data of image And id is id.

I have a file which should show image.

// single_image.php

<?php

if (isset($_GET['id']))
{
    include('../connect.php'); // connect to database
    $id = $_GET['id'];
    $ret = $conn->query("SELECT * FROM zdjecia WHERE id=$id");
    $row = $ret->fetch_assoc();
    header("Content-type: image/png");
    echo $row['zdjecie'];
    // echo $row['nazwa']; // correct the result.
}
?>

And in my browser URL I paste.../single_image.php?id=8

My problem is a not displaying images, I have in database few images. I can download it by /phpmyadmin in XAMPP and it is correct image, but my page does not displaying it correctly, Every time I see a broken image icon.

File single_image.php is set to no-bomb and Code-Page 1250 (Central European).

When I check the result by $row['nazwa'], and commented header("Content-type...") line it's showing correct varchar(50) from database.

I'm using it like written a few lines above, or in html, <img src="single_image.php?id=8"/>

回答1:

Try below

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

For better maintenance you can add data:image/png;base64 as your header then only echo base64_encode( $row['zdjecie'] ) this will work for single_image.php?id=$id



回答2:

Using phpMyAdmin, I had to change the MIME display type to .jpeg on my MySQL image column = avatar_image. Once I made this simple change, it displays in the browser...i.e. the browser was getting the .jpeg data as a BLOB in raw form and did not know what to do with it...but it was a MySQL configuration = MIME type change on the MySQL column that fixed it.



回答3:

  1. Don't store images in DB, it's performance suicide.
  2. Don't make your code vulnerable to SQLinjection.
  3. If you must store files in db, store content type. Maybe it's not a png? Or maybe you have a warning/notice printed out? It will break your image.