Loading an image through PHP - 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.

Related

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'];

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

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

Return image using restler

Is it possible to use Luracast Restler to return an image? Something like calling:
http://myserver.com/api/users/002/avatar
to download a png?
It is possible to serve images with Restler.
You need to do the following in your API method
Set the content type header for the right image type (png, jpeg etc)
header("Content-Type: image/png");
echo the image content
Example
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im); //this sends the image as the response
imagedestroy($im);
use exit or die to stop execution instead of the usual return result

Show image created by imagejpeg

I create an image with an external function.
The function that returns the raw data of the image:
function create_image()
{
...
ImageJPEG($myimg,NULL,85);
$imgdata = ob_get_contents();
ob_end_clean();
return $imgdata;
}
My script which should show what the image looks like:
$rawdata = create_image();
<img src="data:image/jpeg;base64,".base64_encode($rawdata)."" />
Now the image is not complete in the <img> tag. If I make the quality 50 (with ImageJPEG($myimg,NULL,50);) the image will be displayed completely. If I catch the rawdata and write it to the disk, the image will be complete in every quality.
$rawdata = create_image();
$im = imagecreatefromstring($rawdata);
ImageJPEG($im,"./test.jpg",90);
Only in the <img> tag it doesn't work.
Does anybody have an idea why it doesn't work?
I personally have never used this technique, I usually use a simple image tag with my image.jpg.php (for example) as an image. For this I put a header("Content-type: image/jpeg") in the image file and simply echo the data.
I really never have tried it with raw data, but I believe this would be preferrable, especially for maintenance (and compatibility).

readfile equivalent for binary data?

I'm using http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation to access private files using php. I can get the data of the file by saying $object->body. I actually want to see the image in the browser or play the video in a video player. Is there a way to do that?
I think I need something like readfile. The problem is readfile is I need the path to the file. The path is private so I cannot use that. Is there a way to do a readfile of the binary data?
I put this in the php thinking this would help but it still displays the binary data.
header('Content: image/jpeg');
header('Content-Disposition: inline; filename=IMAG0108.jpg');
echo $object->body;
You just set the content-type header and output the readfile to the browser. What I do is create a new php file, like "showimage.php", that accepts an ID or some such to know what image to display. Then I use it in a browser page: .
In showimage.php, something like:
<?php
header('Content-type: image/png');
readfile('/var/images/' . $_GET['id'] . '.png');
// or
// echo $object->body;
?>
That would read a file from the local system and output it as an image. Off the top of my head, so I might have messed up that code!
header('Content: image/jpeg');
echo $object->body;
Should work fine (for JPEGs), you need know what filetype is in question and then send appropriate content headers.

Categories