PHP: how to output to browser a png image from disk? - php

I've a file on a folder on disk I don't want to be visible from web browser
So i create an image.php file that take a file name and must 'do echo' to browser of the image.
Example:
mysite.com/image.php?name=selection.png
must show an image to the user into the browser.
Actually browser ask me to save.
I want to show it, not do ask to download...
i'm using this snippet
header("Content-Type: image/png");
header('Content-Length: ' . filesize($full_file_name));
header("Content-Disposition: inline; filename='$image'");
readfile($full_file_name);
exit(0);
if saved and opened, img is perfect. How to NOT ask to download it?
EDIT
Yes, i need something to use into image tag
Most of you are replying to my question telling me about image creation, but my question is all about different mode to tell to browser to show something and to ask to user to save something.
NO MORE REPLY ABOUT IMAGE CREATION - YOU'RE OFF-TOPIC !
Probably my question, my title, is not clear, but my question is simple:
- How to tell to browser to SHOW an image insted to ask user to save it
Image creation is working
Image usage via imag src is working
**But when user clicks on image, a new tab is opened with the images src as link, because I need to show full size image into browser.
In this situation browser ask me to save !
EDIT:
Removing
header("Content-Disposition: inline; filename='$image'");
doesn't change Firefox behaviour

try:
header("Content-type: image/png");
passthru("cat $full_file_name");
Be very careful with the passthru command if you're working with user input, since this function will execute anything you pass it.
https://www.php.net/manual/en/function.passthru.php
When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

