Jump to content

How To Display An Image From A MySQL Table


JustinK101

Recommended Posts

Hello,

 

I have images stored in a MySQL table as blobs. How in the world can I load the images from MySQL into a web page, using for example <img src> tag.

 

I assume the first thing I need to do is retrieve the image via a MySQL query:

 

$sql = "SELECT myImage FROM images WHERE id = 1";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

//Now what do I with this to display the image?
$row->myImage

 

Thanks.

Link to comment
Share on other sites

 

file image.php

$ID = (int)$_GET['id'];
//add connection string etc
$sql = "SELECT myImage FROM images WHERE id = $ID";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

//for JPEG
header("Content-type: image/jpeg");
imagejpeg($row->myImage)

Thats the whole file! no echoing in there as it will mess it up..

 

in another file use

<img src="/my/php/image.php?ID=12" />

 

as The Little Guy said

 

hope that sums it up

Link to comment
Share on other sites

MadTechie:

 

I am getting the following errors in my image.php file:

 

Warning: Cannot modify header information - headers already sent by (output started at includes/makeImage.php:1) in includes/makeImage.php on line 31

 

Warning: imagejpeg(): supplied argument is not a valid Image resource in includes/makeImage.php on line 32

 

Here is my code:

 

<?php

if(!isset($_GET['id']) || empty($_GET['id']))
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

function mysql_smart_quote($var)
{
   if (get_magic_quotes_gpc()) 
   {
	   $var = stripslashes($var);
   }
   
   if (!is_numeric($var))
   {
	   $var = "'" . mysql_real_escape_string($var) . "'";
   }
   return $var;
}

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = " . mysql_smart_quote($_GET['id']);
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

header("Content-type: image/jpeg");
imagejpeg($row->image_thumb);

?>

Link to comment
Share on other sites

Wrote this script, it handles more than just jpgs

 

view image + its data page

<?php
require_once("functions.php");
    // again we check the $_GET variable
    if(isset($_GET['image_id']) && is_numeric($_GET['image_id'])) {
        $sql = "SELECT ImageType, ImageTitle, ImageCat, Height, Width, ImageName FROM Images WHERE ImageID=".$_GET['image_id'];
	connectSQL();
        $result = mysql_query($sql)  or die("Invalid query: " . mysql_error());
         while($row=mysql_fetch_array($result)) {
            echo "<h3>".$row['ImageTitle']."</h3>";
		echo "<img src=\"image.php?image_id=".$_GET['image_id']."&width=".$_GET['width']."\" alt=\"".$row['ImageName']."\" />";
		echo "<br/>Image Name: ".$row['ImageName'];
		echo "<br/>Category: ".$row['ImageCat'];
		echo "<br/>Image Type: ".$row['ImageType'];
		echo "<br/>Width: ".$row['Width']."px Height: ".$row['Height']."px";
	}
    }
    else {
        echo 'File not selected';
    }
?>

image.php

<?php
require_once("functions.php");
$id = $_GET['image_id'];
if(!empty($_GET['width'])){
$size = $_GET['width'];
}
else{
$size = 500;
}
if($id) {
connectSQL();
    $query = "select Image, ImageType from Images where ImageID = $id";
    $result = mysql_query($query) or die(mysql_error());
    $data = mysql_result($result,0,"Image");
    $type = mysql_result($result,0,"ImageType");
$type = "image/".$type;
    Header("Content-type: ".$type);   
    $src = imagecreatefromstring($data);
    $width = imagesx($src);
    $height = imagesy($src);
    $aspect_ratio = $height/$width;

    $new_w = $size;
    $new_h = abs($new_w * $aspect_ratio);


    $img = imagecreatetruecolor($new_w,$new_h);
    imagecopyresized($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);
     // determine image type and send it to the client   
    if ($type == "image/pjpeg" || $type == "image/jpg" || type == "image/jpeg") {   
      imagejpeg($img);
    } else if ($type == "image/x-png" || $type = "image/png") {
      imagepng($img);
    } else if ($type == "image/gif") {
      imagegif($img);
    }
    imagedestroy($img);
}
?>

 

