CakeFest 2017 NYC, the Official CakePHP Conference

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7)

imagecreatefromjpegCreate a new image from file or URL

Description

resource imagecreatefromjpeg ( string $filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the JPEG image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a JPEG

<?php
function LoadJpeg($imgname)
{
    
/* Attempt to open */
    
$im = @imagecreatefromjpeg($imgname);

    
/* See if it failed */
    
if(!$im)
    {
        
/* Create a black image */
        
$im  imagecreatetruecolor(15030);
        
$bgc imagecolorallocate($im255255255);
        
$tc  imagecolorallocate($im000);

        
imagefilledrectangle($im0015030$bgc);

        
/* Output an error message */
        
imagestring($im155'Error loading ' $imgname$tc);
    }

    return 
$im;
}

header('Content-Type: image/jpeg');

$img LoadJpeg('bogus.image');

imagejpeg($img);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a JPEG
add a note add a note

User Contributed Notes 33 notes

up
17
jan at recreatie-zorg dot nl
3 years ago
This function does not honour EXIF orientation data.  Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg().  Below is a function to create an image from JPEG while honouring EXIF orientation data.

<?php
   
function imagecreatefromjpegexif($filename)
    {
       
$img = imagecreatefromjpeg($filename);
       
$exif = exif_read_data($filename);
        if (
$img && $exif && isset($exif['Orientation']))
        {
           
$ort = $exif['Orientation'];

            if (
$ort == 6 || $ort == 5)
               
$img = imagerotate($img, 270, null);
            if (
$ort == 3 || $ort == 4)
               
$img = imagerotate($img, 180, null);
            if (
$ort == 8 || $ort == 7)
               
$img = imagerotate($img, 90, null);

            if (
$ort == 5 || $ort == 4 || $ort == 7)
               
imageflip($img, IMG_FLIP_HORIZONTAL);
        }
        return
$img;
    }
?>
up
24
matt dot squirrell dot php at hsmx dot com
4 years ago
This little function allows you to create an image based on the popular image types without worrying about what it is:

<?php
function imageCreateFromAny($filepath) {
   
$type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize()
   
$allowedTypes = array(
       
1// [] gif
       
2// [] jpg
       
3// [] png
       
6   // [] bmp
   
);
    if (!
in_array($type, $allowedTypes)) {
        return
false;
    }
    switch (
$type) {
        case
1 :
           
$im = imageCreateFromGif($filepath);
        break;
        case
2 :
           
$im = imageCreateFromJpeg($filepath);
        break;
        case
3 :
           
$im = imageCreateFromPng($filepath);
        break;
        case
6 :
           
$im = imageCreateFromBmp($filepath);
        break;
    }   
    return
$im
}
?>
up
7
willertan1980 at yahoo dot com
13 years ago
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;
    }
}
up
3
e dot a dot schultz at gmail dot com
10 years ago
In John's human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn't compile with the "--enable-memory-limit" option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php

<?php
function setMemoryForImage( $filename ){
   
$imageInfo = getimagesize($filename);
   
$MB = 1048576// number of bytes in 1M
   
$K64 = 65536;    // number of bytes in 64K
   
$TWEAKFACTOR = 1.5// Or whatever works for you
   
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                           *
$imageInfo['bits']
                                           *
$imageInfo['channels'] / 8
                            
+ $K64
                          
) * $TWEAKFACTOR
                        
);
   
//ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
    //Default memory limit is 8MB so well stick with that.
    //To find out what yours is, view your php.ini file.
   
$memoryLimit = 8 * $MB;
    if (
function_exists('memory_get_usage') &&
       
memory_get_usage() + $memoryNeeded > $memoryLimit)
    {
       
$newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
                                            +
$memoryNeeded
                                           
- $memoryLimit
                                           
) / $MB
                                       
);
       
ini_set( 'memory_limit', $newLimit . 'M' );
        return
true;
    }else
        return
false;
    }
}
?>
up
5
juozaspo at gmail dot com
6 years ago
There is my actual script to resize image without distortion to generate a thumbnail and/or show a smaller to browser.

<?php
// usual header used on my all pages
ob_start("ob_gzhandler");
$PHP_SELF=$_SERVER['PHP_SELF'];
include
"include/errors.php"; //error log script

// actual script begins here
$type=false;
function
open_image ($file) {
   
//detect type and process accordinally
   
global $type;
   
$size=getimagesize($file);
    switch(
$size["mime"]){
        case
"image/jpeg":
           
$im = imagecreatefromjpeg($file); //jpeg file
       
break;
        case
"image/gif":
           
$im = imagecreatefromgif($file); //gif file
     
break;
      case
"image/png":
         
$im = imagecreatefrompng($file); //png file
     
break;
    default:
       
$im=false;
    break;
    }
    return
$im;
}

