Displaying a Base64 images from a database via PHP - 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);

Related

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

PHP QR Code Generator with SQL statement

I would like to use the results of a MYSQL query and generate a batch of QR Codes have the following php script via PhpQrCode. What I need is simply display the list of barcodes generated on HTML page. This is what I wrote so far:
<?php
include "qrlib.php";
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
while ($row = mysql_fetch_array($barcodes))
{
echo "<html>";
echo "<img src=";
QRcode::png ($row['Description']);
echo ">";
}
?>
The query is correct since I tested it out but I only get a blank page with a sort of broken image. Can someone help me as to what I am doing wrong please?
Thanks
SOLVED as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
To render the image in the html page, hold the returned QRcode image in a location and then specify it as a link in src attribute of <img> tag.
If QRcode::png returns the raw image data, use data URIs to display:
$qr_code = base64_encode(QRcode::png ($row['Description']));
$src = 'data: image/png;base64,'.$qr_code;
echo '<img src="', $src, '">';
Solved as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
I have stored the PNGs as files via variable $filename.

Pear Barcode 2 - save to disk

I am generating a gif barcode using Pear Barcode2.
this currently works and I can see the image as gif image file. so the page is not shown in HTML form but as a stand alone image.
my code is:
$small_graph_height = 55;
$small_graph_width = 1.2;
$large_graph_height = 55;
$large_graph_width = 1.14;
$type = "gif";
$code = "code39";
$to_browser = TRUE;
include_once "application/libraries/Image/Barcode2.php";
$ticketno='TDN4993';
$productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
$productserial_type = $code;
$productserial_imgtype = $type;
$productserial_bSendToBrowser = $to_browser;
$productserial_height = $large_graph_height;
$productserial_width = $large_graph_width;
$productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);
ob_start();
imagepng($productserial_img);
$productserial_imgBase64 = base64_encode(ob_get_contents());
ob_end_clean();
imagedestroy($productserial_img);
$image= '<img class="ProductSerial" src="data:image/' . $productserial_imgtype . ';base64,' . $productserial_imgBase64 . '">';
echo $image;
what I want to do is save this image directly to the server hard disk rather than display it to the user.
I have tried to use PHP's imagegif but it doesnt like the fact that $image is in a string format.
Any advice will be welcome. Thanks as always
If you need to save the image on the disk you would need to use imgpng() function.
An example which i got from here.
imagepng($bc->draw($data, $type, 'png', false),'ur_image_location');
$small_graph_height = 55;
$small_graph_width = 1.2;
$large_graph_height = 55;
$large_graph_width = 1.14;
$type = "gif";
$code = "code39";
$to_browser = TRUE;
include_once "application/libraries/Image/Barcode2.php";
$ticketno='TDN4993';
$productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
$productserial_type = $code;
$productserial_imgtype = $type;
$productserial_bSendToBrowser = $to_browser;
$productserial_height = $large_graph_height;
$productserial_width = $large_graph_width;
$productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);
ob_start();
imagepng($productserial_img);
$png = ob_get_contents();
ob_end_clean();
file_put_contents('barcode.png', $png);
echo 'image saved to file barcode.png';

Displaying an image in php using mysql

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?

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.

Categories