Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP display image BLOB from MySQL [duplicate]

Tags:

php

mysql

I'm attempting to display an image stored in the BLOB column in the database;

I fetch the data from the database with a SELECT perform no transformations on the data and display it with the following (from a script whose only output is the following):

header("Content-Type: image/jpeg"); echo $image; 

Please note chrome is displaying the content size as the correct size for the image as well as the correct mime type (image/jpeg). nothing is echoing out before the header and ive checked the blob in the database is correct. There is also no trailing whitespace before or after the <?php ?> tags.

chrome/IE displays an image icon but not the image itself. any ideas?

EDIT: image is got the from the database as such:

$sql = "SELECT * FROM products WHERE id = $id"; $sth = $db->query($sql); $row = $sth->fetch(); $image = $row['image']; 

var_dump($image) gives:

string 'ÿØÿà�JFIF��x�x��ÿá�ZExif��MM�*�����������J��������Q�������Q������tQ������t�����† ��±ÿÛ�C�         ÿÛ�CÿÀ�_"�ÿÄ�����������  ÿÄ�µ���}�!1AQa"q2‘¡#B±ÁRÑð$3br‚  %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³    ´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ��������'... (length=60766) 
like image 304
user2732663 Avatar asked Dec 13 '13 00:12

user2732663


People also ask

How do I view BLOB images?

Using Active Server Pages (ASP), you can view images stored in BLOB (Binary Large Object) fields in your Internet browser.


2 Answers

Try it like this.

For inserting into DB

$db = new mysqli("localhost", "root", "", "DbName"); $image = file_get_contents($_FILES['images']['tmp_name']); $query = "INSERT INTO products (image) VALUES(?)"; $stmt = $db->prepare($query); $stmt->bind_param('s', $image); $stmt->execute(); 

For accessing image from Blob

$db = new mysqli("localhost", "root", "", "DbName"); $sql = "SELECT * FROM products WHERE id = ?"; $stmt = $db->prepare($sql); $stmt->bind_param('s', $id); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_array(); echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'"/>'; 
like image 154
3 revs, 2 users 73% Avatar answered Oct 07 '22 06:10

3 revs, 2 users 73%


This is what I use to display images from blob:

echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />'; 
like image 34
Arian Faurtosh Avatar answered Oct 07 '22 07:10

Arian Faurtosh