Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Image Functions : imagejpeg


Output image to browser or file (PHP 4, PHP 5)
bool imagejpeg ( resource image [, string filename [, int quality]] )

imagejpeg() creates a JPEG file from the given image.



An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().


The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

To skip this argument in order to provide the quality parameter, use NULL.


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).

Return Values

Returns TRUE on success or FALSE on failure.



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


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

Related Examples ( Source code ) » imagejpeg

Code Examples / Notes » imagejpeg

darren kulp kulp

With regard to chris.calo's code:
// The following block retrieves the source file.  It assumes the filename extensions match the file's format.
  if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
  if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
... etc.
It assumes more than that, namely that the filename does not contain the strings '.gif', '.jpg', '.jpeg', '.bmp', or '.png' *anywhere* in the string. Some valid files with special filenames could break this; for example, a file named "" would cause this script to attempt to load the file as a PNG. Obviously this is a rare case, but the issue could be easily avoided by using "else ifs" (uses less CPU time) or checking that the extension abuts the end of the string or both.
That said, the whole business could be avoided if PHP didn't clutter the namespace with different functions to do the same thing with different image formats. Ick.


When displaying an image using imagepng or imagejpeg, you may want/need to call "header("Content-type: image/jpeg")" before the imagepng and imagejpeg functions.
It appears that some servers/browers are striping out the default header so the image is not rendered and appears as raw data.
(Firefox 1.02+ and OSX Safari for example)

15-feb-2006 03:44

Hope someone will find this usefull... save it to thumb.php and use it for on-the-fly thumbnails generating
<img src= "thumb.php?src=pic.jpg&wmax=150&hmax=100&quality=90&bgcol=FF0000"> </img>
// by
// proportional on-the-fly thumb generator from JPG images
// usage example:
// <img src= "thumb.php?src=pic.jpg&wmax=150&hmax=100&quality=90&bgcol=FF0000"> </img>
// parameters:  src = source image
//              wmax = max width
//              hmax = max height
//              quality = JPG quality of generated thumb - optional.
//                        if not specified, quality=90
//              bgcol = if specified, allways generates exact wmax x hmax sized thumb,
//                      with bacground color bgcol and centered source image
// note: if source image is smaller than desired thumbnail, it will not be resized!
header("Content-type: image/jpeg");
$source = imagecreatefromjpeg($src);

if ($orig_w>$wmax || $orig_h>$hmax)
if ($thumb_w/$orig_w*$orig_h>$thumb_h)
} else
if (!@$bgcol)
if (!@$quality) $quality=90;


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:
   // 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));
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).


This is a function that I had developed for a CMS.  The idea is that it runs from an upload form. The user uploads a hi-res image, which is copied to the server, a low res one is created (half the width/height of hi res) and a thumbnail is created.
The image is resized matching the smallest side of the image to the thumbnail size (in this example it is 70px).  The other side is then resized proportionally (which will end up being more than 70px) and cropped and centered so that it too is 70px.
There is a mixture of imagecopyresized and imagecopyresampled, i have chosen the ones that work best in this situation but imagecopyresampled gives a much nicer image.
Hope this helps someone.
$dest_hires = "../images/artistsphotos/".$imageName."h.jpg";
$dest_lowres = "../images/artistsphotos/".$imageName."l.jpg";
$dest_thumbnail = "../images/artistsphotos/".$imageName."i.jpg";
/*upload full size image to site - if it is hi res we do not want to manipulate it
want to leave all qualit in tact.*/
$ims = getimagesize($dest_hires); //now we have dimensions of original image...

/******creating lower res image******/
$newwidth=ceil($ims[0]/2);//half the width of original file - use ceil() to avoid decimals.
$newheight=ceil($ims[1]/2);//half the height

$img = imagecreatetruecolor($newwidth,$newheight); //low res img - always use truecolor to prevent any 'wierd' colour effects.
$org_img = imagecreatefromjpeg($dest_hires); //load in hi res

imagecopyresized($img, $org_img, 0, 0, 0, 0, $newwidth, $newheight, $ims[0], $ims[1]);
imagejpeg($img,$dest_lowres,80);//save to file low res img.