$url = $_GET['url'];
if (isset(
$_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($url))) {
 
// send the last mod time of the file back
   
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($url)).' GMT', true, 304); //is it cached?
} else {

$image = open_image($url);

if (
$image === false) { die ('Unable to open image'); }

$w = imagesx($image);
$h = imagesy($image);

//calculate new image dimensions (preserve aspect)
if(isset($_GET['w']) && !isset($_GET['h'])){
   
$new_w=$_GET['w'];
   
$new_h=$new_w * ($h/$w);
} elseif (isset(
$_GET['h']) && !isset($_GET['w'])) {
   
$new_h=$_GET['h'];
   
$new_w=$new_h * ($w/$h);
} else {
   
$new_w=isset($_GET['w'])?$_GET['w']:560;
   
$new_h=isset($_GET['h'])?$_GET['h']:560;
    if((
$w/$h) > ($new_w/$new_h)){
       
$new_h=$new_w*($h/$w);
    } else {
       
$new_w=$new_h*($w/$h);   
    }
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//effects
if(isset($_GET['blur'])){
   
$lv=$_GET['blur'];
    for(
$i=0; $i<$lv;$i++){
       
$matrix=array(array(1,1,1),array(1,1,1),array(1,1,1));
       
$divisor = 9;
       
$offset = 0;
       
imageconvolution($im2, $matrix, $divisor, $offset);
    }
}
if(isset(
$_GET['sharpen'])){
   
$lv=$_GET['sharpen'];
    for(
$i=0; $i<$lv;$i++){
       
$matrix = array(array(-1,-1,-1),array(-1,16,-1),array(-1,-1,-1));
       
$divisor = 8;
       
$offset = 0;
       
imageconvolution($im2, $matrix, $divisor, $offset);
    }
}

header('Content-type: image/jpeg');
$name=explode(".", basename($_GET['url']));
header("Content-Disposition: inline; filename=".$name[0]."_t.jpg");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
header("Cache-Control: public");
header("Pragma: public");
imagejpeg($im2);
//imagedestroy($im2);
//imagedestroy($image);
}  

?>
up
4
hvozda at ack dot org
10 years ago
If imagecreatefromjpeg() fails with "PHP Fatal error:  Call to undefined function:  imagecreatefromjpeg()", it does NOT necessarily mean that you don't have GD installed.

If phpinfo() shows GD, but not JPEG support, then that's the problem.  You would think that --with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn't in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified...
up
1
brentwientjes at NOSPAM dot comcast dot net
7 years ago
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system.  I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section.  Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser.  So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images.  I have been testing for several days with hundreds of various size images and it seems to work well.  Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking.  Best of luck.

---  from move_upload_file post ---

I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base, $w_dst, $h_dst, $n_img, $o_img)
  {
ini_set('memory_limit', '100M');   //  handle large images
  
unlink($img_base.$n_img);         //  remove old images if present
  
unlink($img_base.$o_img);
  
$new_img = $img_base.$n_img;
    
  
$file_src = $img_base."img.jpg"//  temporary safe image storage
  
unlink($file_src);
  
move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);
             
   list(
$w_src, $h_src, $type) = getimagesize($file_src);  // create new dimensions, keeping aspect ratio
  
$ratio = $w_src/$h_src;
   if (
$w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}

   switch (
$type)
     {case
1:   //   gif -> jpg
       
$img_src = imagecreatefromgif($file_src);
        break;
      case
2:   //   jpeg -> jpg
       
$img_src = imagecreatefromjpeg($file_src);
        break;
      case
3//   png -> jpg
       
$img_src = imagecreatefrompng($file_src);
        break;
     }
  
$img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample
  
  
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
  
imagejpeg($img_dst, $new_img);    //  save new image

  
unlink($file_src);  //  clean up image storage
  
imagedestroy($img_src);       
  
imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/", 150, 150, "u".$p_id."v".$ver.".jpg", "u".$p_id."v".$delver.".jpg");

?>
up
1
huguowen at cn dot ibm dot com
9 years ago
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

Problem I meet:

When i run following function, which terminates at  

$img = @imagecreatefromjpeg($image_path);

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

Solution:

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini 
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it's not enabled by default.
You have to turn it on,
You may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension.

Change:
,extension=php_gd2.dll

To:
extension=php_gd2.dll

