How to display image from mysql blob in PHP (joomla) - php

I create a component in my joomla website. the component shows some photos (not big, only 8KB). the photos are stored in mysql blob. i can upload the photos to the joomla database but i cannot display it on the website. whatever i do it only show some encoding character or blank. I tried to create a separate page but but the result is same. Here is what i have done :
mycomp is my joomla component.
admin.mycomp.php
<?php
function showDetail($option)
{
$db = &JFactory::getDBO();
$id = mysql_real_escape_string(JRequest::getVar('id'));
$query = "select id,myphoto from jos_myphotos where id = ".$id;
$db->setQuery($query);
$rows = $db->loadObjectList();
HTML_myphoto::showPhoto($rows,$option);
}
?>
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
header("Content-type: image/jpeg");
echo $row->myphoto; //this will show some encoding character
echo base64_decode($row->myphoto); //this will show blank page
//change echo with print get the same result.
...
}
...
}
I tried to create a separate page like this :
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
?>
<img src="show_image.php?myphoto=<?php echo $row->myphoto;?>" width=200 height=300>
<?php
...
}
...
}
show_image.php
<?php
$myphoto = (isset($_GET['myphoto'])) $_GET['myphoto'] : false;
if($myphoto)
{
header("Content-type: image/jpeg");
echo $myphoto; //this will show some encoding character
echo base64_decode($myphoto); //this will show blank page
//change echo with print get the same result.
}
?>
the result is same.

I think you have 2 options:
Either you make an image tag with its source in a PHP file receiving only a ID parameter and retrieving the photo's string in the DB and echoing it.
Or you echo directly your photo's string in your tag:
<img src="<?php echo base64_decode($myphoto); ?>" />
EDIT
I just checked in an old app where I store the favicons in a DB. You don't need to base64_decode when you display your image inline (my option 2).
So FYI, this image works:
<img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=" style="margin-right: 5px; vertical-align: middle;" class="bbns_itemDragger">
And it is stored in my DB like this (base64 encoded):
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=

I'm sorry, did you skip some lines from show_image.php?!
Cause $myphoto is just the id of the photo. You can't base64_decode an ID.

Related

how to show blob image in html?

I have a image stored in mysql as mediumblob and now I want to show it in html page, so I am doing this with it:
$c = base64_encode($resu[0]->image);
$image = '<img src="data:image/jpeg;base64,'.$c.'" />';
echo $image;
But I am getting only half of original image, so am I missing something here ?
Just an idea, may be you can seperate the logic to display the image.
What I mean is that you can create a file like image.php that accepts the id or filename
of the image and then display the image. Then you can simply refer the image in your HTML
by, for example, doing something like this:
<img src="image.php?imgId=12547"/>
in image.php file something like the following
$imgId=isset(GET['imgId'])?GET['imgId']:0;
$sql = "SELECT * FROM theBlogs WHERE ID = $imgId;";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: image/jpeg");
echo $row['imageContent'];
Just perform a quick test with strlen on $resu[0]->image variable and check blob size in DB and check if they are different sizes for sure.
Display in li tag means use this
<li data-thumb='<?php echo "data:image/jpeg;base64,".base64_encode($img1 ); ?>'>
<div class="thumb-image">
<img <?php echo 'src="data:image/jpeg;base64,'.base64_encode( $img1 ).'"';?>
data-imagezoom="true" class="img-responsive" alt="">
</div>
</li>

PDO to retrieve and display images without creating files

