PHP的图像blob不会显示 [英] php image blob wont show

查看:136
本文介绍了PHP的图像blob不会显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图显示我的mysql数据库中的图像.图像被保存为斑点格式.我制作了单独的php文件来获取图像.然后,从想要显示图像的位置调用该文件,如下所示:

So I am trying to show an image from my mysql database. The image is saved as a blob format. I made seperate php file for fetching the image. I then call this file from where I want to show the image like so:

<img src="image.php?id=3" />

这是获取图像的文件:

<?php
    require 'scripts/connect.php';

    if(isset($_GET['id']))
    {
        $id = mysql_real_escape_string($_GET['id']);
        $q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
        $q->execute();
        $data = $q->fetch();

        header("content-type: image/jpeg");
        echo $data["image"];
    }
?>

但是当我尝试运行此代码时,没有图像显示.相反,我得到了这个令人讨厌的损坏的链接图像:

But when I try and run this code no image shows up. Instead I get this annoying broken link image thing:

http://i.imgur.com/NQOPSAf.png

推荐答案

您的代码没有达到您的期望.

Your code doesn't do what you expect.

尝试更改

$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");

in-如果id字段为数字1;如果不是,请添加单引号-

in - if id field is numeric one; if isn't, add single quote -

$q = $db->prepare("SELECT image FROM products WHERE id = $id");

您的示例在传递给查询$id占位符而不是其值(您未将其串联)时不起作用

Your example didn't work as you were passing to query $id placeholder and not his value (you dind't concatenated it)

当然,使用该方法,您完全不会被 SQL注入保存,因此您应该以这种方式使用pepared语句

Of course with that method you're not save by SQL Injection at all, so you should use pepared statement that way

$q = $db->prepare("SELECT image FROM products WHERE id = :id");
$q->execute(Array(":id" => $id));

编辑

正如OP告诉我的那样,$ data ['image'];是一个比特流,我建议使用类似的东西:

Edit

As OP told me that $data['image']; is a bitstream, I will suggest to use something like:

echo '<img src="data:image/jpg;base64,'. base64_encode($data['image']). '" alt='imagename'>;

或者如果您的回声直接进入src属性:

or if your echo goes directly into src attribute:

echo 'data:image/jpg;base64,'. base64_encode($data['image'])

这篇关于PHP的图像blob不会显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