This question already has answers here:
PHP display image BLOB from MySQL [duplicate]
(2 answers)
Closed 6 years ago.
Good Afternoon, y'all!!
I have a database with a table containing a row with 4 columns called "ID", "login", "pass" and "image"(BLOB). I have a system with users authentication and etc, and I want to implement the image registered by the user to be shown in the topbar. Everything's working pretty well so far, the only problem is that the database image is printing like this:
ÿØÿàJFIF``ÿÛC %# , #&')*)-0-(0%()(ÿÛC (((((((((((((((((((((((((((((((((((((((((((((((((((
ÿÀ€€"ÿÄ ÿĵ}!1AQa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’
“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ ÿĵw!1AQaq"2B‘¡±Á #3R
ðbrÑ $4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹º
Detail: When I open the image selected to the database in NOTEPAD, it's the same shown above.
IMAGE.PHP
include "dbconnection.php";
$defaultpath = "img/avatar.png";
$sql = "SELECT * FROM `bg_users`";
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
if (!isset($_SESSION)) {
$_SESSION['UserImage'] = $result['image'];
print $_SESSION['UserImage'];
}
else {
echo "src='img/avatar.png'";
}
?>
Again, the interaction between PHP and MySQL is completly fine. The problem is that PHP is not printing the file as image. I can't make header("Content-type: image/png"); because the page i want to include image.php already have a header parameter.
Could't someone help me on this? I would be very pleased
Thank You!
First of all i wouldn't save images as blob in your database, easier to just store them in a folder and save the the path to it in the database.
If you want to do it your way, do the following:
echo '<img src="data:image/png;base64,'.base64_encode( $result['image'] ).'"/>';
This is a really bad practice though and might slow down the page load quite a bit. I'd suggest you re-evaluate you database structure and store the images directly and just save the path in the database
Related
This question already has answers here:
Convert HTML to image in php
(2 answers)
Closed 3 years ago.
I want to make a some step of saving data into DB as BLOB data type. I need convert data to BLOB in the DB. I have the data that are considered as HTML output in the some file. The selected programming language is PHP with Zend Framework 1 and database is MySQL.
I tried to save HTML page as valid BLOB image in DB, but it is still not working. I can't find any solutions about it and I don't know how to do. When I got a content from URL and saved it into DB as BLOB by using function file_get_contents($url), that is worked to me fine.
Here is a code that saves the content of the HTML page in the file described below into DB as BLOB.
$file = "C:\test.html";
$fp = fopen($file, 'r');
$content = fread($fp, filesize($file));
fclose($fp);
$dbModel = new MyTable($this->db);
$dbRowSet = $dbModel->find(1);
$dbRow = $dbRowSet->current();
$dbRow->map = $content;
$dbRow->save();
Here is a preview of saved HTML page in DB, but there I can't show any BLOB image.
There is shown BLOB image. I had the URL page and tried to save it into DB.
I expected that the result of saving data (HTML page) into DB should be that DB contains valid BLOB images.
Thank you for your help.
You can download wkhtmltoimage from this link. There is a version for all operating systems so that shouldn't be a problem. Then you can use it like so:
$path="wkhtmltoimg/wkhtmltoimage.exe"; //path to your executable
$url="http://google.com";
$output_path="test.png";
shell_exec("$path $url $output_path");
One thing you want to note is that if PHP is in safe mode, shell_exec will not work and you won't be able to do your conversion.
Credit: #Tom
Convert HTML to image in php
After this you just need file_get_contents() and save blob in the database.
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">';
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
$sql="SELECT * FROM `blob` ";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)) {
$image=$row ['image'];
header("content-type: image/jpg");
echo '<img src="path/'.$image.'" width="360" height="150">';
}
This is the code i'm using to display the image uploaded to my database... however, i get the error message that the headers have already been sent... i have no idea what i'm doing wrong!
i can see on my website where my images are meant to be but no actual image!
In general:
When you get this message it seems that there is an output done before. It can even be a simple "whitespace" character like [:space:].
But:
In addition to that you seem to get some things wrong. You do create HTML (!) but you send a header-message that tells the browser that it get's binary data of an image.
So when you really have binary data in your database you have to output binary data and not any html "thingy". I really really recommend you to read a good book about how a server works and what header(..) actually does.
Please also have a look here:
php:Store image into Mysql blob, Good or bad?
http://pujanpiya.com.np/?q=node/25
PS: I did not get into any more detail about your question neither provide a solution because I do not think this would help you rather than solving this issue of misunderstanding temporarily.
Your code is totally wrong; storing images inside a MySQL database is a bad idea and you're using your image data as a path to a nonexistent image; if you still want to stick with the idea of having images in your database, here's example code that would work :
while ($row = mysql_fetch_array($query)) {
echo '<img src="data:image/jpeg;base64,'.base64_encode($row["image"]).'" />';
}
This encodes the image into base64 and then uses that as a data URI inside an img; no headers needed.
Also, mysql is deprecated; use mysqli or PDO instead.
The problem is that you're doing it in a while loop, which will be executed multiple times:
while($row=mysql_fetch_array($query)) {
$image=$row ['image'];
header("content-type: image/jpg"); // Headers are sent here
echo '<img src="path/'.$image.'" width="360" height="150">'; // Content here
}
When mixing headers like this, what you would normally want to do is put the header before any content. However in your case, this wouldn't make sense either because you are sending "content-type: image/jpg". If you are echoing an image to the browser using HTML, the content-type should be text/html (which is sent by PHP by default). So just leave that line out completely. If you are trying to send the actual binary contents of an image, then you wouldn't use an HTML tag, just send the Content-Type header and then echo the contents for one single image.
I have a postgres database with stored images 'bytea' type and I try to display them into a browser with PHP. I found the way to display one of them but I can't make it for more than one. The code I use is the following:
File Name - display_image.php
$conn = pg_connect("dbname=test user=postgres password=postgres");
$temp = '/home/postgres/tmp.jpg';
$query = "select lo_export(image, '$temp') from map ";
$result = pg_query($query);
if($result)
{
while ($line = pg_fetch_array($result))
{
$ctobj = $line["image"];
echo "<IMG SRC=show.php> </br>";
}
}
else { echo "File does not exists."; }
pg_close($conn);
File Name - show.php
header("Content-type: image/jpeg");
$jpeg = fopen("/home/postgres/tmp.jpg","r");
$image = fread($jpeg,filesize("/home/postgres/tmp.jpg"));
echo $image;
The problem seems to be the "tmp.jpg" virtual file which displays only one image. If the result of the query is 7 images then it displays 7 times the same image within a while loop. How can I solve this?
Thanks for the interest!
I did this some time ago for bytea.
You need to run your bytea data through pg_unescape_bytea. See http://php.net/manual/en/function.pg-unescape-bytea.php
Basically your SQL query returns the bytea field in an escaped format.
However this is not what you are doing. And so the above is just for the next poor sap who comes here looking for bytea help. Please amend to note you are using LOB's not BYTEA's.
Also note that your code there is not concurrency safe. If two users request different images, my guess is that you will get both users getting different images. For this reason you should add the oid to the retrieval url, and name your file /tmp/$oid.jpg where $oid is the oid of the large object. You will need to retrieve that info (I believe it looks like it is stored in the image field of map?). On the other hand that assumes that all files are essentially public. if that's not the case, you want to move everything into the show_image.php and clean up when you are done.
I know it's not the greatest technique, but coming from Foxpro and Dbase background, some habits just don't die. I am absolutely fresh in PHP and trying to re-create learning curve of my earlier programming experience.
I have drilled GOOGLE for the issue and tried to come up with the script, only issue is sometimes I came up with garbles, sometime empty screen, sometimes only IMAGE.
The scenario is If I am able to create this simple script, I will probably understand how to handle images issue.
I have a database in my MYSQL called crm. In the database I have a table called mast_cust with fields f_name, l_name and pic (BLOB)
I already have some records in them.
What I understood was:
Images and Data (Textual) cannot be printed together
You have to have two scripts , one gathering the image and the other gathering data
The one which gathers data , calls the one which collects images and prints it.
What I want is, to see data in tabular format
First Name | Last Name | Image
These are my two scripts, which is the one which prints garble
Script 1 : Main PHP file - list.php
Script 2 : Image Storing Script: pix.php
list.php
<?php
$errmsg = "";
if (! #mysql_connect("localhost","root","Admin"))
{
$errmsg = "Cannot connect to database";
}
#mysql_select_db("crm");
$strSQL = "select f_name,l_name,pic from mast_cust";
$rsPix = mysql_query($strSQL);
$numRows = mysql_numrows($rsPix);
$i = 0;
while($i < $numRows){
?>
<img src="pix.php?pixID=<?php echo mysql_result($rsPix,$i,"pic"); ?>"/>
<?php
$i++;
}
?>
Script 2 pix.php
<?php
$errmsg = "";
if (! #mysql_connect("localhost","root","Admin"))
{
$errmsg = "Cannot connect to database";
}
#mysql_select_db("crm");
if (IsSet($_GET['pixID'])){
$gotten = #mysql_query("select pic from pix where cust_id = ".$_GET['pixID']);
header("Content-type: image/jpeg");
while ($row = mysql_fetch_array($gotten))
{
print $row['pic'];
}
mysql_free_result($gotten);
}
?>
Any help resolving this issue is highly appreciated.
Thanks and Regards
It seems like you're storing the jpeg image as a blob in mysql.
1.) You can only send one pic at a time. So no need for a for loop.
2.) If so, you'll need to format the output of the data for the pic, so that a browser can read it.
I would recommend against this approach. You should avoid using a relational database for storing images. Try storing the jpegs on a regular filesystem or a file server (like S3), and store the url to it in the database.
If obfuscating the image url isn't enough, try the following approach:
Echo/print a jpg-image with php, for safety?
It uses:
http://php.net/manual/en/function.readfile.php