Trying to loop through a test database with images (I know many say not to do this, but it simplifies so much in terms of backups, etc.). I can get the result I want by creating image files on the fly, but there must be a way to do this without creating files. Can someone suggest a syntax I can use without having to create these image files?
Here is what I have working:
<?php
// configuration
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT id,title,author,description,cover FROM books";
$q = $conn->prepare($sql);
$q->execute();
$q->bindColumn(1, $id);
$q->bindColumn(2, $title);
$q->bindColumn(3, $author);
$q->bindcolumn(4, $description);
$q->bindColumn(5, $cover, PDO::PARAM_LOB);
while($q->fetch())
{
file_put_contents($id.".png",$cover);
echo ("<img src='".$id.".png'><br />, $title, $author, $description,<br/>");
}
?>
I am thinking that we should be able to eliminate the "file_put_contents.." line and in the echo line, replace the
<img src='".$id.".png'>"
with some php/pdo statement that retrieves the blob and puts it in the proper format. Tried a few things, but have not been successful.
Any suggestions would be helpful!
you do not need to do it in 2 separate files and invoke the script in src attribute of img tag.
Try do this
echo '<img src="data:image/'.$type.';base64,'.base64_encode($image).'"/>';
Where $type is the extension of the image(.png/.jpeg/....) and $image is the binary of the image that you have stored in your DB. in my case I pull the value of the type of image from the db, if you store always the same extension(ex jpeg) you can simply write:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
the method is an alternative to do that with 2 files.
You need to write code in 2 files. As when browser gets <img src="path/to img_file"> code (or code like <script src="....">), etc, a separate request is sent to server by browser at src path value. So, you also need to create file img_file.
Pseudo code is below,
Firstfile.php
<?php
..................... Other code
while($q->fetch())
{
?>
<img src="image.php?id=<?php echo $id; ?>"><br />,
<?php
echo "$title, $author, $description<br/>";
}
?>
And at image.php file,
header('Content-Type: image/png');
$id = $_GET['id'];
$query = " ..... where id = '".$_GET['id']."'";
//You need error handling if $_GET['id'] is integer and valid value. I am not writing this error handling code
if($q->row_count!=1){
//no database row found. It's error.
echo "Show no image found image. As browser expects image you can not write text here";
die;
}
//it's valid image, else code is already terminated by above die.
while($q->fetch())
{
//show image
echo $cover;
}
?>
I wrote Pseudo code exact code depend on requirements.
If you want .png extension, you can use Apache rewrite. Google it you will get it.
When first time i wrote answer, I missed last php ending tag. By the way, last ending tag ?> is optional in php.
If you are getting X , it seems first file code is ok. As imag_file is not at server, it's showing 404 error. View source to check whether $_GET['id'] is correct. If id is correct, then you want to write at file img_file.php

If MSSQL Table Column is NULL, Change CSS Style Using JS using PHP If Statement is Not Working

I am trying to use a PHP Query to get an image name from my MSSQL table column. The queried image name is put into an <img> tag. If the column is empty, it should set the empty column to the image noimageishereforgbmtrailerserviceltd999.png, which is a blank .png image and make the link unclickable. I am doing this to essentially hide the image from the user if there is no image set, so the user doesn't see a big X inside of where an image should be. The code currently changes the column to noimageishereforgbmtrailerserviceltd999.png correctly, but does not change the css styles of the link around it. Here is the PHP code I'm using:
$job_posname = "SELECT * FROM new_trailers1 WHERE orderid = '$sn'";
$query=mssql_query( $job_posname, $connection);
$array=mssql_fetch_assoc($query);
$job_posname7=stripslashes($array['photo1']);
if ($job_posname7['photo1']===NULL || ctype_space($job_posname7['photo1'])){
$job_posname7 = "noimageishereforgbmtrailerserviceltd999.png";
echo "<script>document.getElementById('picca2').style.pointer-events='none';</script>";
echo "<script>document.getElementById('picca2').style.cursor='default';</script>";
} else {
$job_posname7=stripslashes($array['photo1']);
}
?>
<a id="picca2" href="unitimages/<? echo $job_posname7; ?>" onclick="swap(this); return false;"><img id="pica2" src="unitimages/<? echo $job_posname7; ?>" width=50 height=50></a>
Thank you for any help. All help is appreciated.
Can't you default the noimageishereforgbmtrailerserviceltd999.png on all columns, and just change it if the image exists on the database? I am assuming you are generating the columns dynamically.
Or, just add a class on a PHP variable if the condition is set.
Make a .class in css and just call it depending on what you need.
For example
$job_posname = "SELECT * FROM new_trailers1 WHERE orderid = '$sn'";
$query=mssql_query( $job_posname, $connection);
$array=mssql_fetch_assoc($query);
$job_posname7=stripslashes($array['photo1']);
if ($job_posname7['photo1']===NULL || ctype_space($job_posname7['photo1'])){
$job_posname7 = "noimageishereforgbmtrailerserviceltd999.png";
echo "<script>document.getElementById('picca2').style.pointer-events='none';</script>";
echo "<script>document.getElementById('picca2').style.cursor='default';</script>";
$my_css_class_that_hides_image = "hide";
} else {
$job_posname7=stripslashes($array['photo1']);
}
?>
<a id="picca2" href="unitimages/<? echo $job_posname7; ?>" class="<? echo $my_css_class_that_hides_image; ?>" onclick="swap(this); return false;"><img id="pica2" src="unitimages/<? echo $job_posname7; ?>" width=50 height=50></a>
... And define it on your style sheet:
.hide{
/** Style here **/
}

