(1)
$file = $_GET['file'];
echo '<img src="'.$file.'" />';
(2)
$file = $_GET['file'];
$imginfo = getimagesize($file);
header('Content-type: '.$imginfo['mime']);
echo file_get_contents($file);`
From these 2 code, my image can show in the browser nicely. But what is the differences of them? Which method should I prefer?
The first example you've posted is simply "including" the image file into the DOM.
It would essentially output something like:
<img src="path/to/image.png" />
While the second option actually sets the Content-Type to whatever the mime of the image is. Meaning if it's a png for example, the page that runs that script will actually be served as a whole image.
If it was a png image, it'd return the content type of image/png.
The key difference is output:
Example 1 references from a path whereas example 2 outputs the binary and labels it an image (so HTTP clients can interpret the response correctly).
To the point... example 1 is preferred because it doesn't have to store the file contents in memory.
The first example you've posted is simply:
output:
<img src="image.png" />
The second option actually sets the Content-Type:
It's return the content type of image/png or image/jpg like that.
I prefered go to second example.
Related
Hi i write some code for images to be put side by side.I use Imagick library for that purpose.This is my code.
$im = new Imagick();
// session contain image path like upload/my.jpg
$im->readImage("http://localhost/wordpress3.5/".$_SESSION['imgname']);
$im->readImage("http://localhost/wordpress3.5/".$_SESSION['preimgurl']);
$im->resetIterator();
$combined = $im->appendImages(false);
/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;exit();
But the output is not what i suppose to be.this is output.I write this code under the plugin/ files.Also i want to save that image to directory like "localhost/wordpress/uplaod_pic/".
You should use an image tag with the src tags containing the direct or base64 version of the image.
First example would be direct:
echo '<img src="http://localhost/wordpress3.5/'.$_SESSION['imgname'].'">';
Second would be using base64 with the data URI scheme, PHP Example:
echo '<img src="data:image/png;base64,'.base64_encode($combined).'">';
I would recommend the first method, simply because it looks like a product display, the images are most likely public and hotlinking can be busted if you choose.
In both examples, since the image is inline, you wouldn't need to set the content-type to an image.
You should also place the correct mime type within the second version, either image/png, image/jpeg or others depending on the image.
Edit: To extend this:
$combined contains the image, so you want to save this, simple use:
file_put_contents('upload_pic/'.$time().'.png', $combined);
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 need to send a GET request to my page pic.php, and I want to get a real picture in return.
For now I implemented this idea like this:
<?php
if ((isset($_GET['pic']))&&(isset($_GET['key']))){
$pic = $_GET['pic'];
$pic=stripslashes($pic);
header('Location: /content/'.$pic);
}
?>
But it's not really what I want - it redirects to image directly. What I want is to keep the same URL, but get a needed file depending on what values were submitted.
What is the best way to do that?
thx.
This example code snippet should do what you ask. I've also included code to only strip slashes if magic quotes is enabled on the server. This will make your code more portable, and compatible with future versions of PHP. I also added use of getimagesize() to detect the MIME type so that you output the proper headers for the image, and do not have to assume it is of a specific type.
<?php
if(isset($_GET['pic']))
{
//Only strip slashes if magic quotes is enabled.
$pic = (get_magic_quotes_gpc()) ? stripslashes($_GET['pic']) : $_GET['pic'];
//Change this to the correct path for your file on the server.
$pic = '/your/path/to/real/image/location/'.$pic;
//This will get info about the image, including the mime type.
//The function is called getimagesize(), which is misleading
//because it does much more than that.
$size = getimagesize($pic);
//Now that you know the mime type, include it in the header.
header('Content-type: '.$size['mime']);
//Read the image and send it directly to the output.
readfile($pic);
}
?>
I can see you doing this in two ways:
1) Return the URL to the image, and print out an image tag:
print '<img src=' . $img_url . ' />';
2) Alternatively, you could just pull the data for the image, and display it. For instance, set the header appropriately, and then just print the image data.
header("content-type: image/png");
print $img_data;
This assumes that you have the image data stored in a string $img_data. This method will also prevent you from displaying other things on the page. You can only display the image.
You can load the image, send the image headers, and display the image as such:
header('Content-Type: image/jpeg');
readfile('/path/to/content/pic.jpg');
Obviously the headers would depend on the filetype, but that's easy to make dynamic.
Not sure if I understand what you're after, but guessing that you want to load the picture in an img tag?
If I'm right you just do:
<img src=http://www.domain.com/pic.php?"<?php echo image here ?>" />
Basically you just make the source of the image the webpage you get directed to where the image is.
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).'">';