PHP 显示来自 MySQL 的图像 BLOB [英] PHP display image BLOB from MySQL
问题描述
我正在尝试显示存储在数据库中 BLOB 列中的图像;
I'm attempting to display an image stored in the BLOB column in the database;
我使用 SELECT 从数据库中获取数据,不对数据执行任何转换,并使用以下内容显示它(来自其唯一输出如下的脚本):
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;
请注意,chrome 将内容大小显示为图像的正确大小以及正确的 mime 类型 (image/jpeg
).在标题之前没有任何回显,我检查了数据库中的 blob 是否正确.<?php ?>
标签前后也没有尾随空格.
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 显示图像图标,但不显示图像本身.有什么想法吗?
chrome/IE displays an image icon but not the image itself. any ideas?
图像是从数据库中获取的:
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) 给出:
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)
推荐答案
试试这个.
用于插入数据库
$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();
用于从 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']).'"/>';
这篇关于PHP 显示来自 MySQL 的图像 BLOB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!