Display image in div based on value in Database

I have been working on a project but I have reached a point where I am stuck. I have a database that contains the the working status of some mahcines. The values for the status go from 1-5. I need to be able to display a different image for each machine in a webpage based off of the value that appears in the database for that Mahcine. I am drawing a big blank on how to do this. Im using a MySQL DB and everything is written in PHP.
Basically it this. If a machine has a status value of 1 then it shows a green image. If the value is 2 then it would be yellow and so on. . .
Hope you guys can help
You can try something like this:
// your mysql select, wich contains the machine data.
$query = mysql_query("select the data about machines...");
// you iterate on the result set and fetch each row to $data
while($data = mysql_fetch_array($query))
{
switch($data['machine'])
{
case "machine type 1": // you can put integer values here as well, like case 1:
echo '<img src="first_machine.jpg" alt = "first machine" />'
break;
case "machine type 2":
echo '<img src="second_machine.jpg" alt = "second machine" />'
break;
default: // undefinied
echo '<img src = "undefinied.jpg" alt = "undefinied" />'
}
}
Don't use the img tag, instead create a div for which you apply a style class same as the machine status value
<div class="machine status<?php echo $status;?>" ></div>
now in your css,
.status1{
background-image:url(red.jpg);
}
.status2{
background-image:url(green.jpg);
}
.status3{
background-image:url(jpg.jpg);
}
.machine{
width:50px;
height:50px;
}
Ok you can't display multiple images within a image/jpeg page...
You're telling the browser that the page is image/jpeg (in other words, the page is AN IMAGE) but you're echoing out multiple image data
You should rather use the gallery page to show all images like this:
<?php
// $images = result from database of all image rows
foreach ($images as $img) echo '<img src="img.php?id='.$img["id"].'">';
?>
and in img.php:
// Load the image data for id in $_GET['id'];
header("Content-type: image/jpeg");
echo $data;

Read multiple image php

I have two separate files, one is to display the html/php document image, and the other is a php file that renders the image using the header function content-type:image/jpeg.
I tried using it with one image and it works well. However, I need to display multiple images. How could I do this?
The html/php doc has an img tag that points out to the php file that renders the image
echo "<image src=Image.php>";
The image.php
$selectimage = mysql_query("SELECT Image from ImageTbl", $con);
if($selectimage)
{
header("Content-type:image/jpeg");
while($row = mysql_fetch_array($selectimage))
{
echo $row["Image"];
}
}
make two files one for image another for fetching the row like this
image.php
$image_id = $_GET["id"];
header("Content-type:image/jpeg");
//query database to get only one image from id
echo $row["Image"];
another file
getimages.php
//query for image data
while($row = mysql_fetch_array())
{
echo "<img src='image.php?id=$row[id]' />";
}
You can't output all the images together, because to the browser, it will look like the data of multiple images mushed together, which is nonsensical. Also, each image tag can only display one image. To solve this, give the image table an ID field to identify the image.
Then in the file that outputs HTML, do something like this (passing the ID for the image you need):
echo "<image src='Image.php?id=1>";
echo "<image src='Image.php?id=2>";
echo "<image src='Image.php?id=3>";
And then in the file that outputs the image, do:
$id = intval($_REQUEST['id']); // intval will validate the ID to be an int
$selectimage = mysql_query("SELECT Image from ImageTbl WHERE id=$id LIMIT 1", $con);
if ($selectimage) {
$row = mysql_fetch_array($selectimage);
if ($row) { // check if the image really exists
header("Content-type:image/jpeg");
echo $row["Image"];
}
}
Use a foreach loop to loop through the requested records and echo them out independently to the img tags which your using.
That would be the best way in my opinion.
If you want to display number of different images using one script, try to add some unique hash to the script name ( for e.g. md5( microtime() ) )
$seed = md5( microtime() );
echo '<image src="Image.php' . $seed . '">';

Categories