Image from mysql database doesn't display in browser
I'm trying to display an image that is stored in a MySql Database.
I have the following table
CREATE TABLE `Pictures` (
`Id` varchar(36) character set utf8 NOT NULL,
`Name` varchar(100) character set utf8 NOT NULL,
`Type` varchar(25) c开发者_运维知识库haracter set utf8 NOT NULL,
`Size` varchar(25) character set utf8 NOT NULL,
`Picture` mediumblob NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB;
The php code haves the following structure
Repostory
- Service - - Image.phpRepository
public static function GetPictureById($id)
{
global $db;
$d = $GLOBALS["db"];
$result = $d->prepare("SELECT * FROM Pictures WHERE id = :id");
$result->bindParam(":id", $id, PDO::PARAM_STR, 36);
if($result->execute() !== true)
{
Pre($result->errorInfo());
return;
}
$result->bindColumn("Id", $id);
$result->bindColumn("Type", $type);
$result->bindColumn("Size", $size);
$result->bindColumn("Picture", $picture, PDO::PARAM_LOB);
while($result->fetch(PDO::FETCH_BOUND))
{
$pic = new Picture();
$pic->SetId($id);
$pic->SetType($type);
$pic->SetSize($size);
$pic->SetPicture($picture);
}
return $pic;
}
Service
public static function GetPictureById($id)
{
return PictureRepository::GetPictureById($id);
}
Image.php
error_reporting(E_ALL);
$root = $_SERVER["DOCUMENT_ROOT"]."/new";
include_once($root . "/Config/Config.php");
$picture = PictureRepository::GetPictureById($_GET["id"]);
header("Content-type:". $picture->GetType());
echo $picture->GetPicture();
unfortunately IE shows a block with a red cross and Firefox tells the image contain errors
Who sees the solution?
The problem is your use of echo
.
echo
is for printing strings. You need to write binary data to the STDOUT stream.
To do this, you need to use fwrite
.
Something like:
fwrite(STDOUT,$picture->GetPicture());
Download the image (right click/save as) and then load it up in a text editor, see if there's any PHP warnings/errors at the start of the file. You've got E_ALL for error reporting, so a single syntax oddity anywhere in your scripts will spit out a warning and corrupt the data stream.
精彩评论