You may also have to correct the extension directory setting
from:
extension_dir = "./"
extension_dir = "./extensions"
To (FOR WINDOWS):
extension_dir = "c:/php/extensions"(php 4)
extension_dir = "c:/php/ext"(php 5)

Cheers!
up
3
bpiere21 at hotmail dot com
14 years ago
###--- 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);
up
1
Ray.Paseur sometimes uses Gmail
6 years ago
If you have a blank in the file name, and you use a local URL, this function works.  Not so with a fully qualified URL

<?php
$url
= 'RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// WORKS PERFECTLY

$url = 'http://www.example.com/RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// FAILS Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
?>
up
1
sagarsdeshmukh91 at gmail dot com
22 days ago
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'image.jpg' is not a valid JPEG file

This only happens with certain images, which when opened in any program are ok, it even uploads to the version of the site I have on localhost with no problems,

To fix try below code snippet-

<?php
...
$image = @ImageCreateFromJpeg($image_name);
if (!
$image)
{
   
$image= imagecreatefromstring(file_get_contents($image_name));
}
...
?>
up
1
dmhouse at gmail dot com
9 years ago
For a script that allows you to calculate the "fudge factor" discussed below by Karolis and Yaroukh, try the following. Grab a few images, preferably some large ones (the script should cope with images of up to 10 megapixels or so), some small ones, and some ones in between. Add their filenames to the $images array, then load the script in your browser.

<?php

header
('Content-Type: text/plain');

ini_set('memory_limit', '50M');

function
format_size($size) {
  if (
$size < 1024) {
    return
$size . ' bytes';
  }
  else {
   
$size = round($size / 1024, 2);
   
$suffix = 'KB';
    if (
$size >= 1024) {
     
$size = round($size / 1024, 2);
     
$suffix = 'MB';
    }
    return
$size . ' ' . $suffix;
  }
}

$start_mem = memory_get_usage();

echo <<<INTRO
The memory required to load an image using imagecreatefromjpeg() is a function
of the image's dimensions and the images's bit depth, multipled by an overhead.
It can calculated from this formula:
Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor
Where Bytes per pixel = Bit depth/8, or Bits per channel * Num channels / 8.
This script calculates the Overhead fudge factor by loading images of
various sizes.
INTRO;

echo
"\n\n";

echo
'Limit: ' . ini_get('memory_limit') . "\n";
echo
'Usage before: ' . format_size($start_mem) . "\n";

// Place the images to load in the following array:
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
$ffs = array();

echo
"\n";

foreach (
$images as $image) {
 
$info = getimagesize($image);
 
printf('Loading image %s, size %s * %s, bpp %s... ',
        
$image, $info[0], $info[1], $info['bits']);
 
$im = imagecreatefromjpeg($image);
 
$mem = memory_get_usage();
  echo
'done' . "\n";
  echo
'Memory usage: ' . format_size($mem) . "\n";
  echo
'Difference: ' . format_size($mem - $start_mem) . "\n";
 
$ff = (($mem - $start_mem) /
         (
$info[0] * $info[1] * ($info['bits'] / 8) * $info['channels']));
 
$ffs[] = $ff;
  echo
'Difference / (Width * Height * Bytes per pixel): ' . $ff . "\n";
 
imagedestroy($im);
 
$start_mem = memory_get_usage();
  echo
'Destroyed. Memory usage: ' . format_size($start_mem) . "\n";

  echo
"\n";
}

echo
'Mean fudge factor: ' . (array_sum($ffs) / count($ffs));

?>
up
1
anatol at nugob dot org
10 years ago
When working with uploaded jpeg files it is usually a good idea to execute a little but very useful program called jhead
( http://www.sentex.net/~mwandel/jhead/ ).

This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.

Usage:
<?php
exec
("/path/to/jhead -purejpg /path/to/image");
// for example when you uploaded a file through a form, do this before you proceed:
exec("/path/to/jhead -purejpg ".$file['tmp_name']);
?>

I didn't have the chance to test this but I guess this might even solve the problem caused by images that were taken with Canon PowerShot cameras which crash PHP.

This is from the jhead documentation: "-purejpg: Delete all JPEG sections that aren't necessary for rendering the image. Strips any metadata that various applications may have left in the image."

jhead got some other useful options as well...
up
1
linus at flowingcreativity dot net
11 years ago
I am using PHP 4.3.8 and GD 2.0.23-compatible, and this function does not return an empty string on failure as stated. This line:

<?php
var_dump
(imagecreatefromjpeg('bogus filename'));
?>

outputs:

bool(false)

Of course this doesn't matter unless you're using a strict comparison operator to evaluate the result, but I thought I'd point it out.
up
1
ceefour -at!- gauldong.net
11 years ago
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)
up
1
cs at kainaw dot com
12 years ago
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.
up
0
pavel.lint at vk.com
4 years ago
I was experiencing troubles with imagecreatefromjpeg() as it outputted errors even when called with @ in front. ini_set("gd.jpeg_ignore_warning", 1) didnt work for me, so I came up with another simple solution.

