search for in the  
<imageistruecolorimagelayereffect>
Last updated: Thu, 19 May 2005

imagejpeg

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagejpeg -- Output image to browser or file

Description

bool imagejpeg ( resource image [, string filename [, int quality]] )

imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See also imagepng(), imagegif(), imagewbmp(), imageinterlace() and imagetypes().



User Contributed Notes
imagejpeg
wojteksw at go2 dot pl
03-Apr-2005 05:37
I have changed one line in the script of Kokesh
25-Jun-2004 06:42 listed above, and now it generates better quality thumbnails.
You have to change function imagecopyresized() to imagecopyresampled()
nerdgirl at HATE_SPAMnerdgirl dot dk
27-Feb-2005 02:31
Here is an example of uploading an image, changing its size (width/height) and saving it to a new file. It uses ftp to upload both the original and the resized image. This is usefull in situations where ftp is your only option.

It took me a while to figure it out, so I hope this will save someone else a lot of time :-)

The following assumes that the image is uploaded from a form with a filefield called 'gfx'. I have left out all error checking to keep it simple, so remember to modify the code, to suit your needs.

<?php
$new_width
= 100;
$new_height = 200;
$tmp_image=imagecreatefromjpeg($_FILES['gfx']['tmp_name']);
$width = imagesx($tmp_image);
$height = imagesy($tmp_image);
$new_image = imagecreatetruecolor($new_width,$new_height);
ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
//Grab new image
ob_start();
ImageJPEG($new_image);
$image_buffer = ob_get_contents();
ob_end_clean();
ImageDestroy($new_image);
//Create temporary file and write to it
$fp = tmpfile();
fwrite($fp, $image_buffer)) {
rewind($fp);
//Upload new image
$conn_id = ftp_connect('ftp.example.tld');
ftp_login($conn_id,'user','pass');
ftp_fput($conn_id,'path/to/new/file.jpg', $fp, FTP_BINARY);
fclose($fp);
?>
r dot duclos at chello dot fr
11-Feb-2005 08:41
Hy, here is a little code for generate a thumbnail, very good quality. Enjoy it !

<?php

function miniature($pict, $dest_pict){
  
  
$handle = @imagecreatefromjpeg($pict);

  
$x=imagesx($handle);
  
$y=imagesy($handle);
                                                  
       if(
$x > $y){                               
              
$max = $x;                         
              
$min = $y;                         
       }                                         
       if(
$x <= $y){                               
              
$max = $y;                         
              
$min = $x;                         
       }                                       

//$size_in_pixel : Size max of the label in pixel.  The size of the picture being
//proportional to the original, this value define maximum size
//of largest side with dimensions of the picture. Sorry for my english !

//Here $size_in_pixel = 100 for a thumbnail.
      
$size_in_pixel = '100';

      
$rate = $max/$size_in_pixel;
      
$final_x = $x/$rate;
      
$final_y = $y/$rate;

       if(
$final_x > $x) {
              
$final_x = $x;
              
$final_y = $y;
       }

      
$final_x = ceil($final_x);
      
$final_y = ceil($final_y);

      
$black_picture = imageCreatetruecolor($final_x,$final_y);
      
imagefill($black_picture,0,0,imagecolorallocate($black_picture, 255, 255, 255));
      
imagecopyresampled($black_picture, $handle, 0, 0, 0, 0,$final_x, $final_y, $x, $y);

       if(!@
imagejpeg($black_picture,$dest_pict.'/mini_'.$pict, $size_in_pixel))
      
imagestring($black_picture, 1, $final_x-4, $final_y-8, ".", imagecolorallocate($black_picture,0,0,0));
                      
      
//The number is the quality of the result picture
      
imagejpeg($black_picture,'', '100');
      
imagedestroy($handle);
      
imagedestroy($black_picture);
   }
  
$pict = "PICT7024.jpg";
$dest_pict = "D:/Program Files/EasyPHP1-7/www/test";
miniature($pict, $dest_pict);

?>
arjini at gmail dot com
12-Sep-2004 06:20
Scenario:
   When pointing your browser directly at a script outputting an image, it displays without problem, but when using it in another page via html (i.e. : img src="x.php?yada=yada" ), you get a broken image.

Reason:
   *Any* extra data sent along with the image will cause it to not display on other pages. Extra data may include, whitespace characters (check the begginings and ends of your files), or a call to session_start(), which is what got me.

Summary:
   If you're going to send an image DONT START A SESSION in the script that is outputting the image, and make sure that the PHP delimiters are the first and last things in your file.
10-Sep-2004 10:40
For best results, use only loss-less file formats (such as PNG) for storing images or image parts that you later intend to output with this function.
arjini at gmail dot com
07-Sep-2004 08:48
Converting a directory of PNG images into jpegs is as easy as:

<?php
   $d
= dir('./');
   while(
false !== ($e = $d->read())){
       if(
strpos($e,'.png')){
          
$r = imagecreatefrompng('./'.$e);
          
imagejpeg($r,str_replace('.png','.jpg',$e),75);
       }
   }
?>

Don't let anybody convince you otherwise. Put that in the folder that the images are in and run it. I tried for 2 hours to get photoshop to do it, to no avail. PHP to the rescue!
Olav Alexander Mjelde
07-Jul-2004 07:31
Note to steve:
yes, this is true.. I simply forgot to think about that issue with the clear text to the script..

I think the easiest way to "fix" it, would be to replace the @ in the string with something which cant be used in an email adress..

Then the script would do a replace of excisting of that character..

abc@123.com would then be abc*123.com, which the script would parse back into abc@123.com
Steve
26-Jun-2004 08:14
Regarding Olav's attempt at avoiding spambots, the code will produce a string of code like requests.php?string=<email_address>, and most spambots will parse that email address right out.  You should either create static php scripts to output specific addresses, or do something like save a temporary file on the server with the address you want, and either pass the filename to the makeimage script or have the script open a specific file to check.  If you put the address anywhere on the page the spambot will parse it out, including a tag like href="mailto:xxx".  That's why people use forms to send email now.
Kokesh
25-Jun-2004 11:42
Here is the simple, but powerful script for creating thumbnails on the fly.
You can include the script
directly to www page - just put it in <img src= tag.
with width 150pix.
This resizer respects the ASPECT RATIO.
Here is the script:
<?php
// Use it this way: resize.php?pic=imageurl&width=width_in_pixels
// kokesh@kokeshnet.com 2004
  
header("Content-type: image/jpeg");
  
$im    = imagecreatefromjpeg($pic);
  
$orange = imagecolorallocate($im, 220, 210, 60);
  
$px    = (imagesx($im) - 7.5 * strlen($string)) / 2;

  
$old_x=imageSX($im);
  
$old_y=imageSY($im);

  
$new_w=(int)($width);
   if ((
$new_w<=0) or ($new_w>$old_x)) {
    
$new_w=$old_x;
   }

  
$new_h=($old_x*($new_w/$old_x));

   if (
$old_x > $old_y) {
      
$thumb_w=$new_w;
      
$thumb_h=$old_y*($new_h/$old_x);

   }
   if (
$old_x < $old_y) {
      
$thumb_w=$old_x*($new_w/$old_y);
      
$thumb_h=$new_h;
   }
   if (
$old_x == $old_y) {
      
$thumb_w=$new_w;
      
$thumb_h=$new_h;
   }
    
$thumb=ImageCreateTrueColor($thumb_w,$thumb_h);
    
imagecopyresized($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

  
imagejpeg($thumb,"",90);
  
imagedestroy($thumb);
?>
rich @ richud dot com
24-Jun-2004 03:49
'quality' must be a whole number however if a mixed number is given it only uses whole part, e.g. a given value of 90.987 results in 90 being used.
Tom Davis
08-Jun-2004 05:49
I came across a problem where Internet Explorer refused to cache some dynamically created images. To get round this, send out a Last-Modified header.

Eg:

<?php

header
('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT');
header('Content-Type: image/jpeg');
imagejpeg($photo);

?>
25-May-2004 01:42
A word of warning when outputting images to the browser...

Make sure there is no extra spaces around the <?php ?> tags, in the file you are editing, and also any included files.

I began to think there was a bug in GD or something, and I checked the file I was working on, but forgot about the includes...

Hours gone..
stick [at] geek [dot] hu
23-May-2004 06:08
Just a note to Olav Alexander Mjelde's code: don't forget to put an
imagedestroy($im);
at the end of it or you can run into memory problems.
jannehonkonen at hotmail dot com
05-May-2004 12:44
I had problem wanting to insert stealth - copyrights into images. I could have done this easily with fopen and such, but I still wanted to use imagejpeg(); and it's quality feature. Well this is one kind of solution what I discovered, and seems to work fine.

--code--
$filename = "http://www.domain.com/something.jpg";
$im = imagecreatefromjpeg($filename);
imagejpeg($im,$ModImg,65);
$ModImg .= "This is the text added after EOF of the jpeg";
echo $ModImg;
--code--

As imagejpeg(); inserts imagedata into $ModImg, it does not show the image, but it seems to send headers in that point, so header(); is not needed before echoing variable. Text is viewable with Hex-editors etc.
Olav Alexander Mjelde
07-Apr-2004 08:24
Some people have never heard of spambots, searching the net for email adresses.
How do you avoid this?
Some people write emails like: olav-x AT volvo-power.net (mine btw),
but this will confuse "stupid" users.
The optimal sollution is to have an image with your email adress on.

* When using this function,
you have to put it in a non-html php file..
eg. I put it in a makeimage.php file.
so, how do you display it?

In your users.php, put this:

echo "<b>Email:</b>&nbsp;
       <img src=\"/sql/phpPictures/makeimage.php
         ?string={$row['email']}\">";

Below is the makeimage.php (working example)

<?php
header
("Content-type: image/jpg");
if (!isset(
$string))
  { 
  
$string = "Missing data";
  }

$font  = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);
          
$im = @imagecreate ($width,$height);
//white background
$background_color = imagecolorallocate
                
($im, 255, 255, 255);
//black text
$text_color = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $font, 0, 0$string, $text_color);

