Image display using php without affecting the html code - php

I have a question about the images displaying using a function getImage_w($image,$dst_w), which takes the image URL ($image) and the destination width for this image ($size). Then it re-draws the image changing its height according to the destination width.
That's the function (in libs/image.php file):
function getImage_w($image,$w){
/*** get The extension of the image****/
$ext= strrchr($image, ".");
/***check if the extesion is a jpeg***/
if (strtolower($ext)=='.jpg' || strtolower($ext)=='.jpeg'){
/***send the headers****/
header('Content-type: image/jpeg');
/**get the source image***/
$src_im_jpg=imagecreatefromjpeg($image);
/****get the source image size***/
$size=getimagesize($image);
$src_w=$size[0];
$src_h=$size[1];
/****calculate the distination height based on the destination width****/
$dst_w=$w;
$dst_h=round(($dst_w/$src_w)*$src_h);
$dst_im=imagecreatetruecolor($dst_w,$dst_h);
/**** create a jpeg image with the new dimensions***/
imagecopyresampled($dst_im,$src_im_jpg,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
imagejpeg($dst_im);
}
In a file imagetest.php I have this code portion:
<?php
require 'libs/image.php';
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'">
';
In the past, I used to write the URL with $_GET paramers defining the image. But now , I want to use the function directly in my code.
The problem is that the image is displaying correctly, but the Hello World HTML code is not translated by the browser (I know that the header are already sent by the first code) But I want to know how to display the image correctly without affecting the html code. and also without using get parameters that change the URL of the image to this undesired form :
libs/image.php?image=http://www.example.com/image&width=200

After my earlier, totally wrong answer, I hope to make up for it with this. Try this code:
<?php
function getImage_w($image,$w){
// Get the extension of the file
$file = explode('.',basename($image));
$ext = array_pop($file);
// These operations are the same regardless of file-type
$size = getimagesize($image);
$src_w = $size[0];
$src_h = $size[1];
$dst_w = $w;
$dst_h = round(($dst_w/$src_w)*$src_h);
$dst_im = imagecreatetruecolor($dst_w,$dst_h);
// These operations are file-type specific
switch (strtolower($ext)) {
case 'jpg': case 'jpeg':
$ctype = 'image/jpeg';;
$src_im = imagecreatefromjpeg($image);
$outfunc = 'imagejpeg';
break;
case 'png':
$ctype = 'image/png';;
$src_im = imagecreatefrompng($image);
$outfunc = 'imagepng';
break;
case 'gif':
$ctype = 'image/gif';;
$src_im = imagecreatefromgif($image);
$outfunc = 'imagegif';
break;
}
// Do the resample
imagecopyresampled($dst_im,$src_im,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
// Get the image data into a base64_encoded string
ob_start();
$outfunc($dst_im);
$imgdata = base64_encode(ob_get_contents()); // Don't use ob_get_clean() in case we're ever running on some ancient PHP build
ob_end_clean();
// Return the data so it can be used inline in HTML
return "data:$ctype;base64,$imgdata";
}
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.getImage_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'" />
';
?>

This basically is not possible. The webbrowser requests the HTML page and expects HTML. Or it requests an image and expects an image. You cannot mix both in one request, just because only one Content-Type can be valid.
However, you can embed the image in HTML using data URI:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4/8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Be aware that the base64 encoding is quite ineffective, so make sure you definitly compress your output, if the browser supports it, using for example gzip.
So for you it likely looks like the following:
echo '<img src="data:image/jpeg;base64,' . base64_encode(displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200)) . '">';
And make sure displayimg_w() does not output a header anymore.
Furthermore, displayimg_w() needs to be adjusted at the end to return the image data as string rather than direct output:
ob_start();
imagejpeg($dst_im);
return ob_get_flush();

Related

PHP - Read an image with URL

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?>">

Convert base64 to image resize and encode in php

I am using html5 file api to preview a image in browser and then saving it to database as base64 string using ajax.
I need to reduce the quality in order to resize the image.
<?php
$img = $_POST['img'];
$i = explode(",",$img);
$img = $i[1];
$img = imagecreatefromstring[$img];
$rimg = imagejpeg($img,XXXXXXX, 60);
?>
xxx=> how could I turned it back to base64?
thanks in advance.
From http://php.net/manual/en/function.imagejpeg.php
/*
* imageXXX() only has two options, save as a file, or send to the browser.
* It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
* So I start the output buffering, use imageXXX() to output the data stream to the browser,
* get the contents of the stream, and use clean to silently discard the buffered contents.
*/
ob_start();
switch ($image_type)
{
case 1: imagegif($tmp); break;
case 2: imagejpeg($tmp, NULL, 100); break; // best quality
case 3: imagepng($tmp, NULL, 0); break; // no compression
default: echo ''; break;
}
$final_image = ob_get_contents();
ob_end_clean();
return $final_image;
or save to the file, then load the file as binary stream, base 64 the binary and delete the file

Transform .jpg, .jpeg or .gif to .png without saving them on machine

Is it possible to transform a .jpg, .jpeg or .gif image to .png in php without saving the image in your computer?
Something like:
function read_image($filename, $extension) {
switch($extension) {
case '.png':
$image = imagecreatefrompng($filename);
break;
case '.jpg': case '.jpeg':
$unTransformed = imagecreatefromjpeg($filename);
$image = transform($unTransformed);
break;
case '.gif':
$unTransformed = imagecreatefromgif($filename);
$image = transform($unTransformed);
break;
return $image;
}
}
function transform($unTransformed) {
// Some magic here without actually saving the image to your machine when transforming
return $transformed;
}
I honestly couldn't find an answer for this. Also note that GD is mandatory.
Using output buffering and capturing the output of imagepng should work, like this:
function transform($unTransformed) {
ob_start();
imagepng($unTransformed);
$transformed = ob_get_clean();
return $transformed;
}
Of course, this is assuming you actually want a variable containing a png bytestream of your image file. If the only purpose is to output it anyways, don't bother and do as Marty McVry suggests.
Directly from the PHP manual: (imagepng()-function, which outputs a PNG image to either the browser or a file)
header('Content-Type: image/png');
$transformed = imagepng($untransformed);
You might encounter a problem sending the headers along, so it's possibly necessary to output the headers somewhere else or transform the stream created by imagepng to a base64-string and display the image like that, depending on the rest of your code.

How to create image in php

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.

How to read an image with PHP?

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

Categories