The problem is caused by gd error output, so by redirecting STDERR to /dev/null all the error messages in it are supressed and you can still use regular STDOUT for your error output.

So, just use
<?
fclose
( STDERR );
$STDERR = fopen( "/dev/null", "wb" );
?>
up
0
Jrn Berkefeld
5 years ago
I encountered a very strange behaviour:
The background:
Each time users uploaded images, the original file was stored along with a thumbnail and a medium sized version for small-sized slideshows.
that means that on upload all of these original images were acknowledged by php as valid jpg

The change:
I created a new slideshow script that featured full-screen display. My old "medium-sized" version were only about 600px wide which caused them to luck all ugly after stretching that to modern screen sizes.
--> I created a small script that opens all original images and saves bigger "medium-sized" versions than the once I had.

the problem:
for some reason about 1/3 of all images (not the last third but always the same images) were now labeled as "... is not a valid JPEG file ..." by php

the cause:
still unknown

the solution:
<?php
...
$src_img = @imagecreatefromjpeg($myJPGfile_relative);
if (!
$src_img) {
   
$src_img = LoadJPEG("http://example.com/".$myJPGfile);
}
?>

Each time the local approach fails the script falls back to loading the same file "from the outside" via the below mentioned "LoadJPEG" script - big thanks to the author!
That worked even though I'm talking about the exact same file on the exact same server. The only difference is that one time it's accessed locally and the second via port 80.

when using this, watch for correct paths relative to your script and the possibly different path relative to your domain.
up
0
nico at anvilstudios dot co dot za
6 years ago
I encountered a problem with this function on a windows system. Instead of returning false in case of the file not being a JPG, the function resulted in an error:
"imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error".

To get around this first check whether the file is a JPEG file using its mime type, if it is not return false.
up
0
sales at wholehogsoftware dot com
9 years ago
I've found a bug in CentOS 4.x that, while previously addressed, does not seem to be directly addressed here as far as the nature of the bug is concerned.

If you are having a problem getting this function to work on CentOS 4.4 (may appear earlier) and are receiving this error:

Call to undefined function imagecreatefromjpeg()

This is because the installation *does* support JPG by default if you have libjpeg installed. However, the config script finds libjpeg in /usr/lib but it is never successfully added to the PHP build.

To fix this, you should recompile PHP and be absolutely sure to add '--with-jpeg-dir' to the config command. This should appear BEFORE the --with-gd option. Example:

'--with-jpeg-dir' '--with-gd'

If you don't put it before --with-gd, the option is completely ignored.

As always, be sure to do a 'make clean' before a 'make install'. I made the mistake of forgetting to check and wasted 30 minutes trying to resolve this problem simply because I forgot to clean up after myself previously.
up
0
info at daleconsulting dot com dot au
10 years ago
In a post by Angel Leon, an example script was given that forms a thumbnail gallery using imagecreatefromjpeg.  I am fairly new to php scripts, but I found that the script did not display the table of thumbnail images if the row wasn't "filled" with images.. i.e. if there were 5 images in the folder and the script specified 3 rows in the table, then the page would only display the thumbnails for the first row and only three images were shown.  I found that if you specified the variable row with this equation, then the table would display properly:

$row = intval(count($files)+($row_size-1));

(This is the first line in the createThumbTable function.)
up
0
Anonymous
10 years ago
regarding e dot a dot schultz at gmail dot com post

i tried the script (with the bugfixes posted later) and still got memorytrouble. most often it is still not enough memory to upload big images, even if it seems to calculate right. so this helped my perfectly:

$newLimit = $newLimit+3000000; (before passing it to the ini_set() function).

extremly simple and maybe not the best solution, but it works for now (you sure can give it less than an additional 3mb, just try what works for you).
up
0
ben dot lancaster at design-ontap dot co dot uk
10 years ago
It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path
up
0
webmaster at killer dot com dot ar
10 years ago
The prior script by "e dot a dot schultz at gmail dot com", have a bug

$memoryLimitMB don't have a value

Add
         $memoryLimitMB = 8;
