Displaying an image in php using mysql - php

I'm trying to display an image along with other information from the database.
PHP
<?php
mysql_connect("localhost","111","222") or die("Could not connect to localhost");
mysql_select_db("movies") or die( "Could not connect to database");
$result = mysql_query("SELECT * FROM allmovies");
if ($result == false ) die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<img src=' . $row['image'] . '>";
?>
Like:
Title: Blah
Price: Blah
Image: <img src=rarara">
All from MySQL in one page?

Don't store image data in a database, they are generally not suited to this and incurs extra overhead on your MySQL connections returning the data. You should be storing the path to the image file, and serving that.
If you insist on doing it you you should only be returning one image at a time with the proper header based on the image type using something like the following:
$imagedata = data_from_mysql();
header('Content-Length: ' . sizeof($imagedata) );
header('Content-Type: image/png');
echo $imagedata;
exit;
If you really want to make your page source bloated, slow, unmanageable, and nigh-uncacheable:
while( $imagedata = data_from_mysql() ) {
echo "<img src='data:image/png;base64," . base64_encode($imagedata) . "'>";
}
I cannot stress enough how these are terrible ideas that you should not use, but if you cannot listen to reason you can at least do bad things the right way.

You could use imagecreatefromstring()
$im = imagecreatefromstring($row['image']);
if ($im !== false) {
ob_start();
imagejpeg($im);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' . base64_encode($data) . '" />';
}
Just my opinion, but it might be slightly more sane to save the images to the file server and then store a reference to the path instead of the whole image as a blob?

Related

php - cannot load image from database

I'm trying to design a page in php which shows images from database. or I would say only the location of images are in database.
But, when it shows up the images.. But it does print the image path.. That means it is getting the image path without any issue.
Here's my code:
<?php
$con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
mysqli_connect_error();
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
//$srcc = "C:\wamp\www\foodies\images";
//$quality=100;
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
echo "<img src='".$row['img']."' width=200 height=200/>";
?>
I don't think you understand what's going on with the <img> tag. The src attribute needs to be a URL that tells your Web browser how to access the image, not a local file path. (URLs can be made for accessing local files, but that doesn't seem to be what you're doing, and that won't help you make Web-ready software anyway.)
The best way to display images from database is to save the image path in database tables then use Data URLS Schemes.
Try this instead:
<?php $con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
echo "<img src="data:image/jpeg;base64,<?php echo base64_encode( $img); ?>" width=200 height=200/>";
?>
The $img is the image file name, without the extension. Let's say you have saved your image in a folder "image" and the image file extension is jpeg.
I hope this is helpful.
while($row = mysql_fetch_array($result)) {
if($row['file_location']=="")
{
//your code
}
else
{
?>
VIEW IMAGE
<?php
}
}
Sorry for late reply to this. This was resolved. The issue was that I was giving location starting from root drive and not from root of web folder where the images were actually stored.
Ex: Website and images were located in C:\WAMP\my_site\images\
Instead of giving location from website root folder "\my_site\images\" I was giving it from C:\WAMP.......
Minor mistake though! ;)
Thank you everyone!

Displaying a Base64 images from a database via PHP

I have this database that contains images as strings. Those strings look something like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...
I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:
<?php
$host = "smth";
$user = "smth";
$pass = "smth";
$db_name = "smth";
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
$dbh->exec("SET NAMES utf8");
$q = $dbh->prepare("select content from img where id = :id");
$q->execute(array(':id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_BOTH);
header("Content-type: image/jpeg");
echo $row['content'];
?>
The data is being fetched correctly but the image is not displayed.
I need to be able to use this link like this <img src="mysite.com?id=21" /> and I do NOT want this solution: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABA..." />
Thanks!
The solution to your problem is here:
How to decode a base64 string (gif) into image in PHP / HTML
Quoting that source but modifying:
In the case you strip out the first case and choose to decode the string, you should add this before echoing the decoded image data:
header("Content-type: image/gif");
$data = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo base64_decode($data);
In the second case, use this instead:
echo '<img src="data:image/gif;base64,' . $data . '" />';
The second case is bad because the browser does not perform caching if the same image is shown on multiple pages.
Use this:
$code_base64 = $row['content'];
$code_base64 = str_replace('data:image/jpeg;base64,','',$code_base64);
$code_binary = base64_decode($code_base64);
$image= imagecreatefromstring($code_binary);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
try this
//your image data
$logodata = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo '<img src="data:image/gif;base64,' . $logodata . '" />';
Try this:
echo '<img src="data:image/png;base64,' . $base64encodedString . '" />
/**
* #param $base64_image_content
* #param $path
* #return bool|string
*/
function base64_image_content($base64_image_content,$path){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = $path."/".date('Ymd',time())."/";
$basePutUrl = C('UPLOAD_IMG_BASE64_URL').$new_file;
if(!file_exists($basePutUrl)){
//Check if there is a folder, if not, create it and grant the highest authority.
mkdir($basePutUrl, 0700);
}
$ping_url = genRandomString(8).time().".{$type}";
$ftp_image_upload_url = $new_file.$ping_url;
$local_file_url = $basePutUrl.$ping_url;
if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
ftp_upload(C('REMOTE_ROOT').$ftp_image_upload_url,$local_file_url);
return $ftp_image_upload_url;
}else{
return false;
}
}else{
return false;
}
}
If you are dealing with data stored in a PostgreSQL database bytea field you will receive a stream when fetching the PDO. To process the data any further first transform the stream to usual data like this: $stream = $row['content']; rewind($stream); $data=stream_get_contents($stream);