imagejpeg ($im);
?>

Enjoy..
php at andy-pearce dot com
19-Feb-2004 02:42
This might be too obvious, but perhaps worth pointing out. If you want to simply serve images without altering them, it's presumably more efficient to use something like the following:

<?php
  
// Normally $filename would depend on $_GET, etc.
  
$filename = '/photoalbum/images/test.jpg';
  
header('Content-type: image/jpeg');
  
header('Content-transfer-encoding: binary');
  
header('Content-length: '.filesize($filename));
  
readfile($filename);
?>

That way you avoid the overhead of reading and parsing the image, you simply send it directly to the browser.

This is particularly useful if you're using PHP to implement access controls, because it allows you to redirect files from areas of the filesystem browsers can't normally access (although the filename should always come from your script if possible, and not from a URL field, to prevent subverting it with URLs such as image.php?../../../etc/passwd).
gzink at zinkconsulting dot com
01-Jan-2004 05:17
Don't forget that JPEG compression has artifacts! And they're not all really obvious. The PHP JPEG compression is pretty decent, but it seems to generally:

-Lighten the image overall, by a reasonable amount (never seen this before, but it will drive graphic designers crazy, you might want to darken the image before compressing it)
-Reduce saturation, especially with images with lots of points of different color within a few pixels of each other (this is a documented feature of JPEG)
-Seriously mess with blue colors, which is common to all JPEG but really annoying in some situations with blue and black or other detailed blue parts

