|
|
 |
imagecreatefromjpeg (PHP 3 >= 3.0.16, PHP 4, PHP 5) imagecreatefromjpeg -- Create a new image from file or URL Descriptionresource imagecreatefromjpeg ( string filename )
imagecreatefromjpeg() returns an image identifier
representing the image obtained from the given filename.
imagecreatefromjpeg() returns an empty string
on failure. It also outputs an error message, which unfortunately
displays as a broken link in a browser. To ease debugging the
following example will produce an error JPEG:
Example 1.
Example to handle an error during creation (courtesy
vic at zymsys dot com )
|
<?php
function LoadJpeg($imgname)
{
$im = @imagecreatefromjpeg($imgname); if (!$im) { $im = imagecreate(150, 30); $bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
}
return $im;
}
?>
|
|
Note: JPEG support is only available if
PHP was compiled against GD-1.8 or later.
Tip: You can use a URL as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify
the filename and Appendix L for a list of supported
URL protocols.
| Warning | Windows versions of PHP
prior to PHP 4.3.0 do not support accessing remote files via this function, even if
allow_url_fopen is enabled.
|
User Contributed Notes
imagecreatefromjpeg
Zap
14-Apr-2005 09:14
Under some configurations imagecreatefromjpeg will create files that are owned by the webserver rather than the php user. For example, php may be run as phpuser and the image will be created under apache.
This can lead to permissions problems - only a +0777 will be enough to be able to create a picture.
My solution was to chmod over ftp to 0777 just before the picture is written then change back to 0755 when the image has been created.
The alternative of course would be to have a properly configured system...
Angel Leon
31-Mar-2005 08:13
This is a very useful script when you have hundreds of images and you need a quick setup for a thumbnail, where you can select how many
pictures per row, size of the thumbnail, and the size of the pictures when clicked, all in one script. Just throw all your images and this script in a file named index.php or index.html (if your apache httpd.conf defaults to html and runs .html as php).
Script also contains simple text watermarking. See function thumbImage()
and modify to add image watermarking if you like.
<?
$row_size = 3;
$thumb_height = 200;
$big_image_height=668;
$waterMark = "mysite.com";
$dh = opendir(".");
$files = array();
while (($file = readdir($dh)) !== false) {
if (ereg("jpg",$file) || ereg("gif",$file) || ereg("png",$file)) {
$files[] = $file;
}
}
closedir($dh);
if ($show_image) {
thumbImage($show_image,$big_image_height,$waterMark);
} else if ($thumb_image) {
thumbImage($thumb_image,$thumb_height,$waterMark);
}
else {
echo "<center>" . createThumbTable($files,$row_size) . "</center>";
}
function createThumbTable($files,$pics_wide) {
$row = intval(count($files)/$pics_wide);
$picIndex = 0;
$rs = "Mostrando " . count($files) . " imagenes<br>";
$rs .= "<table border=0 cellspacing=1 cellpadding=0 style='border:1px solid black'>\n";
for ($i=0; $i <$row; $i++) {
$rs .= "\t<tr>\n";
for ($picIndex,$j=0;
$j < $pics_wide && $picIndex < count($files);
$j++,$picIndex++) {
$rs .= "\t\t<td><a href=index.php?show_image=" .
$files[$picIndex] . ">" .
"<img src=index.php?thumb_image=" .
$files[$picIndex] . " border=0 title='Copyright wedoit4you.com'></a></td>\n";
}
$rs .= "\t</tr>\n";
}$rs .= "<tr><td colspan=$pics_wide align=center>Free Thumbnail script by <a href=http://www.wedoit4you.com>wedoit4you.com</a><br>Written by Angel Leon (March 2005)</td></tr></table>\n";
return $rs;
} function thumbImage($file,$img_height,$waterMark) {
$img_temp = imagecreatefromjpeg($file);
$black = @imagecolorallocate ($img_temp, 0, 0, 0);
$white = @imagecolorallocate ($img_temp, 255, 255, 255);
$font = 2;
$img_width=imagesx($img_temp)/imagesy($img_temp)*$img_height;
$img_thumb=imagecreatetruecolor($img_width,$img_height);
imagecopyresampled($img_thumb,
$img_temp,0,0,0,0,$img_width,
$img_height,
imagesx ($img_temp),
imagesy($img_temp));
$originx = imagesx($img_thumb) - 100;
$originy = imagesy($img_thumb) - 15;
@imagestring ($img_thumb, $font, $originx + 10, $originy,
$waterMark, $black);
@imagestring ($img_thumb, $font, $originx + 11, $originy - 1,
$waterMark, $white);
header ("Content-type: image/jpeg");
imagejpeg($img_thumb, "", 60);
imagedestroy ($img_thumb);
}
?>
dmf four one fiive at yahoo dot com
02-Mar-2005 06:08
Another thing to note, is the file not might actually be a jpeg , even though the filename ends in .jpg. If this is the case the command won't work. You will need imagecreatefromgif()
The easiest way to check is to use your favorite editor like vi.
On Line one it will tell you if its a gif or a jpg..
I took a quick look at a few image files. the gifs say GIF87a and the real jpegs should say JFIF or something like that.
ceefour -at!- gauldong.net
24-Feb-2005 04:24
I have to say recompiling PHP from the sources and enabling JPEG support in gd took me awhile to figure out.
Somewhere especially configure --help should have stated that --with-jpeg-dir is MANDATORY if you want to have JPEG support. And even if you did so, it doesn't mean you'll get it. If it's wrongly configured, no error is going to be output, all you get is "no JPEG support". What's more confusing is when JPEG support is disabled phpinfo won't say "JPEG Support: disabled", but just omit the entry so you won't even realize something is wrong.
If you recompile PHP or gd, make sure:
- rm -f config.cache FIRST
- make clean (this helps A LOT), actually you can just delete modules/gd.*, and every *.o in ext/gd. this part actually gave me the best headache
- ./configure --with-jpeg-dir=/usr/lib OR any other directory which contains the BINARY library of libjpeg
- make, make install
phpinfo should now display jpeg support... good luck.
(you lucky guys who already have PHP 5 installed on your server... you don't have to go through all the mess I had)
tl at comvironment dot com
24-Feb-2005 03:53
I made a script to produce, save, and use dynamic buttons simultaneously. If the file exists, it will be shown as usual. If not, this script produces a new image and saves it. You only need the background (back.jpg). Maybe it is useful for somone.
<?php
class Button {
var $ib = 'back.jpg';
var $im;
function Button ($fileName, $string) {
$this -> im = $fileName;
if(!file_exists($this -> im)) {
$this -> _createButton($string);
}
}
function getFileName() {
return $this -> im;
}
function _createButton($string) {
$font = 4;
$width = max(400,(ImageFontWidth($font) * strlen($string)) + 4);
$height = max(20,(ImageFontHeight($font) + 4));
$imgBack=ImageCreateFromJPEG($this -> ib);
$imgText=ImageCreateTrueColor($width,$height);
$textColor = imagecolorallocate ($imgText,90,90,90);
ImageCopy($imgText,$imgBack,0,0,0,0,$width,$height);
ImageString ($imgText,$font,2,2,$string,$textColor);
ImageJPEG($imgText,$this -> im,85);
ImageDestroy($imgBack);
ImageDestroy($imgText);
chmod ($this -> im,0644);
}
}
$button = new Button('button.jpg','button text');
echo '<img src="' . $button -> getFileName() . '">';
?>
cs at kainaw dot com
01-Nov-2004 01:09
The ImageCreateFromJPEG() function is capable of throwing an emalloc() error. If this happens, the script will die, but the error will be in your error logs. You should ensure that you have memory available before creating a large image from a jpeg file.
webmaster at kautto dot se
25-Oct-2004 05:48
Concerning the path discussion. A relative path works just fine, if it is used properly. The thing is just to keep track of where in the file system you actually are calling the function from.
E.g. including file A into file B, and then executing file A. Now calls made in file B will act as if they actually are made file A, due to the inclusion. So a well designed filesystem is very important. Also moving a file might lead to this type of path related problems.
Hope this made any sence! :)
Jezu
22-Oct-2004 05:36
I have noticed that Nokia's old camera-phones create non-standard JPEG's.
Nokias' JPEG doesn't end with 0xFFD9. Add 0xFFD9 end of file and image works fine with imagecreatefromjpeg(). Willertan1980 already sent code to do that.
dmjoe
15-Jul-2004 06:46
This function DOES accept paths in the filename, just make sure they're absolute paths. A relative path won't work, at least it didn't for me. This is in response to jonlup's comment from june 25:
"I played with "imagecreatefromjpeg()" function and, after a few tests, I found that the filename that it requires as parameter should be only a simple filename: the function does not work if in the string of the filename is specified a path to that file."
29-Jun-2004 06:55
here is my clear method to resize images
you can check how it works on http://www.jetevents.pl
<?php
$maxx=100; $maxy=75; $name=strtolower(substr($_FILES['file']['name'],0,-4)).".jpg"; $size = GetImageSize ($_FILES['file']['tmp_name']); if ($size[0]>$size[1]) {$sizemin[0]=$maxx;$sizemin[1]=$maxy;};
if ($size[1]>$size[0]) {$sizemin[0]=$maxy;$sizemin[1]=$maxx;};
$im=@imagecreatefromjpeg($path); $small = imagecreatetruecolor($sizemin[0], $sizemin[1]); ImageCopyResampled($small, $im, 0, 0, 0, 0, $sizemin[0], $sizemin[1], $size[0], $size[1]);
ImageDestroy($im); if (ImageJPEG($small,$path,100)) {
echo "File $path has been written<br>\n"; echo "size: ".$sizemin[0]."x".$sizemin[1] ."<br>\n";
}
else
{
echo "<font color=red><b>"; echo "Error ! File has not been written.";
echo "</b></font><br>\n";
};
?>
jonlup at yahoo dot com
25-Jun-2004 09:04
I played with "imagecreatefromjpeg()" function and, after a few tests, I found that the filename that it requires as parameter should be only a simple filename: the function does not work if in the string of the filename is specified a path to that file.
The quickest workaround found: do a chdir() to the directory of your image file before try to use "imagecreatefromjpeg()" with your file as parameter.
I did not test the other functions (imagecreatefromgd2(), imagecreatefromgd(), imagecreatefromgif() etc.), but I suppose that they work in the same way.
I think that little trick should be specified in the manual.
Javier Rayon
25-May-2004 01:55
Using imagecreate() combined with imagecreatefromjpeg() in PHP 4.3.0 and up creates wrong color jpeg's.
Use imagecreatetruecolor() instead of imagecreate() for right color images.
Sne
07-Apr-2004 08:02
small script that calculates square (in %) of eche color on the PNG image.
<?
$t1=time();
$im1=ImageCreatefrompng('1.png'); echo "<img src=1.png>";
$widthIm=ImageSX($im1);
$heightIm=ImageSY($im1);
$total=$widthIm*$heightIm;
$cvcol=imagecolorstotal($im1);
for ($i=0; $i<$widthIm; $i++){
for ($j=0; $j<$heightIm; $j++){
$tochka=imagecolorat($im1,$i,$j);
$num[$tochka]=$num[$tochka]+1;
}
}
echo "<br><br>$widthIm x $heightIm ($total pixels).";
echo " Number of colors in pallette - $cvcol<br><br>
";
echo "<table width=400 border =1>";
for ($k=0; $k<$cvcol; $k++) {
$proc=round($num[$k]/$total*100, 2);
$Palitra =ImageColorsForIndex($im1,$k);
$Palitra[red]= dechex($Palitra[red]);
$Palitra[green]= dechex($Palitra[green]);
$Palitra[blue]= dechex($Palitra[blue]);
echo "<tr><td>$k</td><td width=100>$Palitra[red]-$Palitra[green]-$Palitra[blue]</td>";
echo "<td width=100>$proc %</td>";
echo "<td width=100 bgcolor=$Palitra[red],$Palitra";
echo "[green],$Palitra[blue]> </td></tr>";
}
echo "</table>";
imagedestroy($im1);
$t2=-$t1+time();
echo "<br>Time past: $t2 sec";
?>
jdolecek at NetBSD dot org
24-Feb-2004 06:16
ImageCreateFromJPEG() as of GD 2.0.15 (as bundled with PHP 4.3.4) doesn't handle 4-channel (with alpha channel) JPG images well, the function fails and emits message 'Unsupported color conversion request' to stderr. The solution I found for this is to use NetPBM tools - 'jpegtopnm < orig.jpg | pnmtojpeg > new.jpg' creates a JPG image PHP GD library can open just fine.
willertan1980 at yahoo dot com
20-Aug-2003 06:14
did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG
JPEG image should start with 0xFFD8 and end with 0xFFD9
// this may help to fix the error
function check_jpeg($f, $fix=false ){
# [070203]
# check for jpeg file header and footer - also try to fix it
if ( false !== (@$fd = fopen($f, 'r+b' )) ){
if ( fread($fd,2)==chr(255).chr(216) ){
fseek ( $fd, -2, SEEK_END );
if ( fread($fd,2)==chr(255).chr(217) ){
fclose($fd);
return true;
}else{
if ( $fix && fwrite($fd,chr(255).chr(217)) ){return true;}
fclose($fd);
return false;
}
}else{fclose($fd); return false;}
}else{
return false;
}
}
office at 4point-webdesign dot com
08-Jul-2003 02:47
Here's the answer for your 256 color only problem!!!
use these functions in order then it works fine!
$img_src=imagecreatefromjpeg('yoursource.jpg');
$img_dst=imagecreatetruecolor(20,20);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, 20, 20, 20, 20);
imagejpeg($img_dst, $g_dstfile, 100);
imagedestroy($img_dst);
Greetz, GTB
lordneon at deskmod dot com
23-Jun-2003 04:00
For Windows users who wants to enable the GD libary:
It took me some while to figure this out, but in the end it worked (and still does) great.
1. First download the latest (stable recommended) version of php
2. Unzip to f.ex c:\php\
3. Now you should have a file in c:\php\ that's named php.ini.dist (or something like that). Rename that to php.ini and copy it to the root of you Windows directory.
4. Open the php.ini file (the easiers way is to open the run promnt at your start menu and just type php.ini and hit enter).
5. Search (ctrl+f) for extension_dir. The default value is set to "./", make it to "./extensions"
6. Now you need to find where in the php.ini the modules for Windows is located. Search for gd.
7. Remove the ; char infront of this line: extension=php_gd2.dll
8. Try make a php script with some image functions and see if it works. F.ex $im = imageCreate("test.jpg");
If you get a message that says something like imageCreate function doesn't exist the gd libary is not loaded.
9. That's all. Have fun using GD in Windows :)
atapi103 at hotmail dot com
31-May-2003 03:14
As jpsy sugested Windows users can download the zip to get the gd2_dll extension
OR
If you already installed with the windows installer and are too lazy to get the zip you can go here
http://www.coupin.net/gd-freetype/windows.php
Download the php_gd2.dll file put it wherever you want, and change the
extension_dir=C:\php\extensions
Wherever you saved the dll to is the path you put in, remember to uncomment
extension=php_gd2.dll
Do not uncomment the one above for gd.dll (the one without the 2)
tom at ierna dot com
31-Jan-2003 05:37
Doing a "make clean", regardless of which platform you're on (including MacOS X) should clean up the source tree enough to ensure that config changes take effect...
tuxedobob at mac dot com
16-Jan-2003 12:27
Note for PHP 4.3 under Mac OS X 10.2.3:
I originally compiled using only --with-mysql --with-apxs. When this compiled correctly (for a change; previous versions didn't), I then tried adding --with-gd --with-jpg-dir and a bunch of other goodies, but they didn't add in. Apparently removing config.cache isn't sufficient. My advice is to simply delete the entire folder, and try your new configure command on a clean untarred source folder.
bpiere21 at hotmail dot com
29-Jun-2002 08:57
###--- imagecreatefromjpeg only opens JPEG files from your disk.
###--- To load JPEG images from a URL, use the function below.
function LoadJPEG ($imgURL) {
##-- Get Image file from Port 80 --##
$fp = fopen($imgURL, "r");
$imageFile = fread ($fp, 3000000);
fclose($fp);
##-- Create a temporary file on disk --##
$tmpfname = tempnam ("/temp", "IMG");
##-- Put image data into the temp file --##
$fp = fopen($tmpfname, "w");
fwrite($fp, $imageFile);
fclose($fp);
##-- Load Image from Disk with GD library --##
$im = imagecreatefromjpeg ($tmpfname);
##-- Delete Temporary File --##
unlink($tmpfname);
##-- Check for errors --##
if (!$im) {
print "Could not create JPEG image $imgURL";
}
return $im;
}
$imageData = LoadJPEG("http://www.example.com/example.jpg");
Header( "Content-Type: image/jpeg");
imagejpeg($imageData, '', 100);
1 at chatways dot com
07-Feb-2002 01:04
imagecreatefromjpeg doesn't seem to support cmyk-jpgs :-(
mihkel at raba dot ee
05-Jan-2002 03:00
[Ed Note: You must have netpbm installed for this to work --alindeman @ php.net]
Just wanted to let you know that
imagecreatefromjpeg crashes php
(command line at least) sometimes with segmentation fault when jpeg is corrupted.
To get rid of the nasty segmentation fault i used
system ("jpegtopnm f.jpg > f.pnm", $r);
if ($r != 0) {printf ("invalid jpeg\n"); return; }
system ("pnmtopng f.pnm > f.png");
$im =imagecreatefrompng ("f.png");
jason_wilk at hotmail dot com
02-Oct-2001 12:16
Wow, it only took me 3 hours to get all of the lib paths correct for my install. Some of them are /usr, and some are /usr/lib...go figure. I figured that I would post this in the hopes that it will save somebody some time.
Remember that if you're using rpm installs...you have to install the devel packages. For example, if you're installing mysql from rpm, and you want to compile with support for your particular MySql dist, you must install mysql-devel*.rpm.
Anyway, I'm a redhat 7.1 install...with all appropriate devel packages installed.
./configure \
--with-mysql=/usr \
--with-ftp \
--with-apxs=/home/www/bin/apxs \
--with-xpm-dir=/usr/X11R6 \
--with-gdbm=/usr/lib \
--with-gd=/usr \
--with-zlib-dir=/usr/lib \
--with-jpeg-dir=/usr/lib \
--with-png-dir=/usr/lib \
--with-tiff-dir=/usr/lib \
--with-config-file-path=/home/www/conf \
--with-freetype-dir=/usr/lib \
--enable-magic-quotes \
--enable-track-vars
paul at rainbowzone dot com
28-Aug-2001 02:21
Basta/Justnoone:
GD no longer supports the GIF format due to legal issues with Unisys (they own the patent for LZW compression used in GIF). See the documentation for GD for more details:
http://www.boutell.com/gd/manual1.8.4.html
brett_no_spam at dolphyn dot com
01-Jul-2001 08:56
In the new versions (PHP 4.0.6, GD 2.0.1), ImageCreateFromJPEG() results in a TRUE COLOR image.
In the older versions, you only get 256 colors.
dmsales at design-monster dot com
28-Jun-2001 12:17
I just wanted to note here something i found else where that was very helpful to me when using jpeg images. when using imagecreatefromjpeg() it can be difficult to allocate new colors.
The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.
infoNOSPAM at psnetworks dot net
08-Apr-2001 11:33
For those having trouble getting jpeg support using gd, make sure you
rm config.cache
before reconfiguring php. Otherwise the configure script will assume jpeg support is still not compiled into gd.
mboucher at ampmedia dot net
19-Feb-2001 06:00
In response to my own post:
Maybe this is common knowledge but here is how I solved my problem. Hopefully this will help out seeing how I couldn't find any other articles on this topic with a solution.
This seems to work pretty well. Displays in browser and QT Picture Viewer but for some reason Photoshop won't open it. Translation error. Since I'm just using it to cache the image for when the our content provider goes down no biggie there.
$si = fopen($imagePathURL, "r"); // open URL
$serverImg = fread($si, 1000000); // read contents
fclose($si); // close file
/* open file to save to (w+ creates if file does not exist || b opens binary safe [Win32]) Seemed to work fine with out the 'b' on Windows NT but just to be safe. */
$si = fopen($saveImgTo, "w+b");
fwrite($si, $serverImg); // write contents to file
fclose($si); // close file
Hope this helps somebody...long live PHP
support at corbach dot de
21-Dec-2000 05:46
Wonder why that's just the only image function you can't get to work? Remember that you have to use a gd library that supports JPEG (make it manually and <important>edit the makefile</important>)! Especially all gd RPMs from SuSE (including 7.0) don't support it as it's not default up to gd 1.8.3.
timpie2000 at zeelandnet dot nl
22-Sep-2000 07:52
Be sure to allocate your colors AFTER you used this function or else you might get some strange colors..
rodders_plonker at yahoo dot com
21-Jul-2000 10:49
To all those having trouble with a message to the effect of:<br>
CreateImageFromJpeg() not supported in this PHP build<br>
Start by adding --with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)
| |