store image into mysql DB with php and display

Having big time problems in displaying an image out of my mysql database
I'm storing it in a longblob type
when the image is displayed i get a broken image icon
here is code for storing image
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
//temporary file name
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$imageType = $_FILES['image']['type'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
VALUES
('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";
//For debugging purposes
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Your Image has been Added";
}
}
then printing the image
if(isset($_POST['usersImage'])){
//code to show images
$user = $_POST['usersImage'];
$sql = "SELECT * FROM `photos` WHERE userName = '$user'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
switch ($row['photoType']) {
case 'image/jpeg':
echo "<tr>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";
echo "</tr>";
//echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
//echo '<p id="caption">'.$row['caption'].' </p>';
break;
}
}
}
as you can see my latest attempt was to use base64 encoding to print out the image
my previous try was the commented out code
When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.
<?php
$photo_bin = //binary data from query here;
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $photo_bin;
Quick example^ of a php script that can be requested by the browser from an img tag.
Validation is important. You are opening yourself up to so many security issues.
Never use $_POST / $_GET inside a sql statement. Escape them, better yet, use PDO statements. Validate that the image is actually an image, at this point, you could be entering any type of file into your table.
As you're finding, it's also far more difficult to store images in a database than on the filesystem. Usually, there are far more arguments to store the image on the filesystem than inside a table.
Having a quick look down your insertion code, I'm not quite sure why you're adding slashes to the binary data. remove the call to addslahes, and try that.

How can i display image from database?

Image can't display from database in php and it's fire such error.
When I execute this code such error is occure The image cannot be display beacuse it's contain error. Image is store in mysql database and field type is BLOB. IT didn't find any solution to avoid this error.
<?php
require_once('database/db.class.php');
$objDatabase=new db_class();
$objDatabase->connect();
$sql="SELECT id,firstname,lastname,sex,email,userimage,ext,city,state,username FROM t_users WHERE username='".$_SESSION['username']."'";
$totalRow=$objDatabase->select($sql);
if($row=$objDatabase->get_row($totalRow, 'MYSQL_BOTH'))
{
$userArray=array('id'=>$row['id'],'firstname'=>$row['firstname'],'lastname'=>$row['lastname'],'sex'=>$row['sex'],'email'=>$row['email'],'userimage'=>$row['userimage'],'ext'=>$row['ext'],'city'=>$row['city'],'state'=>$row['state'],'username'=>$row['username']);
}
?>
<table cellspacing="10px" width="100%">
<tr>
<td width="23%" style="vertical-align:top">
<?php
header("Content-type: image/{$userArray['ext']}");
header("Content-Length: " . strlen($userArray['userimage']));
echo $userArray['userimage'];
?>
</td>
</tr>
</table>
Upload Image Code
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
$img = file_get_contents($_FILES['photo']['tmp_name']);
$img = mysql_real_escape_string($img);
// Preparing data to be used in MySQL query
$data=array('firstname'=>$_REQUEST['firstname'],'lastname'=>$_REQUEST['lastname'],'sex'=>$_REQUEST['gender'],'email'=>$_REQUEST['email'],'userimage'=>$img,'ext'=>$ext,'city'=>$_REQUEST['city'],'state'=>$_REQUEST['state'],'zipcode'=>$_REQUEST['zipcode'],'username'=>$_REQUEST['usernameText'],'password'=>$_REQUEST['passwordText']);
$result=$objDatabase->insert_array('t_users',$data);
<input name="photo" type="file" id="photo">
edit - I forgot to include: base64 files will be considerably larger than BLOB.
Try saving it as base64 instead of BLOB.
Here is a function I found on http://www.php.net/manual/en/function.base64-encode.php
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
When you retrieve the image from the database, it will be as a base64 string, you can put the string directly into the src="" attribute in your HTML (no need to decode). Browsers can parse base64 and display an image.
Well, this isn't the way to do it, just store the image as per usual, then store the path in the database.
If you do want to do it this way, you'll need to make a new file, called something like image.php, then put
<?php
require_once('database/db.class.php');
$objDatabase=new db_class();
$objDatabase->connect();
$sql="SELECT id,firstname,lastname,sex,email,userimage,ext,city,state,username FROM t_users WHERE username='".$_SESSION['username']."'";
$totalRow=$objDatabase->select($sql);
if($row=$objDatabase->get_row($totalRow, 'MYSQL_BOTH'))
{
$userArray=array('id'=>$row['id'],'firstname'=>$row['firstname'],'lastname'=>$row['lastname'],'sex'=>$row['sex'],'email'=>$row['email'],'userimage'=>$row['userimage'],'ext'=>$row['ext'],'city'=>$row['city'],'state'=>$row['state'],'username'=>$row['username']);
}
header("Content-type: image/{$userArray['ext']}");
header("Content-Length: " . strlen($userArray['userimage']));
echo $userArray['userimage'];
?>
in to that file.
Then in the table use
<img src='/image.php ?>' alt='' />
But don't, just do it by storing the path in the DB, it's rare that you should be storing binary data in a database that's not the file system, for reasons I won't go into here.