You might want to consider using imagepng() and outputting a PNG image instead of a JPEG if any of the above affect you, or your image is not very photo-like. Sometimes I have an algorithm compare JPEG to PNG for an image and send the smaller version to the user.

Also, when using imagepng(), you should use imageinterlace() before it 95% of the time. Interlaced JPEGs load progressively, improving in quality as the image loads, so users on slower connections see the whole image at low quality. All this happens without affecting the file size (actually, sometimes the file size is smaller!) or final quality.

Hope this helps a few people out. It's not all that obvious without lots of playing around.

-Galen
http://zinkconsulting.com/
chris AT NOSPAM sketchdiary DOT com
24-Sep-2003 06:20
Just a reminder, if you're passing a string of text via GET, you should rawurlencode() or urlencode() them.  Some older browsers (such as Netscape 4.x) have issues regarding spaces in the URL.

NS 4 shows a broken image:
<image src="newimage.php?text=Show me the text!">

Makes all browsers happy:
<image src="newimage.php?text=<? echo urlencode('Show me the text!'); ?>">

Better to be safe than sorry...
irishcybernerd at email dot com
29-May-2003 12:33
Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.

   //Start buffering the output stream
   ob_start();

   // output the image as a file to the output stream
   Imagejpeg($im);
  
   //Read the output buffer
   $buffer = ob_get_contents();

   //clear the buffer
   ob_end_clean();

   //use $buffer as you wish...