To do this, you'd have to base64 encode the image, then output the result. You could use a function like this:
<?php
/**
* Base64 encodes an image..
*
* #param [string] $filename [The path to the image on disk]
* #param [string] $filetype [The image file type, (jpeg, png, gif, ...)]
*/
function base64_encode_image($filename, $filetype)
{
if ($filename)
{
$imgBinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
And then output the result as the source of the image, like:
$image = base64_encode_image('...name of file', '... file type');
echo "<img src='$image' />';
EDIT: I think I got the wrong end of the stick here, but oh well!

You can use PHP's GD library.
in your image.php.
<?php
header('Content-type: image/png');
$file_name = $_GET['name'];
$gd = imagecreatefrompng($file_name);
imagepng($gd);
imagedestroy($gd);
?>

You could alternatively use PHP's imagepng:
imagepng — Output a PNG image to either the browser or a file
<?php
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>

If your picture paths are stored in a database this method is okay. (I have exampled using MySQLi, adapt this to your Database API)
CREATE TABLE IF NOT EXISTS `PicturePath` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`Path` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;
--
INSERT INTO `PicturePath` (`ID`, `Path``) VALUES
(1, 'img/picture.png')
//End DB
// Start script
$PictureID = $_GET['Name'];
$Get_Picture = $Conn->prepare("SELECT PicturePath FROM pictures WHERE ID=?");
$Get_Picture->bind_param('i', $PictureID);
$Get_Picture->execute();
$Get_Picture->bind_result($Path);
$Get_Picture->close();
echo "<img src='$Path'></img>";
The above method is best if you are selecting images using URL Parameters
Otherwise:
$Picture = $_Get['Name'];
$Image = imagecreatefrompng($Picture);
header('Content-Type: image/png');
imagepng($Image);
might be the solution
Manual here:
http://php.net/manual/en/function.imagepng.php

Related

PHP display image without HTML

How may I display an image without using any kind of HTML.
Let's say I have some protected images, which may only be shown to some users.
The protected image is in directory images/protected/NoOneCanViewMeDirectly.png
Then we have a PHP file in the directory images/ShowImage.php, which check if the user is permitted to view the image.
How may I display the image using PHP only.
If you're not sure what I mean this is how I want to display the image. http://gyazo.com/077e14bc824f5c8764dbb061a7ead058
The solution is not echo '<img src="images/protected/NoOneCanViewMeDirectly.png">';
You could just header out the image with the following syntax
header("Content-type: image/png");
echo file_get_contents(__DIR__."/images/protected/NoOneCanViewMeDirectly.png");
if (<here your logic to show file or not>)
$path = $_SERVER["DOCUMENT_ROOT"].<path_to_your_file>; // to get it correctly
$ext = explode(".", $path);
header("Content-Type: image/".array_pop($ext)); // correct MIME-type
header('Content-Length: ' . filesize($path)); // content length for most software
readfile($path); // send it
}
Note: 1. image/jpg is not correct MIME-type, use image/jpeg instead (additional check needed), 2. readlfile() is better than echo file_get_contents() for binary data, 3. always try to provide content length for browsers and other software
You can use imagepng to output png image to browser:
$im = imagecreatefrompng("images/protected/NoOneCanViewMeDirectly.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

How can I display an image stored in a database on a php page?

I couldn't manage to show retrieved blob image file as image on my php page. The code part that shows the retrieved data from the database is as follows:
echo '<h4>'.$yaz["Header"].'</h4><br>'.$yaz["Picture"].'<p class="text">'.$yaz["Description"].'</p><br>';
when I write this code, I get Header and Description and any problem does not occur. But the picture comes as
����JFIFHH��:>ExifMM*����(2�;���i؈%PdCanonCanon EOS 500DHH2012:09:05 10:23:46
How can I display my picture on the php page?
That's simple.
Just don't store an image in database in a blob field. Instead, store the image itself on a filesystem, while in database store only name of the file. this way your code would work.
echo '<h4>'.$yaz["Header"].'</h4><br><img src='.$yaz["Picture"].'><p class="text">'.$yaz["Description"].'</p><br>';
Try like this:
$image = $row['image'];
$image_type= $row['image_type'];
$size = $row['image_size'];
$ext = explode('/', $image_type);
$name = $id . '.' . $ext[1];
header("Content-type: $image_type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
print $image;
exit;
Don't store the image in the database. store it in your file system. store name and location of the file in the database. Because
1.If database is corrupted, no way to retrieve.
2.Retrieving image files from db is slow when compared to other option.

PHP mySQL turning a string into a png is only working for the first image

So I am trying to get a bunch of photos to appear that are saved in a mysql database. With the code I am using, the page displays just the very first photo in the database with nothing else. There are 5 different photos and I don't know where they are going. If someone could help that would be great. My code is here:
while($imageRow = mysql_fetch_array($imageResults)){
$data = $imageRow['image_data'];
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
}
The headers will only display one image per page.
You could try:
while($imageRow = mysql_fetch_array($imageResults)){
$data = $imageRow['image_data'];
print '<img src="data:image/png;base64,'.$data.'" />';
}
That's untested, but something like that should work.
A better way would be to store the image file on the disk and store the location in the database.
You could either insert them into mysql as in blob type or simply upload the file to a folder and insert the file name into the database (I assume you just dont create random folders for each instance therefore you would know the destination path already)

header("Content-Type: image/jpeg"); returns broken image

Im fetching an blob image from my database, but it returns broken.
If i remove header("Content-Type: image/jpeg");
it returns the file extension at it should be since its a PNG file
‰PNG IHDR\r¨fÆÉIDAT
Any ideas whats the problem ?
And yes. i tried the header("Content-Type: image/png"); also
I have tried with ob_start and ob_end_flush();
code
ob_start();
$query = $db->query("SELECT `image` FROM `userdetails` WHERE id = '{$_SESSION['uid']}' ");
$row = $query->fetch(PDO::FETCH_ASSOC);
echo $row['image'];
header("Content-Type: image/jpeg");
ob_end_flush();
thanks
What you ask about in your question is subject to many parameters of which I fear your question does - if at all - scratch only some of them.
What pops into the eye is the PNG header:
‰PNG IHDR\r¨fÆÉIDAT
does not look broken. So you probably did have a problem to store the image into the database. Maybe the data was truncated / modified and this change got unnoticed?
One way to deal with that is to create a checksum of the files before putting them into the blob to be able later on to verify the data-integrity.
You need to output the header before the image data, not afterwards:
header("Content-Type: image/png");
echo $row['image'];

Loading an image through PHP

I'm trying to load an image through PHP, but I don't know how.
The filename is stored in the database, such as image.jpg
if($_GET['image']){
// Client requesting image, so retrieve it from DB
$id = mysql_real_escape_string($_GET['image']);
$sql = "SELECT * FROM $tbl_name WHERE id = '$id' LIMIT 1";
}
The client needs to request an image like so
http://example.com/index.php?image=1
And then it should return the image, so it can be embedded like this:
<img src="http://example.com/index.php?image=1" alt="" />
Is this possible?
$img = 'path/to/image.jpg';
header('Content-Type: image/jpeg');
readfile($img);
just tested it
You can use the GD library for that. You start by creating a resource using a function like http://php.net/imagecreatefromjpeg. You will need to provide the path as a parameter.
After that, you just output the resource using a function like http://php.net/imagejpeg.
Don't forget to send the content type header, and also to use imagedestroy on the resource.
Update:
Consider this sample:
$im = imagecreatefromjpeg('path/to/image.jpg');
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);
I suggest you first make a file called image.php. So you will call image.php?id=1
Have image.php header be the image type. header('Content-Type: image/jpeg');
Then you can use the GDImage library in PHP to load the image, and output it. Or you can read the file and output it. The header() is key.

Categories