and the function connectSQL();

<?php
function connectSQL() {
//mysql connect and picks db
if(empty($connected)){
	$link = mysql_connect("", "", "") or die(mysql_error());
	$db = mysql_select_db("") or die(mysql_error());
	$GLOBALS['conncted'] = "yes";
}
}//End of connectSQL
?>

basically use view.php with the number and width and let it go

Link to comment
Share on other sites

cooldude,

 

Yeah I dont get it though, I have the header call as the first thing on the page. How in the world do I do this?

 

<?php header("Content-type: image/jpeg");

if(!isset($_GET['id']) || empty($_GET['id']))
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

function mysql_smart_quote($var)
{
   if (get_magic_quotes_gpc()) 
   {
	   $var = stripslashes($var);
   }
   
   if (!is_numeric($var))
   {
	   $var = "'" . mysql_real_escape_string($var) . "'";
   }
   return $var;
}

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = " . mysql_smart_quote($_GET['id']);
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

imagejpeg($row->image_thumb);

?>

Link to comment
Share on other sites

Ok I think I am getting closer, the problem was that I was calling imagempeg($row->image_thumg); That wont work, so now I have it as:

 

imagejpeg(imagecreatefromstring($row->image_thumb));

 

But now I am getting the following error:

 

[function.imagecreatefromstring]: Data is not in a recognized format in includes/makeImage.php on line 33

Link to comment
Share on other sites

Ok this is getting very annoying. I am still getting cannot modify header information error. The following is my exact code:

 

<?php 
if(!isset($_GET['id']) || empty($_GET['id']))
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

function mysql_smart_quote($var)
{
   if (get_magic_quotes_gpc()) 
   {
	   $var = stripslashes($var);
   }
   
   if (!is_numeric($var))
   {
	   $var = "'" . mysql_real_escape_string($var) . "'";
   }
   return $var;
}

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = " . mysql_smart_quote($_GET['id']);
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

header("Content-type: image/jpeg");
echo $row->image_thumb;
?>

 

I don't understand why I am getting the cannot modify header error. Thanks guys.

Link to comment
Share on other sites

Yes absolutely no white space before the opening or closing php tags, I have triple checked, but it must be because it says the error is on line 1. If I move the opening php tag down a line, the error changes to line 2. SOOOOOO WEIRD.

 

As far as the db_config.php and db_connect.php here they are, and again I checked those files for no whitespaces.

 

This is the most fusterating thing ever. :(

 

db_config.php

<?php $db_loc = "localhost"; $db_user = "connect"; $db_pass = "mypasswordhere"; $db_name = "images"; ?>

 

db_connect.php

<?php $db = mysql_connect($db_loc, $db_user, $db_pass) or die("<p><b><font color=\"red\">Error:</font> " . mysql_error() . "</b></p>"); mysql_select_db($db_name) or die("<p><b><font color=\"red\">Error:</font>Cannnot Select Database '" . $db_name . "'.</b></p>"); ?>

 

Here is the bloody error message:

Warning: Cannot modify header information - headers already sent by (output started at includes/makeImage.php:1) in includes/makeImage.php on line 28

Link to comment
Share on other sites

try this

 

<?php
$ID = (int)$_GET['id'];
if( $ID == 0 )
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = $ID"
$result = mysql_query($sql) or die(mysql_error());
$row = @mysql_fetch_object($result);
$img = $row->image_thumb;
header("Content-type: image/jpeg");
//echo $img;
imagejpeg($img);
exit

Link to comment
Share on other sites

updated (forgot some ;) and too late to edit last post!

<?php
$ID = (int)$_GET['id'];
if( $ID == 0 )
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = $ID";
$result = mysql_query($sql) or die(mysql_error());
$row = @mysql_fetch_object($result);
$img = $row->image_thumb;
header("Content-type: image/jpeg");
//echo $img;
imagejpeg($img);
exit;
?>

Link to comment
Share on other sites

Ok, so I copyied my exact code and pasted it into a brand new text document with wordpad. Then I renamed the document from .txt to .php and uploaded and it worked. It seems Dreamweaver must put a special character in the file, which makes no sense because when I open up the file I created with dreamweaver in wordpad I don't see any special characters. Honestly that is stupid, dreamweaver must be inserting a special character that I cant see even with wordpad.

Link to comment
Share on other sites

you could use ob_start() at the top of the page. then ob_end_flush() after your echo $row->image_thumb.

 

P.S. Have never used output buffering before so don't attack me if I'm wrong, although I'm fairly certain it should work.

 

<?php
ob_start(); 
if(!isset($_GET['id']) || empty($_GET['id']))
{
	return;
}

require_once("db_config.php");
require_once("db_connect.php");

function mysql_smart_quote($var)
{
   if (get_magic_quotes_gpc()) 
   {
	   $var = stripslashes($var);
   }
   
   if (!is_numeric($var))
   {
	   $var = "'" . mysql_real_escape_string($var) . "'";
   }
   return $var;
}

$sql = "SELECT product_images.image_thumb FROM product_images WHERE product_images.id = " . mysql_smart_quote($_GET['id']);
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($result);

header("Content-type: image/jpeg");
echo $row->image_thumb;
             ob_end_flush();
?>

Link to comment
Share on other sites

Ok,

 

I am wondering how is is possible to do what I have done above, i.e.

 

<img src="includes/makeImage.php?id=6">

 

Work with an AJAX call. For example, I only want to query the image out of the DB and display it,  if a user clicks a button or any JS event for that matter. I know how to do the JS code:

 

<input type="button" name="clickMe" value="Click Me" onclick="requestImage(6);" />

 

Also in the header of the page I have:

 

<script type="text/javascript" src="includes/prototype.js"></script>
<script type="text/javascript">
var returnValue;

function requestImage (id) {
     var myUrl = 'includes/makeImage.php';
     var myPars = 'id=' + id;
     var myAjax = new Ajax.Request (myUrl, {method: 'get', parameters: myPars, onLoading: showLoad, onComplete: showResponse});
     return returnValue;
}

function showLoad() {
     //Do nothing for now 
}

function showResponse(originalRequest) {
     returnValue = originalRequest.responseText;
}
</script>

 

So that js code works perfect except the problem now lies with php. What is returned from that AJAX call is just a big messy nasty string filled with the binary data of the image. How do I acutally take that and make an image?

 

Will doing this work?

<img src="javscript: requestImage(6);">

Link to comment
Share on other sites

Can you perhaps give an example using the button and an image.

 

For example:

 

<input type="button" name="clickMe" value="Click Me" onclick="$(myImage).src = requestImage(6);">

<img src="" id="myImage">

 

Would that work? Sorry I dont follow.

Link to comment
Share on other sites

OK, after re-reading a few posts..

 

your using AJAX to pull the image.. first off the ajax call shouldn't pull the image but a html string to display the image,

 

So ignore the last post..

 

but as for

 

<input type="button" name="clickMe" value="Click Me" onclick="requestImage(6);" />

 

what would you expect that to do ?

Request Image(6) to do what ?

 

heres what i think your after!

<script language="javascript">
function showimage(ID)
{
document.getElementById('imgTest').src = "includes/makeImage.php?id="+ID;
}
</script>
<img id="imgTest" src="" />

<input type="button" name="clickMe" value="Click Me" onclick="showimage(6);" />

 

Link to comment
Share on other sites

Would this run the query at runtime, I dont think so right?

 

document.getElementById('imgTest').src = "includes/makeImage.php?id="+ID;

 

My goal is to not run the query, unless an event is triggers, and do all this without page-reloads.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.