/******creating thumbnail******/
//see which is bigger, x or y axis, then resize smaller side to 70.
//$resizewidth is the temporary width of the thumbnail, it is in fact the width when it has been resized
//using the apect ration and before cropping, at this stage the thumb will not be 70px X 70px
//unless it is a square. Same applies to height ($resizeheight).
//$thumbx and $thumby are the positions of the cropping are for thumbnail, these are calculated
//so that the cropped image is centered.

if ($ims[0]>$ims[1])
{//then the width is bigger
$aspectRatio = $ims[1]/70;


$thumbx=ceil(($resizewidth - $thumbwidth)/2);
else if ($ims[0]<$ims[1])
{//then the height is bigger
$aspectRatio = $ims[0]/70;


$thumby=ceil(($resizeheight - $thumbheight)/2);
else if ($ims[0]==$ims[1])
{//then we have a perfect square.

$img = imagecreatetruecolor($resizewidth,$resizeheight);
$org_img = imagecreatefromjpeg($dest_lowres);

//this is the almost thumbnail sized image with everything resized to ratio
imagecopyresampled($img, $org_img, 0, 0, 0, 0, $resizewidth, $resizeheight, $newwidth, $newheight);
$img2 = imagecreatetruecolor($thumbwidth,$thumbheight);
//this is the thumbnail image, where the above is cropped.
imagecopyresized($img2, $img, 0, 0, $thumbx, $thumby, $resizewidth, $resizeheight, $resizewidth, $resizeheight);

08-feb-2006 06:21

This extension allows to save frames from movie files as jpeg.


The behaviour of not being allowed to write the file is based on a change in latest release, see
- Added missing safe_mode checks for image* functions and cURL.
- ...
Some people (including me) consider this new behaviour as broken, see also - please vote for/against the bug if you feel same/different.
Workaround is e.g. a touch($filename); before the imagejpeg($im,$filename);

chris dot calo

Thanks to Stuart and Darren for the corrections to the create_thumbnail function.  Another note on that function: imagecreatefromwbmp was incorrectly used.  WBMPs are wireless bitmaps, not windows bitmaps (thanks to clambert at whitecrown), so the thumbnail routine as is will not be able to handle windows bitmaps.  See the notes at for tips on working with windows bitmaps.


Thanks to Chris dot Calo for the thumbnail snippet.  The file type issue is easily resolved by getting the type from the file with getimagesize, and you can handle unsupported types at that stage too.  Thus:
  list($img_width,$img_height, $type) = getimagesize($source_file); // Get the original dimentions
  if ($type != 1 && $type != 2 && $type != 3 && $type != 15) { die("Your file is not a supported format"); }
...and then later check the type again to open the image correctly:
  if ( $type == 1 ) { $img_source = imagecreatefromgif($source_file); }
  else if ( $type == 2 ) { $img_source = imagecreatefromjpeg($source_file); }
  else if ( $type == 3 ) { $img_source = imagecreatefrompng($source_file); }
  else if ( $type == 15 ) { $img_source = imagecreatefromwbmp($source_file); }

olav alexander mjelde

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 (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
Below is the makeimage.php (working example)
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);

kenneth keiter

So.. after messing around with this beast of a function for hours, I discovered that it DOES NOT preserve the resource it is using the create the image, nor do imagepng() or imagegif(). By this I mean that you can not run two imagejpeg(), imagepng() or imagegif() calls on the same resource. Another possibly undocumented quirk... :-(


   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.
   *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.
   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.

john luetke

Rewrote the manual example into this function for creating a thumbnail image:
function thumbnail_jpeg ($original, $thumbnail, $width, $height, $quality) {
 list($width_orig, $height_orig) = getimagesize($original);
 if ($width && ($width_orig < $height_orig)) {
   $width = ($height / $height_orig) * $width_orig;
else {
   $height = ($width / $width_orig) * $height_orig;
 $image_p = imagecreatetruecolor($width, $height);
 $image = imagecreatefromjpeg($originial);
 imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
 imagejpeg($image_p, $thumbnail, $quality);


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.

your dot sheepy

Regarding Carl Gieringer's comment, it is possible to have PHP files in utf-8.  Just make sure the editor does not output BOM, which is unnecessary in utf-8 anyway.
Except for any editors from Microsoft, most programmer's editors that supports utf allows you to surpress BOM.


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
// output the image as a file to the output stream

//Read the output buffer
$buffer = ob_get_contents();
//clear the buffer
//use $buffer as you wish...


Please note that there is a bug report open for the currently broken safe_mode behaviour on this function:
According to the PHP staffer who has responded the docs are wrong (I don't agree but I'm also not their employee).  
The work around is to use touch() (or any other file system function that can do this) to create the file first before using imagejpeg().

olav alexander mjelde

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.. would then be abc*, which the script would parse back into


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 :)


Just wanted to mention that the create_thumbnail script below fails on uppercase filenames. Many cameras default to IMG_XX.JPG and since strpos is case sensitive it fails.
I changed all the strpos to stripos and it worked wonderfully.


Just incase its confusing, i forgot to add
to the top of the script below!


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...


Just a note to Olav Alexander Mjelde's code: don't forget to put an
at the end of it or you can run into memory problems.


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


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.


in addition to my THUMBNAIL GENERATOR script:
i forgot to say, src path must not be http:// but server path (e.g. for some linux server: src=/home/users/user1/public_html/images/image1.jpg) or relative path, as in example in script (src=test.jpg, src=../test.jpg, src=pictures/test.jpg...)

bram van dam

If you wish to capture the jpg data into a variable, rather than outputting it or saving it into a file (perhaps so you can put it in a database), you might want to consider output buffering. Something along these lines should work:
ob_start(); // start a new output buffer
imagejpeg( $newimage, NULL, 100 );
$ImageData = ob_get_contents();
ob_end_clean; // stop this output buffer


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 :-)


If imagejpeg brings up this warning:
Warning: imagejpeg(): Unable to access data ...
it could be a problem with "Safe Mode". A solution could be to touch the new file before, like:
imagejpeg($image_p, $newfile, 100);


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.


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()


i had the same problem as tobylewis had
when i tried to call imagejpeg(), width porperly parameters given it displayed
imagejpeg(): Unable to access usr/home/public_html/pic1.jpg
imho if not correctly configured server this function is not allowed to create the file on disk.
the workaround however is if you create the file using some other function, before call imagejpeg(). something like this
imagejpeg($dest,$file_name_dest, $quality);  


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.
$filename = "";
$im = imagecreatefromjpeg($filename);
$ModImg .= "This is the text added after EOF of the jpeg";
echo $ModImg;
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.

elliott brueggeman

I did an experiment with the image quality parameter of the imagejpeg() function when creating jpegs. I found the optimal image quality with file size is taken into account to be 80 - very close to the default value of 75.
Anything over 80 results in an unnecessary increase in file size without much increase in image quality.
Results and sample pictures:


I could not find any information on changing the DPI information on a JPG file using the GD lib. Since changing this does not resize or scale the actual image, it is only a header-setting.
The following snipplet will save your $image to $file and set the DPI to 150.
 imagejpeg($image, $file, 75);
 // Change DPI
 $dpi_x   = 150;
 $dpi_y   = 150;
 // Read the file
 $size    = filesize($file);
 $image   = file_get_contents($file);
 // Update DPI information in the JPG header
 $image[13] = chr(1);
 $image[14] = chr(floor($dpi_x/255));
 $image[15] = chr(      $dpi_x%255);
 $image[16] = chr(floor($dpi_y/255));
 $image[17] = chr(      $dpi_y%255);
 // Write the new JPG
 $f = fopen($file, 'w');
 fwrite($f, $msg, $size);
P.s. not fully tested (yet) but it works for my images ...

tom davis

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.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT');
header('Content-Type: image/jpeg');

r dot duclos

Hy, here is a little code for generate a thumbnail, very good quality. Enjoy it !
function miniature($pict, $dest_pict){
   $handle = @imagecreatefromjpeg($pict);
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');
$pict = "PICT7024.jpg";
$dest_pict = "D:/Program Files/EasyPHP1-7/www/test";
miniature($pict, $dest_pict);

03-jan-2006 01:59

I had similar problem with safe mode. My solution is:
before imagejpeg(), touch() etc.
and after everything:
strange, but it works


Here's another on-the-fly thumbnail creation script.
When I scripted the pictuerviewer on my page, I had all the pictures only in full size and qualit, because I wanted the posibility für visitors to download the pictures.
But as Imagesizes of more than 4 MP are to large for websites, I created thumbnails and the smaller pictures on the fly. But I found out, that the Script needed too much RAM, especially in the thumbnail overview, when I had more then 50 thumbnails to create on the fly at the same time.
So I modified my image creator and my viewer to let them store images, that are created. So only the first visitor has to wait (which is usually me for controlling the uploads und updates), all other visitors get the stored images, which is much faster.
Create different folders. I have a main folder called 'imagesdb' and the tree subfolders full (Full quality images), show (images for the picture viewer) and thumb (for thumbnails in overview).
Store the script for example as image.php and link it like that:
$image_name = "foo.jpg";
$style = "show";
    // I've taken the foldernames. It's easier. For the
    //thumbnails replace "show" with "thumb".
$image_name = "imagesdb/$style/$image_name";
       $image_name = "image.php?image_name=$image_name&style=$style";
    // only if file doesn't exist call the on-the-fly creating file
Now the main script, stored in the file image.php:
$image_name = $_GET['image_name'];
$style = $_GET['style'];
    // Now set the maximum sizes to the different styles.
    // You may set additional styles, but remember to
    // create the according subfolders.
switch($style) {
 case "show":
   $max_size = 800;
 case "thumb":
   $max_size = 125;
$dest_file = "imagesdb/$style/$image_name";
    // set output file
$image_file = "imagesdb/full/$image_name";
    // set source file
$size = getimagesize($image_file);
    // get original size
if($size[0] > $size[1]) {
 $divisor = $size[0] / $max_size;
else {
 $divisor = $size[1] / $max_size;
    // to get allways pictures of the same size, which ist
    // mostly wanted in imageviewers, look what ist larger:
    // width or height
$new_width = $size[0] / $divisor;
$new_height = $size[1] / $divisor;
    // set new sizes
settype($new_width, 'integer');
settype($new_height, 'integer');
    // sizes should be integers
$image_big = imagecreatefromjpeg($image_file);
    // load original image
$image_small = imagecreatetruecolor($new_width, $new_height);
    // create new image
imagecopyresampled($image_small, $image_big, 0,0, 0,0, $new_width,$new_height, $size[0],$size[1]);
    // imageresampled whill result in a much higher quality
    // than imageresized
    // the original data are no longer used
header("Content-type: image/jpeg");
if($style=="show" || $style=="thumb") {
   imagejpeg($image_small, $dest_file, 100);
    // if you have set additional sizese put them in the
    // if-arguments, too.
    // if someone calls the image.php directly in the
    // browser with imagenames allready existing, they
    // won't be overwritten
imagejpeg($image_small, '', 100);
    // finally send image to browser and destroy no longer
    // needed data.
As this website helped me for several times in the past and for creating this script, I hope I can help others with this script saving the time for developing a much more performant solution than an allways-on-the-fly-creating script.


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:
// Use it this way: resize.php?pic=imageurl&width=width_in_pixels
// 2004
   header("Content-type: image/jpeg");
   $im     = imagecreatefromjpeg($pic);
   $orange = imagecolorallocate($im, 220, 210, 60);
   $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
   if (($new_w<=0) or ($new_w>$old_x)) {
if ($old_x > $old_y) {
if ($old_x < $old_y) {
if ($old_x == $old_y) {

pedja pedja

Here is sample function that creates thumbnail of source JPEG file. Thumbnail wil be in square form (with and height are the same), and original image cropped to fit in.
$p_thumb_file - name of the file (including path) where thumb should be saved to
$p_photo_file - nam of the source JPEG file (including path) thatthumbnail should be created of
$p_max_size - with and height (they will be the same) in pixels for thumbnail image
$p_quality - quality of jpeg thumbnail
function photoCreateCropThumb ($p_thumb_file, $p_photo_file, $p_max_size, $p_quality = 75) {
$pic = @imagecreatefromjpeg($p_photo_file);
if ($pic) {
$thumb = @imagecreatetruecolor ($p_max_size, $p_max_size) or die ("Can't create Image!");
$width = imagesx($pic);
$height = imagesy($pic);
if ($width < $height) {
$twidth = $p_max_size;
$theight = $twidth * $height / $width;
imagecopyresized($thumb, $pic, 0, 0, 0, ($height/2)-($width/2), $twidth, $theight, $width, $height);
} else {
$theight = $p_max_size;
$twidth = $theight * $width / $height;
imagecopyresized($thumb, $pic, 0, 0, ($width/2)-($height/2), 0, $twidth, $theight, $width, $height);
ImageJPEG ($thumb, $p_thumb_file, $p_quality);


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.
$new_width = 100;
$new_height = 200;
$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
$image_buffer = ob_get_contents();
//Create temporary file and write to it
$fp = tmpfile();
fwrite($fp, $image_buffer)) {
//Upload new image
$conn_id = ftp_connect('ftp.example.tld');
ftp_fput($conn_id,'path/to/new/file.jpg', $fp, FTP_BINARY);

chris dot calo

function create_thumbnail( $source_file, $destination_file, $max_dimension)
list($img_width,$img_height) = getimagesize($source_file); // Get the original dimentions
$aspect_ratio = $img_width / $img_height;

if ( ($img_width > $max_dimension) || ($img_height > $max_dimension) ) // If either dimension is too big...
if ( $img_width > $img_height ) // For wide images...
$new_width = $max_dimension;
$new_height = $new_width / $aspect_ratio;
elseif ( $img_width < $img_height ) // For tall images...
$new_height = $max_dimension;
$new_width = $new_height * $aspect_ratio;
elseif ( $img_width == $img_height ) // For square images...
$new_width = $max_dimension;
$new_height = $max_dimension;
else { echo "Error reading image size."; return FALSE; }
else { $new_width = $img_width; $new_height = $img_height; } // If it's already smaller, don't change the size.

// Make sure these are integers.
$new_width = intval($new_width);
$new_height = intval($new_height);

$thumbnail = imagecreatetruecolor($new_width,$new_height); // Creates a new image in memory.
// The following block retrieves the source file.  It assumes the filename extensions match the file's format.
if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
{ $img_source = imagecreatefromjpeg($source_file); }
if ( strpos($source_file,".bmp") ) { $img_source = imagecreatefromwbmp($source_file); }
if ( strpos($source_file,".png") ) { $img_source = imagecreatefrompng($source_file); }

// Here we resample and create the new jpeg.
imagecopyresampled($thumbnail, $img_source, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
imagejpeg( $thumbnail, $destination_file, 100 );

// Finally, we destroy the two images in memory.


For example:
Header("Content-type: image/jpeg");
$im = imagecreatefromjpeg("./test.jpg");
the jpeg quality from 0 to 100

10-sep-2004 04: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.


For all those people getting the
"Warning: imagejpeg(): Unable to access data ..."
I solved it by chmodding the directory you're writing to, to 0777.
NO fopen() needed!

envide nefelibata envide

Every script I was writing was giving me an error.
When writing the following code I was able, as a client, to browse the website and save the images (Save image as...) with IE. Yet with Firefox and family the browser tried to save them as 'script_name.php' instead of 'image_name.jpg'.
   header("Content-Type: image/jpeg");
   imagejpeg($image,'',100); // Output to Browser
After trying to save all the watermarked images or saving the image as 'temp.jpg' before outputing it to user, I've read this topic on BugZilla that advised to add the following header:
   header("Content-Type: image/jpeg");
   header("Content-Disposition: attachment; filename=image_name.jpg"); // THIS ONE
Sorry about the English.


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.


Converting a directory of PNG images into jpegs is as easy as:
$d = dir('./');
while(false !== ($e = $d->read())){
$r = imagecreatefrompng('./'.$e);
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!


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.


After trying to get imagejpeg (and imagegif and imagepng) to save an image to a file for some time, it finally dawned on me that perhaps the function would not automatically create the file named in the second parameter.
I then used fopen to create a file prior to the call to imagejpeg and the image was successfully written to the file.  It did not seem to matter if fclose was called before or after the call to imagejpeg.
I also tried to create a file outside of php and use it as the target for output, but this initially failled because of permissions.  Once I set all write permissions on this also accepted output from imagejpeg.


after seeking for 2 days why ImageJpeg() was writing an empty file to the server, it was due to insufficient disk space on my hosting plan.... hope this helps,


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

25-may-2004 07: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..

rich @ richud dot com

'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.


>>Bram Van Dam's
note below is missing "()" from the ob_end_clean call:
ob_end_clean; // stop this output buffer
should read
ob_end_clean(); // stop this output buffer
You can then use this for adding content-length headers (for example flash requires a content length in advance to create loaders)
ob_start(); // start a new output buffer
  imagejpeg( $newimage, "", 90 );
  $ImageData = ob_get_contents();
  $ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer
header("Content-type: image/jpeg") ;
header("Content-Length: ".$ImageDataLength);
echo $ImageData;

Change Language

Follow Navioo On Twitter
eXTReMe Tracker