jt at tsw dot org dot uk
24-Feb-2003 09:39
I've just read all this AFTER solving the problem in my own little way. (this is re dumping the image into a string)

Im not actually saving the file to a database, but I'm passing it over XML:RPC so I have the constraint that I cant just dump it to browser, and also its not binary safe.. my solution does not involve ob_start(); which might arguably be the more elgant solution. I didnt see my solution listed, so I thought I aught to post it to add to the wealth of knowledge:

[apologies if this is incorrect, im snipping from a large bit of irrelevent XML:RPC catching stuff]

$tmpfname = tempnam ("/tmp", "FOO");      // Generate the temp file

Imagejpeg($im,$tmpfname);                        // save me image to the file

$temp = fopen($tmpfname,"rb");                  // <- Open the file for reading binary
  
$buffer = fread($temp,filesize($tmpfname));  // get that data into the buffer
fclose($temp);                                            // close the file
unlink($tmpfname);                                    // finished with the file, discard

$out = base64_encode($buffer);                  // encode it (not nessicary if you are using some kind of binary safe function with the info)

and of course on the other end of whatever your doing,

[ some function to get $in ]

header("Content-type: image/jpeg");
$in = base64_decode($buffer);          // get the binary data back
echo $in;

This should work with things like Imagepng

Hope that helps anyone out.
crazyted at crazyted dot com
19-Feb-2003 11:51
In regards to adding images (or any other binary file) to a database, unless you absolutely *have* to, a MUCH better solution is to simply save the file you create to a directory and update your database with a URL to this file.

When I first started DB development I was hung up with BLOBs and how to make them effectively work with PHP but realized that they can severely impact performance and you also limit what you can do with those files once they're inside the DB.

If you can avoid using BLOBs, and most people can, then by all means just create a look-up table for your file urls and save them to a directory to store the files. File access and scalability will be greatly increased in most cases.
dominik at deobald dot org
26-Dec-2002 09:27
About dwards's note: If you choose to send an image to the user directly and don't want to have "strange characters", you have to set the mime-type of the result the user is going to receive:

header('Content-Type: image/jpeg');
imagejpeg($img);
dward at outeru dot comewithnospam
19-Jul-2002 07:57
It took me quite a while to figure out how to output dynamic images along with html with my php scripts.

I may be dim but I'm sure I'm not the only one. So here it is if you need it.

Instead of sending the image directly to the browser, which ends up looking like a bunch of garbage to most users, send an IMG tag with the SRC attribute set to your PHP script that creates the image.

echo '<IMG SRC="makeimg.php?args=YourMakeImgArgs">';
dklein at gmx dot de
11-Dec-2001 10:52
Looks like any specified resolution settings in a JPEG file get lost when using imageJPEG() function in a script.
I had a high resolution JPEG which i added text to with imagestringup() so my customer can print the emailed JPEG as a filled form, but printing both Graphics from Photoshop revealed that any JPEG created is downsampled to 72 dpi, while width and height is kept.
(72 dpi is the standard web resolution)
Nothing to wonder about, but maybe if you read this you dont need to scratch your head :)
pingling at idea dot net dot pl
23-Oct-2001 06:27
As the GD 1.8.4 manual says, the quality should be a value in the range 0-95. And this seems to be true - setting it to 100 doesn't change the default quality.
godehardt at hotmail dot com
03-Jul-2001 02:28
If you call imagecreatefromjpeg and load a jpeg with 75% quality and output it with imagejpeg u can specify the new quality for e.g. 90% and u can increase quality, but output will look like 75% quality picture with the only difference that the new pic is bigger.

So u should check the source quality before u alter output quality. In most cases a quality of 75% is sufficient. For previews i use 50%.

But i make a check if source quality is lower than my personal output quality, i will not chance source quality !

Hope that helps your Webserver and keeps the traffic low :-)
fuxun at sina dot com
15-Jul-2000 06:03
For example:
<?
Header
("Content-type: image/jpeg");
$im = imagecreatefromjpeg("./test.jpg");
Imagejpeg($im,'',20);
ImageDestroy($im);
?>
the jpeg quality from 0 to 100

<imageistruecolorimagelayereffect>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT