show image from blob mysql - php

Hi I have a image table in my database. These are stored as blob along with details such as image type & name.
I am having a problem showing the image, all I get is a white box with a red cross in it.
code:
<?php
include '../connection.php';
$ID = $_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$ID'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
header("Content-type: $image_type");
print $image;
exit;
?>
Thanks

Well here is a short answer.
<?php
include '../connection.php';
$id = (int)$_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$id'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
$size = $row['image_size'];
//alternative
/* list($image, $image_type, $size) = array(
$row['image'],
$row['image_type'],
$row['image_size']
);
*/
$ext = explode('/', $image_type);
$name = $id . '.' . $ext[1];
header("Content-type: $image_type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
print $image;
exit;
Check your blobtype to be a least MEDIUMBLOB which is able to store data up to 16M

To debug this, I'd suggest commenting-out the Content-type header line, then hitting the url directly in the browser. This will allow you to see any errors, warnings or notices that PHP might be emitting.

Couple of things to try
maybe something is failing and it is returning an error msg in html instead of the expected image
is the content_type stored correctly in the database or are you just storing the file extension of the image
content-type should look something like this
image/gif
image/jpeg

That looks like it might work, what's going wrong?
Try to specify the fields explicitly:
SELECT image, image_type FROM ...
What happens when you run the query from the database?
Are you loading the image like:
<img src="image.php?id=12">
Or do you load the PHP as its own page?

maybe you could try
$row = mysql_fetch_assoc($result);
instead of
$row = mysql_fetch_array($result);

You said in a comment that the table initially said "[BLOB - 64.0 KiB]" but you then changed it to "MEDIUMBLOB". This will expand the size that you can store, but all of your existing data will still be truncated to 64KiB.
Make sure that the field type you use is large enough to store the data you want to store (16mb in a MEDIUMBLOB or ~4gb in a LONGBLOB I'm pretty sure) and then re-insert all of your data.
Other than the security problems mentioned, I don't see why the code shouldn't work other than the database problem.

Or if you don't want to create a separate php file, you can inline it
<?php
// retrieve blob into $img
?><img src='data:image/png;base64,<?php echo base64_encode( $img );?>' alt='Image <?php echo $id;?>'>

Related

php - Unable to display image

I'm very new to development, and I'm trying to retrieve an image from an SQL server over an odbc connection using the below:
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
header('Content-type: image/jpeg');
echo "<img src=".$image."/>";
}
?>
The issue is that I'm getting an icon showing a broken image.
The query is correct as when I change it to the code below, it returns this string instead of the image:
Q2hyeXNhbnRoZW11bS5qcGc=
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
echo $image;
}
?>
I know the code is not correct and might be vulenrable to SQL injection, however I'd appreciate if you can help me retrieve the image.
Many thanks in advance,
J
If you decode the base64 string you get, then you'll see that the decoded data is Chrysanthemum.jpg. This is just the filename of the image, not the image data.
You need to either store the image in the database (not the filename) or add some code to read the image from the filesystem.
BTW, Content-Type image/jpeg requires that the data is the raw image, but your content (<img src=...> ...</img>) is an HTML fragment.

Retrieve BLOB .bin image to be viewed

I have two files;
image.php
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
//Your code to call database for image id (from _GET['id']), for instance:
$image_id = $_GET['pid'];
$data = mysql_query("Select img where pid = $image_id");
while($data = mysql_fetch_assoc($result)){
$image=$data['img'];
header("content-type: image/png");
echo $image;
}
?>
and ay.html to view the image;
<img src="image.php?pid=IMAGE_ID" />
After many examples I tried, and every thread on this site and elsewhere, I'm still getting this error;
The image"http....../image.php?pid=IMAGE_ID" cannot be displayed because it contains errors.
Any help would be appreciated.
By the way the MySql variable is a LONGBLOB called img
I wonder why there isn't a simple IMG type for MySQL variable!
You should post how you stored the image to see exactly what it's wrong with your code but as the error says the image has some kind of error hence it was not stored correctly to database.
Generally the steps to go from an image to binary data and reverse are as below:
Image to binary conversion:
<? php
$image_data=file_get_contents('test.jpg');
$encoded_image=base64_encode($image_data);
echo $encoded_image;
?>
Binary to image conversion:
<?php
$image_data = file_get_contents('test.jpg');
$encoded_image = base64_encode($image_data);
$decoded_image = base64_decode($encoded_image);
echo $decoded_image;
?>
What you're missing altogether is the base_64 encode to prevent symbols from being incorrectly ttransformed.
/In your html page.../
/* */

The image cannot be displayed because it contains errors, displayes text when I remove the following line "header('Content-type: ' ...."

as I was trying to load an image from the database on my dev environment, wasn't able to load the image instead giving back error saying "Image cannot be displayed because it contains errors."
<?php
require_once 'app_config.php'; //app config file
require_once 'database_connection.php'; //database connection
try{
//Get the image id.
if(!isset($_REQUEST['image_id'])){
handle_error("No image to load was specified.");
}
$image_id = $_REQUEST['image_id'];
//Build the SELECT statement
$select_query = sprintf("SELECT * FROM images WHERE image_id = %d", $image_id);
//Run the query
$result = mysql_query($select_query);
//Get the result and handle errors from getting no result
if(mysql_num_rows($result) == 0){
handle_error("We couldn't find the requested image.", "No image found with and ID of " . $image_id . ".");
}
$image = mysql_fetch_array($result);
//Tell the browser what's coming with headers
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);
echo $image['image_data'];
}catch(Exception $exc){
handle_error("Something went wrong loading your image.",
"Error loading image: " . $exc->getMessage());
}
?>
How are you encoding your image data when you store it? I'd recommend you try to base64_decode() it, as that's a common way image data is transmitted/stored.
echo base64_decode($image['image_data']);
exit;
$sql = mysql_query("SELECT * FROM images WHERE image_id = %d", $image_id");
header("Content-Type: image/jpeg");
$row = mysql_fetch_row($sql);
$im=imagecreatefromstring($row[$i]);
imagejpeg($im).'<br>';
echo("<img src=\"$im.$name\" width=\"200\" height=\"150\" />");
this might work..
I've seen this error on perfectly legitimate images when the image uses a CMYK colorspace - which many/most browsers do not support. Try loading the original image directly in the browser (without the PHP/DB process) and see if it throws the same error. If it does you should convert the image to RGB using an image editor (or imagemagick if you want to do it server-side).
This is also a known issue with certain FF extensions, namely Skype. Try disabling extensions or another browser to see if this issue affects you.

weird characters instead of an image when dispalying from mySQL

I'm trying to display a blob image from mySQL, and I'm getting weird characters instead.
To insert data I use:
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Insert data into mysql
$sql="INSERT INTO $tbl_name( image )VALUES('$data')";
$result=mysql_query($sql);
}
To display:
$tbl_name="table"; // Table name
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
if (!$result) {
echo "There is nothing";
}
while($rows= mysql_fetch_assoc($result)){
//header('Content-type: image/jpg');
echo $rows['image'];
?>
How can I fix that?
Thank you in advance.
First, it's best practice to not store images in your database. Store them in a folder instead.
Second, you are seeing the raw data of the image in ASCII.
To answer your question if you must store images in a database, make a new php file.
header('content-type: image/png'); // Use a variable for the image type
// Code here to select a single image from the database.
// Echo the database value.
Call the picture with
<img src="link_to_php_file.php" alt="" />
You need to send an image header, like:
header("Content-Type: image/png"); // or image/jpeg or image/gif
Keep in mind that you can only show one image per time and nothing else.
If you want to show multiple images on a webpage you will need to simply link to them:
<img src="getimage.php?id=1234" />
<img src="getimage.php?id=1235" />
<img src="getimage.php?id=1236" />
Where getimage.php contains the code that will send the Content-Type header and fetch the data BLOB from MySQL.

Oracle Blob as img src in PHP page

I have a site that currently uses images on a file server. The images appear on a page where the user can drag and drop each as is needed. This is done with jQuery and the images are enclosed in a list. Each image is pretty standard:
<img src='//network_path/image.png' height='80px'>
Now however I need to reference images stored as a BLOB in an Oracle database (no choice on this, so not a merit discussion). I have no problem retrieving the BLOB and displaying on it's own using:
$sql = "SELECT image FROM images WHERE image_id = 123";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
But I need to [efficiently] get that image as the src attribute of the img tag. I tried imagecreatefromstring() but that just returns the image in the browser, ignoring the other html. I looked at data uri, but the IE8 size limit rules that out.
So now I am kind of stuck. My searches keep coming up with using a src attribute that loads another page that contains the image. But I need the image itself to actually show on the page. (Note: I say image, meaning at least one image but as many as eight on a page).
Any help would be greatly appreciated.
Well, you can do a few things. You can either make a page that will render the image
<img src="image.php?id=123" />
That image.php page would have this:
$sql = "SELECT image FROM images WHERE image_id = " . (int) $_GET['id'];
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
if (!$row) {
header('Status: 404 Not Found');
} else {
$img = $row['IMAGE']->load();
header("Content-type: image/jpeg");
print $img;
}
Or, you could base64 encode it into the src (note, not all browsers handle this well):
<img src="data:image/jpeg;base64,<?php echo base64_encode($img); ?>" />
But I need to [efficiently] get that image as the src attribute of the img tag
As Byron already says, the accepted and right way is to output the blob in an independent image resource, and to embed that using an img tag. It's the only good way. You can use data: URIs but they
fatten your HTML code
don't work in IE < 8 and are limited to 32 KB in IE 8,
expand the data volume by 33%, and
take away the brower's possibility to cache the image resource.
Almost never a good option.
The normal way to do this is with a <img src=/path/to/script?id=32> field. It will show up on the page not as a link. What is the problem with this? Do you want to embed the image data into HTML?
To make it more efficient, you can implement some type of caching ie, write the image data to a file and do a header(location...) if you find it instead of querying the db again. Also the browser caching headers should be set so the browser doesn't download the image if it has it cached locally.
You may try this :
$img = $row['IMAGE']->load();
print('<img src="data:image/png;base64,'.base64_encode($img).'" />');
<?php
if(isset($_POST['']))//get the id
$roll_no=$_POST[''];
$conn = oci_connect("", "", "");//DB connection
$query = 'SELECT image FROM TABLE where id=:id';
$stmt = oci_parse ($conn, $query);
oci_bind_by_name($stmt, ':id', $id);
oci_execute($stmt);
$arr = oci_fetch_array($stmt, OCI_ASSOC);
$result = $arr['image']->load();
header("Content-type: image/JPEG");
echo $result;
oci_close($conn);
?>

Categories