I've create a table where I've saved images through "BLOB". I need to show those images along with other items. But I don't know how to show those images together in the same page.
Here's my php code that displays other things in form of a table. Similarily, I wanted to display images accordingly. Any help?
<?php
$display_query = mysql_query("SELECT * FROM eportal");
echo "<table id='pageTable'><thead><tr><th>Item code</th><th>Description</th><th>Cost</th></tr></thead>";
echo "<tbody>";
while($row = mysql_fetch_array($display_query)){
print "<tr><td>".$row['itemid']."</td><td>".$row['description']."</td><td>";
print "₹".$row['cost']."</td></tr>";
}
echo "</tbody>";
echo "</table>";
mysql_close($connection);
?>
Saving images to the DB is not a good idea but if You think You need to it this way, then You can retrieve the data from DB table, encode it to base64 (http://php.net/base64_encode) and then in HTML print it in this way:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Using PHP You would write:
echo '<img src="data:'.$image_mime_type.';base64,'.base64_encode($image_data_from_db).'" alt="My image alt" />';
As other people mentioned, storing the images in the database is usually a bad idea.
Images are not transmitted in the same HTTP response with another page data.
To show images from the database, you would need to implement a script which, given the item id, would read the field and send the image's binary data; and provide the path to the script in your form's <img src="">:
while($row = mysql_fetch_array($display_query)){
print "<tr><td>".$row['itemid']."</td><td>".$row['description']."</td><td>";
print "₹".$row['cost']."</td><td>";
print "<img src=\"image.php?id=".$row['id']."\"></td></tr>";
}
image.php is another script which outputs the value of image_blob given the eportal.id. You would also need to provide correct size and mime type in the headers.
You better just store the images in a file (accessible by the web server) and store the path fo the file in the database.
Read the Blob data and write it into the file with header type image.. and try to print it, It should display the image file.
And yes saving image or any file in DB is really a bad habit as you are increasing DB size and it slowdown the performance also.. I suggest you to just try to convert you Blob into Image but don't apply in your work. Just save the image at desired location and keep its location path into DB to fetch and save next time.
The debate of storing blobs versus storing a path to the image file on disk has been debated over and over again. Microsoft provides a research paper comparing the pros and cons of each here. With that said, to display a blob as an image you need to make a call to a separate page and output header information that tells the browser what type of image is stored.
For example:
connectToDatabase();
$sql = "SELECT image_blob FROM eportal;";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: image/jpeg");
echo $row['image_blob'];
$db->close();
In case you still want to save your images in database, you will need second script which will get those images from database and pass them to browser with correct headers.
header("Content-type: image/jpeg");
#
# Replace this with database read:
# readfile('myimage.jpg');
Also, you will need to store what kind of image u use. There will be different header for JPEG, GIF or PNG file.
Related
PHP:
<?php
require "conn.php";
$cid = "6";// $_POST["cid"];
$mysql_qry = "select image2 from cities where ID = '$cid'";
$result = mysqli_query($conn,$mysql_qry);
$row = mysqli_fetch_array($result);
header('Content-Type: image/png');
echo base64_decode($row["image2"]);
$conn->close();
?>
and this is the result
How to solve that? my photo is almost black!
As i can see you are collecting image source from the database table. You must check that weather your entire image source is saved properly after encoding it. So check the database Column Data Type in which you have stored it i doubt that its not saving the full image source hence further you are not able to get the full image.
Advice : Most probably Best Practice is that you should convert it to image and save it on disk and just save the IMAGE SOURCE PATH on your Database Table Column. And then fetch it to display when required.
Otherwise Your DB will exausted and will start taking time in retrieving the records. Also problem will start in DB Backup and migrations.
If you dont want to follow the advise then change your column type to Either Blob depending on your image size.
So i think this question has been addressed before but none of the answers seem to help me.
I have uploaded a .jpeg file to my database by extracting the content from the file and uploaded that to a BLOB field in my database. When it comes to retrieving the data I search the database using an id set by the query string ?id=146 (I've inserted a value that relates to a specific entry in my database just to check the functionality). When I then echo the image['image'] the binary data displays fine (well the browser renders the data how it interprets it) so its finding the entry I want, and it displays the data fine. When I add header("Content-type: image/jpeg"); and reload the page the browser tells me the image is missing. ![screen shot of missing image display][1]
The entire functionality will work as i will reference the php file in the src of an tag on the page I want the image to display. But I can't even get the image to load onto the php page when I type in its URL(inc the correct query string).
Here is a my code for the php page to find the image:
$id = intval(addslashes($_REQUEST['id']));
header("Content-type: image/jpeg");
$result = $dbh->prepare("SELECT * FROM `cefk_profile` WHERE `id`=$id");
$result->execute();
$image = $result->fetch(PDO::FETCH_ASSOC);
echo $image['img'];
And here is a shot of the page that will display the picture:
echo '<img src="php/get_img.php?id=146">';
I am trying to display an image from a MySQL database on a webpage using PHP. I am aware that this is not the most efficient method, but still I would like to see how it is done....
To insert the image into the database I am using this code:
//Get File
File file = new File("C:\\Users\\blah\\blah\\blah\\WebcamImage\\" + name);
FileInputStream fileStream = new FileInputStream(file);
//Prepared Statement
pStmt = connection.prepareStatement("INSERT INTO table (webcamPic1) values (?)");
pStmt.setBinaryStream(1, fileStream, (int) file.length());
pStmt.executeUpdate();
To display the image on the website, I currently have this PHP code:
$result = mysqli_query($con,"SELECT * FROM table");
header('Content-Type: image/jpeg;');
echo "<table border='1' title='WEBCAM'>
<caption>WEBCAM</caption>
<tr>
<th>WEBCAM 1</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['webcamPic1'] .
"</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
On the webpage the file is displayed as a mess of symbols, like this:
ÿØÿàJFIFÿÛC $.' ",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀz£!ÿÄÿÄC!1AQa"q2‘¡±Á#Bá3RÑðbrñ$4CSc¢s’“ÂÒÿÄÿÄ(!1AQa"2q‘¡ðBÿÚ?ûö„ã=–Ù0Xa˜#•7BÀÙ”BTà÷#DÂ.€Å¬´
7……Óc¨L1„¡£ì·2€Ä#?tû7A‘öTl¢ƒÂeEUn#BØ#r°#Â%TCŠ(€±#,±##„” RBÔB‘Â
}’¢µ!•HHá›'±'')DÝ”%#Í7 Ì((hTm¥)U æð¦[쨑6HE¾Pl%sA"æ[ÔûJ¨‹©OHh°7s
Iáp€Ñ¨":µþ¦³Ó÷5¨Ò¼Ñ©ÿí÷]'âäŸöG'àèVqw«ý&Çì¹êøY&'¡Y²ñ¹Wg)±Âï
‡·òYCÿ_¥4÷NÜ.m˜,ƒ„¨g²3öEdÃBžrº¿^·º á•Flˆ!5Õ„NxZ0ˆP…¯>ꨢ
¡Aº£eFYD-!E•)‚ÓÙ›!•Xª2^Pct§•B‘ tŽmÐ) e¨$B‹ÇQ¥•V¹Af:EøU”£
Kð®¡OµÒk 8)œ•r›lØýղТêRˆçÔm¡HÔp0,¹qàé[¢h~³kêäRË)vîîë·ãžØåßD«YpÕ«+ÑÆ9×
gƒž0ºü;\ÚÕ›Pá$C“Ð÷Sòðùqþ‰ÇŸÇ“Ó>Âg=Ö^z>UëL”Àñu0ÇdgªŠåü‘Y8„%0##dÃ(0ˆˆ¼
+| ל¦‚xEY„£÷TˆƒÙÁ[¿T-•” ìUYˆ?+ <#‰ESŽot‹€è(*Â4 E•jRBƒÂ ¸YEÌIÌ ¨°((×BèkïÑA#dvYX€”‰TIÀ©Pm·”ûP
Obviously I am doing something very wrong. What is the correct way to display the true image?
Thank you.
You are mixing two different contents in single HTTP response - it does not work that way and you cannot send HTML and images combined as HTTP does not support multiplexing (SPDY does for example). So this is wrong in the way you do it as browser does NOT expect this and is unable to separate one from the other considering all data it receives in this response as HTML document, hence garbage you seeing as it expects text and handles it all as such. To do this right way, you should have separate PHP script that will return image content, but the request for it should come from browser. So you should just return URL to your image script in SRC for image:
<img src="image.php">
and output image from image.php if so.
Also your code current code makes no sense from other reason too:
header('Content-Type: image/jpeg;');
echo "<table border='1' title='WEBCAM'>
since HTML is NOT image/jpeg type.
PS: storing images in database is considered very bad idea. Store images on disk and keep references to it in your db records only.
There is way to this try something like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
data uri notation should do the job.
last part of the uri i base64 encoded image.
So You just should get Your image data from database encode it with base64_encode and then return it to the browser
For more details check this:
http://en.wikipedia.org/wiki/Data_URI_scheme
I stored it images in the database using an BLOB field (I'm using SQLite). Now I want to recover this image to a HTML page and show the images there.
I can retrieve the binary data from the image from the database, but what I can do to transform this data in an image and show in the page? Currently I want to show the images inside a field in a table.
You could abuse the data: protocol, but trust me, you don't want that if you can avoid it. Normally, you create a separate php-script that serves images, so in script 1:
<img src="/myimagescript.php?id=1234">
In myimagescript.php:
//get the data from the database somehow (mysql query et al.)
//let's assuma the data is in $data
header('Content-Type: image/jpeg');//alter for png/gif/etc.
echo $data;
#uscere90 is right, but an example might help (example of a PNG image):
<?php
header("Content-type: image/png");
echo $image_data;
?>
Typically this is done by creating a wrapper script or function that retrieves the BLOB and delivers it with the appropriate content headers to be used as an <img src=''>
Doing it this way also gives you the benefit of being able to deliver or not deliver the image based on other authentication factors determined by your PHP. If, for example, a user doesn't have permission to see an image, you can instead show some default or blocking image in its place.
// File getimg.php
// Retrieve the image blob specified by $_GET['imgid'] from the database
// Assuming your blob is now in the variable $image...
header("Content-type: image/jpeg");
// Just echo out the image data
echo $image;
exit();
Now in your html:
<img src='getimg.php?imgid=12345' alt='this is your img from the database' />
You can create a simple image.php page that queries your database, then prints out a content-type relevant to the image and vomits the binary data to screen. So, in your table, you'd have <img src=image.php?id=something />, and then you'd use that id in your image.php page to do your database lookup, retrieve the binary data, and print it to screen after printing the content-type header.
image.php:
<?php
header('Content-type: image/jpeg');
//DO SQL NINJA STUFF HERE
echo mysql_result($result,0,"file_content");
?>
There are two options I would say:
You create a script that returns the image data. The <img src="-field then calls that script.
You offer the data of the images directly via a data url.
Both have it's pros and cons. For the first solution you must create a new script for the images. The second method will bloat your page if the images are large.
As there are examples for the image script method already, here is some code fragment for data URIs:
<?php
function data_uri($content, $mime)
{
$base64 = base64_encode($content);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
<img src="<?php echo data_uri($content,'image/png'); ?>" />
You need to set the mime-type according to your image, image/png for PNG images, image/jpeg for JPG files etc., see here for a list.
I'm trying to display multiple images using PHP and MySql database, even if using the while loop I don't get all of the images, I only get one, I mean the first one in the table. What's the problem ?
I'm using a table ID_IMAGE (int, pk, auto increment) and myImage (blob)
$query = mysql_query("SELECT myImage FROM image");
while($data=mysql_fetch_array($query)) {
header('Content-type: image/jpg');
echo $data['myImage'];
}
A possible way to solve this problem is to have a separate script to dynamically output the contents of the image eg. :
image.php
header('Content-type: image/jpg');
// DataBase query and processing here...
echo $data['myImage'];
and call it whenever you need to show images stored in your DB eg. inside your loop:
echo '<img src="image.php?id=' . $data['id'] . '">';
But storing images in the database will take a toll on your server and unless they're really small or you have a good reason to do so, you should only store their physical location on the disk.
You can also use this approach if you wish to hide image location from your users, or control access, but there are better and faster alternatives for that case.
Just to mention the possibility to embed the images directly in html by encoding them, you can use this:
$query = "SELECT myImage FROM image";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="data:image/jpg;base64,' . base64_encode($row['myImage']) . '">';
}
}
Pro:
The browser does not need to load the images over an additional network connection
You can query and display multiple images in one request
Con:
If the image(s) are big and/or there will be many images, the page will be load slow
Encoding an image to base64 will make it about 30% bigger.
For more information about base encode images:
http://davidbcalhoun.com/2011/when-to-base64-encode-images-and-when-not-to/
base64 encoded image size