Before
          $memoryLimit = 8 * $MB;
And change that line for:
          $memoryLimit = $memoryLimitMB * $MB;

--------------

Something similar happens with the script by "JohnBrook at pobox dot com"

$memoryLimit don't have a value

Change:

$memoryLimit = $memoryLimit * $MB;

For:
  $memoryLimit = $memoryLimitMB * $MB;
up
0
Christoph Ziegenberg
10 years ago
Matt reported that PHP crashs using imagecreatefromjpeg() - that's true and it took me a lot of time to find the error - but not only the Canon PowerShot S70, also the Canon PowerShot  A400 lets PHP (5.1.2) crash, without any chance to catch it!

So I exclude all Canon PowerShot images with the following check:

    function check_canonpowershot($filename)
    {
        if (strpos(file_get_contents($filename), 'Canon PowerShot') !== false)
        {
            return true;
        }
        return false;
    }
up
0
JohnBrook at pobox dot com
11 years ago
Also, here is the same formula presented in a somewhat more human-readable way, if you'd rather:

<?php
$MB
= Pow(1024,2);   // number of bytes in 1M
$K64 = Pow(2,16);    // number of bytes in 64K
$TWEAKFACTOR = 1.8;   // Or whatever works for you
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                        *
$imageInfo['bits']
                                        *
$imageInfo['channels'] / 8
                         
+ $K64
                       
) * $TWEAKFACTOR
                    
);
$memoryHave = memory_get_usage();
$memoryLimitMB = (integer) ini_get('memory_limit');
$memoryLimit = $memoryLimit * $MB;

if (
function_exists('memory_get_usage')
     &&
$memoryHave + $memoryNeeded > $memoryLimit
  
) {
  
$newLimit = $memoryLimitMB + ceil( ( $memoryHave
                                     
+ $memoryNeeded
                                     
- $memoryLimit
                                     
) / $MB
                                   
);
  
ini_set( 'memory_limit', $newLimit . 'M' );
}
?>
up
0
JohnBrook at pobox dot com
11 years ago
Additional note on allocating memory: The 1.65 in the formula provided below by yaroukh and Karolis is evidently a "fudge factor" arrived at through experimentation. I found that I had to nudge it up a little bit in order to accurately predict the memory that would be needed, otherwise the allocation still failed. In my case, I went right to 1.8 and that has worked so far. Your mileage may vary, so experiment as needed.
up
0
yaroukh at gmail dot com
11 years ago
Hello Karolis

My solution was intended to solve situations when your webhoster puts a limit on the memory usage; in such a situations ini_set doesn't work ofcourse (even for variables that have 'PHP_INI_ALL' flag in a typical PHP-installation).

Have a nice day
  Yaroukh
up
0
Karolis Tamutis karolis.t_AT_gmail.com
11 years ago
In addition to yaroukh at gmail dot com comment.

It seems that even a small image can eat up your default memory limit real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you can change it dynamically using ini_set. Therefore, we can "allocate memory dynamically", to prevent those memory limit exceeded errors.

<?php

$imageInfo
= getimagesize('PATH/TO/YOUR/IMAGE');
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
                   
if (
function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (integer) ini_get('memory_limit') * pow(1024, 2)) {
                       
   
ini_set('memory_limit', (integer) ini_get('memory_limit') + ceil(((memory_get_usage() + $memoryNeeded) - (integer) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
                       
}

?>
up
0
yaroukh at gmail dot com
11 years ago
Estimated memory needed for ImageCreateFromJPEG

First I supposed simple width*height*bpp will be enough, it isn't though; there is some pretty big overhead.

$imageInfo = GetImageSize($imageFilename);
$memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

With memory_limit enabled running out of memory causes script to crash; above written will tel you how much memory you're gonna need for creating an image-resource out of image-file. So in conjunction with Memory_Get_Usage() and Get_CFG_Var('memory_limit') you can avoid the mentioned ending. (Yet there won't be too many images blocked from processing that would still fit in the memory, as the results of this are pretty accurate.)
up
0
dmsales at design-monster dot com
15 years ago
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.
up
0
rodders_plonker at yahoo dot com
16 years ago
To all those having trouble with a message to the effect of:
CreateImageFromJpeg() not supported in this PHP build
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)
up
-2
reorganisation at evo-german dot com
8 months ago
Had to fight with this error message:

imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error

and found, that some picture tools like GIMP are adding EXIF-Informantions about changes.
Those pictures are running in the above problem.

Using an easy picture tool like Windows Paint - save the image new - and imagecreatefromjpeg worked for me.
To Top