I want to show image with php script. Here is my current code:
<?php
if (isset ($_GET['id'])) $id = $_GET['id'];
$t=getimagesize ($id) or die('Unknown type of image');
switch ($t[2])
{
case 1:
$type='GIF';
$img=imagecreatefromgif($path);
break;
case 2:
$type='JPEG';
$img=imagecreatefromjpeg($path);
break;
case 3:
$type='PNG';
$img=imagecreatefrompng($path);
break;
}
header("Content-type: image/".$type);
echo $img;
?>
But it doesn't show the image. What is the right way instead of echo $img?
just like this :
public function getImage()
{
$imagePath ="img/wall_1.jpg";
$image = file_get_contents(imagePath );
header('content-type: image/gif');
echo $image;
}
header("Content-type: image/jpeg");
imagejpeg($img);
There are functions for each format.
PNG: imagepng http://php.net/imagepng
JPEG: imagejpeg http://php.net/imagejpeg
GIF: imagegif http://php.net/imagegif
In your case you could add:
switch ($t[2])
{
case 1:
imagegif($img);
break;
case 2:
imagejpeg($img);
break;
case 3:
imagepng($img);
break;
}
I've used echo() for this before and it's worked. But try using imagejpeg() function instead.
Also, make sure you don't have any other content being output either before or after the image in your script. A common problem is blank spaces and line feeds being output caused by space and line feeds before or after the <?php and ?> tags. You need to remove all of these. And check any other PHP code loaded via include() or requre() for the same thing.
Related
Here my problem, I do a query to MySQL (PDO) for give me the last 5 URLs of a table nammed avatar who contains the ID and the URL :
$response = $dbh->query("SELECT url FROM avatar ORDER BY id_URL DESC LIMIT 0,5 ");
And I did :
while ($donnees = $response->fetch())
{
$urlImage = $donnees['url']; //'url' contains the URL
$result = file_get_contents($urlImage);
header('Content-Type: image/png');
echo $result;
?>
But the header just return a small empty white square. However, the "$result = file_get_contents($urlImage);" takes properly the URL because when I do :
$urlImage = $donnees['url']; //'url' contains the URL
$result = file_get_contents($urlImage);
echo $result;
?>
It just shows the "encodage of the image" (a ton of special characters) but not displays the image.
I also try with "imagick" but it says to me that the class doesn't exist and I don't think that the imagecreatefrompng can be use with URL.
Thanks !
Can you try this and see if it works?
$image = file_get_contents($donnees['url']);
$finfo = new finfo(FILEINFO_MIME_TYPE);
header('content-type: ' . $finfo->buffer($image));
echo $image;
This is suppose to handle one Image. One php script can return one image. If you want to combine the images and render a big long image then probably you should look at http://image.intervention.io/
EDIT
What I understood after trying out the above code is that if you put file_get_contents before header then the raw characters are shown. However you put it after header then everything seems to be working
$image="http://www.hillspet.com/HillsPetUS/v1/portal/en/us/cat-care/images/HP_PCC_md_0130_cat53.jpg";
$filename = basename($image);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
default:
}
header('Content-type: ' . $ctype);
$image = file_get_contents($image);
echo $image;
Working fiddle
If you're trying to use a dynamic image source where your url is the image source, and it isn't working, then the problem might be that there's a space or extra character somewhere on the page, which will make the browser treat it like a document instead of an image in some cases.
Your problem is that the browser isn't understanding that it's supposed to be an image.
You could always do:
<img src="<?=$urlImage?>">
Following code:
class FilesController extends Controller {
public function icon($fileId) {
$this->uses("FileAttachment");
$FA = new FileAttachment($fileId);
$fnth = $FA->path . 'th___' . $FA->filename;
$this->View->render = false;
if (file_exists($fnth)) {
$imageinfo = getimagesize($fnth);
switch ($imageinfo[2]) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($fnth);
Header("Content-type: image/jpg");
imagejpeg($image);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($fnth);
Header("Content-type: image/gif");
imagegif($image);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($fnth);
//Header("Content-type: image/png");
imagepng($image);
break;
case IMAGETYPE_BMP:
$image = imagecreatefromwbmp($fnth);
Header("Content-type: image/bmp");
imagewbmp($image);
break;
}
}
imagedestroy($image);
}
}
produces broken images. The image is shown in a browser just as a broken one. The file exists, otherwise there would come nothing. My Windows shows the pictures correctly. What can be the cause?
PS. If I remove Header, the browser displays the image's binary content, so it actually looks OK...
Your code is rather pointless - you're forcing PHP (and gd) to do a bunch of useless work to load up the file, decompress it into memory, and then recompress it for output.
Why not simply have:
$info = getimagesize($path_to_file);
header('Content-type: ' . $info['mime']);
readfile($path_to_file);
?
As for your code, check the entire output of the function. If there's ANY php warnings/errors being produced, they'd get embedded in the output and general cause "corrupt" images.
imagecreatefromgif(); //returns an image resource
Have you tried to add at the bottom ?
readfile($image); //reads a file and writes it to the output buffer.
I am creating image with php
code
$src = array ("22.jpg","33.jpg","44.jpg","55.jpg","66.jpg","77.jpg");
$imgBuf = array ();
foreach ($src as $link)
{
switch(substr ($link,strrpos ($link,".")+1))
{
case 'png':
$iTmp = imagecreatefrompng($link);
break;
case 'gif':
$iTmp = imagecreatefromgif($link);
break;
case 'jpeg':
case 'jpg':
$iTmp = imagecreatefromjpeg($link);
break;
}
array_push ($imgBuf,$iTmp);
}
$iOut = imagecreatetruecolor ("35","210") ;
imagecopy ($iOut,$imgBuf[0],0,0,0,0,imagesx($imgBuf[0]),imagesy($imgBuf[0]));
imagedestroy ($imgBuf[0]);
imagecopy ($iOut,$imgBuf[1],0,35,0,0,imagesx($imgBuf[1]),imagesy($imgBuf[1]));
imagedestroy ($imgBuf[1]);
imagecopy ($iOut,$imgBuf[2],0,70,0,0,imagesx($imgBuf[2]),imagesy($imgBuf[2]));
imagedestroy ($imgBuf[2]);
imagecopy ($iOut,$imgBuf[3],0,105,0,0,imagesx($imgBuf[3]),imagesy($imgBuf[3]));
imagedestroy ($imgBuf[3]);
imagecopy ($iOut,$imgBuf[4],0,140,0,0,imagesx($imgBuf[4]),imagesy($imgBuf[4]));
imagedestroy ($imgBuf[4]);
imagecopy ($iOut,$imgBuf[5],0,175,0,0,imagesx($imgBuf[5]),imagesy($imgBuf[5]));
imagedestroy ($imgBuf[5]);
imagepng($iOut);
//header ( 'Content-type:image/png' );
// save the img to directory
$char='0123456789';
$length=10;
$max_i=strlen($char)-1;
$value='';
for($j=0;$j<$length;$j++)
{
$value.=$char{mt_rand(0,$max_i)};
}
$imageid=$value;
it giving error on page like
‰PNG IHDR#ÒOuî² CIDATxœíÖ]ŒdÇUðÿ9§êÞþ˜™]ïìÇlbc‚ÀІ(#dQž
#"$ƒ”<°E‚XXY~ E D¼€"!ÂI’;Q$£°M¼ïzw½_3ÓÓÝ÷Ö×9<ô̬óÄRê§V«Õ·»ÿU]uÏ)JÙ
‚Ì€˜7€wâÕ½«¯^»Óçþå™åfȹ-š©
*6›çŸù¹÷ðêðÌ[í‰%üÈ]؆0‡8##ÙL3¼Än‘×ãÞ«·žxôñ»×69àôú©e?ÊóÙÊx™’W+Ü”˜C1Vö4Üîowq÷zwë?ýI·u§,É~#½™#PF¼Ž'>ô»ÇýÚ‘áÊòêÒh8Hëá¬
Œ,eïÄ9îK ¡Lº½4ëºÙüÖ7Óä¿ø—Ø–€‡(™€b’
»øعß\K÷o¾ãÌúI&*‚lÙÁR4P£ÄEÕ‰P¢ó!Î}ë:ëEdÄ-gX_.߸òòök¯ûŸúöߣMp~1'ç($àßo½-ÿÀÛï][Z/1Ëlo‡PaÕa#¥›{4Óɘ4—\Š9í%©FË'7ÓÕñÝîƒÅ_h¹#øNþÄû}ðØ?6NsLªêü0ö¡q%ö#fÖ2²Óbð’´¨ªjS¸,¾GE.ì\x~÷ùO>ûØ
x°"*¶ñ±|äÄÚ™ñʱÉv§Á4X‰¶·Óõ†S‹½€½Ž£QFècÅcŒ¡OH
ˆ²ÝˤϷws›ë›'è$þûòþ:931þkû¸-Z;1Ÿv%ôÐ’c
߸&Lûaëgq:Ó>Í•àÃñ`¼:;EŠÉHBL¸ºv<š¤É€†§†Ç¿õ¥¯ŸýÉì');¾ó·7ëÜ'
9ö¥ˆH\C–Çäß¼ùæ%Ýž #µs¦áéptU–}±lST°F:£#úãÏ}ù«g?HÊ Q<÷¥=5>–»b¢M¹uV
†½8»<»úûŸ{ooa€xmïÓ|üÈÚÀ›Ï}/
how i can solve this
What you're seeing is the actual content of the image that's generated. You do need to specify content/type, otherwise it will be assumed to be text/plain or text/html. Your image seem to be PNG, so
header("Content-type: image/png")
should be sufficient. I can see this line commented out - but it needs to be included. One note though: it needs to go before the actual image data is output, so you need to move it to the top of your script (or at least above imagephp call).
EDIT: If you want to save the resulting image into a file rather than output it to the browser, then you need to pass the second parameter to imagepng function:
imagepng($iOut, $myfilename)
See Imagephp documentation for more details
EDIT 2: If you need to get the content of the created image to use elsewhere, you can use this trick:
ob_start();
imagephp($iOut);
$image_data = ob_get_clean();
Now you got the resulting image data in a variable and you can continue with your script.
i know that
$localfile = $_FILES['media']['tmp_name'];
will get the image given that the POST method was used. I am trying to read an image which is in the same directory as my code. How do i read it and assign it to a variable like the one above?
The code you posted will not read the image data, but rather its filename. If you need to retrieve an image in the same directory, you can retrieve its contents with file_get_contents(), which can be used to directly output it to the browser:
$im = file_get_contents("./image.jpeg");
header("Content-type: image/jpeg");
echo $im;
Otherwise, you can use the GD library to read in the image data for further image processing:
$im = imagecreatefromjpeg("./image.jpeg");
if ($im) {
// do other stuff...
// Output the result
header("Content-type: image/jpeg");
imagejpeg($im);
}
Finally, if you don't know the filename of the image you need (though if it's in the same location as your code, you should), you can use a glob() to find all the jpegs, for example:
$jpegs = glob("./*.jpg");
foreach ($jpegs as $jpg) {
// print the filename
echo $jpg;
}
If you want to read an image and then render it as an image
$image="path-to-your-image"; //this can also be a url
$filename = basename($image);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
default:
}
header('Content-type: ' . $ctype);
$image = file_get_contents($image);
echo $image;
If your path is a url, and it is using https:// protocol then you might want to change the protocol to http
Working fiddle
My problem is when you use for exemple :
<img src="/img.jpg" />
the src has to be an image and the image has to be accessible to the person. I want to be able to control the access to those image (if the user is logged for example). IF the person has not access to the image, he can't access it. My script that controls the access to an image is a php file.
I know .htaccess can limit access to ressources, but I need to valid in the php file. Is there a way to do this or to load the image with javascript (using ajax request) and changing the source of the image to the location of the image in the temp folder?
Your image source doesn't necessarily have to point to the real image, neither does it have to be an image:
<img src="images.php?f=img.jpg" />
Then you can write a PHP script which does the required validations and return the image afterwards through the script
$image = basename($_GET['f']);
if (user_has_access()) {
// You have to determine / send the appropriate MIME-type manually
header('content-type: image/jpg');
readfile($image);
} else {
header('HTTP/1.1 403 Forbidden');
}
$image = basename($_GET['image']);
if (validation()) {
header('Content-type: image/jpeg');
readfile($image);
} else {
header('HTTP/1.1 403 Forbidden');
}
basename is mandatory, of a hacker will have every password stored on your server.
correct content type
sane memory consumption
<img src="/image.php?id=myImage.jpg">
And myImage.jpg:
<?php
$imageName = $_GET['id'];
$ctype="image/jpg";
$extension = substring($imageName, strstr($imageName, '.'));
switch($extension) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
}
if (someValidation_here) {
header("Content-Type: $ctype");
$handle = fopen($imageName, "rb");
echo fread($handle, filesize($imageName));
fclose($handle);
}
?>
Serve your images with PHP
You can limit access using with PHP, if the PHP is outputting the image contents.
By using the src tag http://www.example.com, you are not using PHP, your web server is serving up the image on its own.
To output an image with PHP, make sure you set your header variable appropriately.
For example:
<?php
if($user->isAuthenticated())
{
$image = imagecreatefromjpeg ($server_image_path);
header('Content-Type: image/jpeg');
imagejpeg($image, NULL, 75);
imagedestroy($image);
}
else
{
header('HTTP/1.1 403 Forbidden');
}
?>
You can do this with PHP ... see imagejpeg for an example ... you then have the img as follows :
<img src="/myfile.php" />
or use your PHP file to grab an image and output it using :
header('Content-Type: image/jpg');
echo file_get_contents("yourimage.jpg");
You can ceep user_login_status in your $_SESSION, and on a view part check it
<?if ($_SESSION['user_status'] == 'login'){?>
<img src="/img.jpg" />
<?}else{?>
// some stuff instead of <img/>
<?}?>