i am attempting to display an image from mysql blob (i know its not best practice) in my PHP page which i will then bring into my iOS app.
I'm having trouble setting the page header which i believe needs to be set as an image.
So, this shows the image but I do not believe the page header is correct:
//header("Content-type: image/png");
echo '<img src="data:image/png;base64,' . base64_encode( $row['image1'] ) . '" />';
However, this does not show my image:
header("Content-type: image/png");
echo '<img src="data:image/png;base64,' . base64_encode( $row['image1'] ) . '" />';
What am I missing? I believe the image should show when the header is set to image/png but i'm getting an error that it cannot be displayed because of errors.
Thank you!
header("Content-type: image/png");
This tells your browser that you're about to pass it raw binary data that is a PNG file. So anything output after that would have to be a binary PNG. You can't then place HTML and expect that to work
echo '<img src="data:image/png;base64,' . base64_encode( $row['image1'] ) . '" />';
This works because you're base64 encoding your image (translates binary into text), outputting that to the browser and then telling your browser to interpret it as base64.
If you want to output the raw binary data you have to rearrange the order. So here's your HTML
<img src="image.php" />
Now you'll note the src points to a PHP file. That's because we're going to have that PHP file return an image. Here's what image.php would look like
//Your query here
$row = mysqli_fetch_assoc($result);
header("Content-type: image/png");
echo $row['image1'];
This works because the browser will call the PHP file, expecting an image. The header tells the browser that this is a PNG file and you can now dump your binary PNG data.
Related
<?php
header("Content-type: image/jpeg;charset=utf-8'");
$path = 'example/source.jpg';
$da = file_get_contents($path);
$base64 = base64_encode($da);
$src = 'data:image/jpeg;charset=utf-8;base64,'.$base64;
echo '<img src="'.$src.'">';
?>
php v5.6.2
I tired copying the $src value in debug and pasted in img src value. still its not showing up.
what did i missed here?.
thanks in advance
header("Content-type: image/jpeg;charset=utf-8");
here you say to the browser i will send you an jpeg image,
then:
echo '<img src="'.$src.'">';
here you send HTML.
because you said it was a jpeg image, the browser will try to render your html as jpeg. since the ascii text-based HTML format is completely incompatible with the binary based jpeg-format, the browser will fail horribly when trying to render your image, and fail with some error (probably image is corrupt or something like that.)
you can either fix your Content-Type header to specify that you're sending HTML, then the browser will (probably successfully!) try to render it as such, eg:
header("Content-type: text/html;charset=utf-8");
or you can modify your code to actually send the image as jpeg, eg:
<?php
header("Content-type: image/jpeg");
$path = 'example/source.jpg';
readfile($path);
(btw a base64 encoded jpeg image will be about 33% larger than just the raw jpeg image, so if you want a fast pageload, or you want to save up on bandwidth, or you want to save up on ram, using readfile() is faster, requires less bandwidth, and requires less ram, both for the server and the client, compared to your embedded base64 approach.)
So maybe your problem is in your mime type. then try this code two solve:
$path = 'domain.com/example/source.jpg';
$content = file_get_contents($path);
$file_info = new \finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($path));
$base64 = base64_encode($content);
$src = 'data:'.$mime_type.';charset=utf-8;base64,'.$base64;
echo '<img src="'.$src.'">';
Note: its better to use path from full address domain, if you want to use from path use readfile()
I'm using an image outside of my docroot and want to display that image inside of a function.
How do I correctly do this?
Here is what I have so far: (Both functions are in the same file)
function page(){
echo'
test<br />
'.output().'
';
}
function output(){
header("Content-Type: image/gif");
readfile( '../../../dirOutsideDocRoot/test.gif' );
}
This currently will output the image but I am not able to see the "test" above it. Is it possible to get the image into the page function using header?
The final content you send to the client can have one content-type only. Either image or text. If you want both in a single page, (when image isn't written to file) you could write the image in base64 in the following way:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
In your case,
data:image/gif;base64,<base64_encoded_image>
See Data URI scheme
Something like the following will work: (Untested)
$img = fread(fopen($path, "r"), filesize($path));
$base64 = "data:image/gif;base64," . base64_encode($img);
It sounds like what you are trying to do is to display an image and text on the same page. To do that you will have to make a page that has the text and has an img tag pointing to another php page that sends back just the image.
Your Content-Type header tells the browser that the entire page is an image. Although, that won't happen either because php will fail saying that data has already been sent so it can't output a header.
Hope this helps.
EDIT: You could also like Cthulhu said, embed the image with base64 like this:
function output(){
$imgbinary = fread(fopen('../../../dirOutsideDocRoot/test.gif', "r"), filesize($filename));
echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary).'" />';
}
For more info about base_64 encoding in php, see http://php.net/manual/en/function.base64-encode.php.
You should have two php pages:
Page 1:
echo'
test<br /><img src="page2.php"/>';
Page 2:
header("Content-Type: image/gif");
readfile( '../../../dirOutsideDocRoot/test.gif' );
I am getting an error when I try to create png files. My code is like:
require_once('....');
header("content-type: image/png");
echo `$command`;
PNG file is generated by $command and the problem is that I include another PHP file and thus it can't display images. How would I be able to solve this?
If you want to show it as an image in the browser, you'll need to base64_encode() it to be sent to the browser instead of just echoing it.
$image = `$command`;
$b64 = base64_encode($image);
echo '<img src="data:image/png;base64,' .$b64. '">';
Or you might try using imagepng() and related GD functions for this.
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 need to send a base64 encoded string to a client. Therefore, I'm opening and reading an image file on the server, encode it and send that data along with the image/jpeg content-type to the browser.
Example in php:
$image = $imagedir . 'example.jpg';
$image_file = fopen($image, 'r');
$image_data = fread($image_file, filesize($image));
header("Content-type: image/jpeg");
echo 'data:image/jpeg;base64,' . base64_encode($image_data);
Clientside, I'm calling:
var img = new Image();
img.src = "http://www.myserver.com/generate.php";
img.onerror = function(){alert('error');}
$(img).appendTo(document.body);
That does not work for some reason. onerror always fires. Watching the FireBug Network task for instance, tells me that I'm receiving the correct header information and a correct value of transfered bytes.
If I send that data as Content-type: text/plain it works, the base64 string is shown in the browser (if I call the script directly). Copying and pasting that output into the src of a <img> element shows the image as expected.
What am I doing wrong here?
Solution
Thanks Pekka for pointing me on my mistake. You don't need (you can't!) encode that binary image data as base64 string in that kind of approach. Without base64 encoding, it just works.
If you set content-type to image/jpeg, you should give just the jpeg data, without the base64 crap. But you're treating the result as if it was html.
You're effectively building a data uri, which is ok, but as you noted, only as an uri. So leave the content type as it is (text/html), and
echo '<img src="data:image/jpeg;base64,'.base64_encode($image_data).'">';
and you're good to go.
I believe it can be done quite efficiently just using php only ... you can use the below function to render images in base64 encoded data
function binaryImages($imgSrc,$width = null,$height = null){
$img_src = $imgSrc;
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
if(isset($height) && isset($width))
{
echo '<img src="data:image/jpg;base64,'.$img_str.'" height="'.$height.'" width="'.$width.'"/>';
}
else
{
echo '<img src="data:image/jpg;base64,'.$img_str.'"/>';
}
}
how to use this function
binaryImages("../images/end.jpg",100,100);
run the function binaryImages .. 1st parameter is the image path , 2nd is the width and then the height ... height and width are optional
In this case, there is no reason to base64 encode the image data in the first place. What you want to emit is plain old image data.
Just pass through the JPEG image as-is.
The only way this would make sense to me is if you grabbed the output of generate.php via an AJAX call, and put the result into the src property directly. That should work (although not in IE < 8, but I'm sure you know that). But if you can call generate.php directly as the image's source, I don't see the need for this.
i would recommend it:
base64_encode Encodes data with MIME base64
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';