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.
Related
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.
I have one protocol that recieve id and send picture back.Now I have question how can I send just create .gif ?? Here please take a look to my code
if($id!="")
{
........
$ext = substr( $picturename, strrpos($picturename, '.')+1 );
switch($ext)
{
case 'jpg':
$ext = 'jpeg';
break;
case 'jpeg':
$ext = 'jpeg';
break;
case 'png':
$ext = 'png';
break;
case 'gif':
$ext = 'gif';
break;
}
header('Content-Description: File Transfer');
header('Content-Type: image/'.$ext);
$file = "./images/".$picturename;
readfile($file);
//this work
}
else
{
// Create a 1x1 image
$im = imagecreatetruecolor(55, 30);
$trans = imagecolorallocate($im, 0, 0, 0);
// Make the background transparent
imagecolortransparent($im, $trans);
header('HTTP/1.1 403 Forbidden');
//How can I send .gif back with header ??
}
You can set multiple headers and output an image in the same manner. Attached is the code to generate a 1x1 pixel.
....
header('HTTP/1.1 403 Forbidden');
header('Content-Type: image/gif');
// output a 1x1 pixel
echo base64_decode("R0lGODdhAQABAIAAAPxqbAAAACwAAAAAAQABAAACAkQBADs=");
Just output imagegif($im);. Setting the 403 header doesn't do anything special, so you can output the image and that's what will be received.
If you don't need to dynamically include anything in the image (like text for example) you could just have a default 1x1 image that you return instead of using imagecreate function...?
As far as the 403 header, though, I'm not sure if browsers will probably display an image if it thinks it was an error response from the server - so you might get broken images.
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
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();
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.