resize and display images from sql in php

I am wanting to alter the following php code so that it resizes and displays images one at a time, with a 'next' and 'previous' button, in order to browse through the photos. I don't want any image gallery or lightbox solutions, rather the photos to just show on the page. I'm new to php so If someone can help out or point me in the right direction all help is appreciated.
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "</p>";
echo "</div>";
source of above code
You can scale them in the browser using width and height attributes (or just one will maintain aspect ratio) however this is bad for many reasons including bandwidth, page performance and image quality.
You can re-size the images using libraries such as GD or Imagick
A quick sample with IMagick:
$hThumb = new Imagick($path_to_file); // Source file
$hThumb->thumbnailImage($x, $y); // You can use 300, 0 to do 300 width and maintain aspect ratio.
$hThumb->stripImage(); // remove meta data
$hThumb->writeImage($path_to_thumb); // write the image to disk
Note
Be sure to have permissions to read/write. You can verify this permissions by using is_readable and is_writable.
Loading
It's recommended to load the images using AJAX which is quite easy if using JQuery or a similar library.
$('#nextBtn').click(function() {
var index = 0; // Store this in your image ID tag perhaps
// e.g. $('#theImage').attr('id').replace('image', '')
// where ID is imageX
$.ajax({
url: 'getImages.php?index=' + index,
type: "GET",
success: function(data) {
var result = $.parseJSON(data);
if (result.success) {
// Set your image src with the new path.
// Use result.image_data.src etc...
}
}
});
});
The PHP would be relatively simple too, a structure similar to this:
<?php
$return = array('success' => false, 'image_data' => array());
if (isset($_GET['index']) && is_numeric($_GET['index')) {
// Fetch your image
$return = array(
'success' => true,
'image_data' => array(
'src' => $src,
'title' => $title,
'index' => $index
)
);
}
echo json_encode($return);
?>
** Another note **
As stated by kgb you should resize these on upload, however, they may not be user submitted so you can also check if the thumbs exist on output and generate any as required. Certainly don't generate them for every view though.
You should resize images on upload, not on output. Store both the original and the resized images, show small images in the list and full size when user wants it...
A sample code from imagecopyresampled() docs:
// Get new dimensions
list($width, $height) = getimagesize($filename);
$widthNew = 320; // You decide
$heightNew = 240; // You decide
// Resample
$imageNew = imagecreatetruecolor($widthNew, $heightNew);
$imageOld = imagecreatefromjpeg($filename);
imagecopyresampled($imageNew, $imageOld, 0, 0, 0, 0, $widthNew, $heightNew, $width, $height);
// Output
imagejpeg($imageNew, $newFilename, 100);
This example expects gd extension to be included with php. Imagick extension mentioned by Martin is more powerful and provides nicer interface, but is rarely included on web hostings.
Also googled this for you: http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html

Categories