Fatal error uncaught error call to undefined function imagecreatefromjpeg in

I’ve searched for this and the solutions provided in past questions are completely incomprehensible to me. Whenever I run functions like imagecreatefromjpeg, I get this: Fatal error: Call to und...

I’ve searched for this and the solutions provided in past questions are completely incomprehensible to me. Whenever I run functions like imagecreatefromjpeg, I get this:

Fatal error: Call to undefined function imagecreatefromjpeg() …

I’m working on a new install of PHP; my last installation never had this problem. I don’t get what’s going on.

TRiG's user avatar

TRiG

9,9927 gold badges57 silver badges106 bronze badges

asked Nov 12, 2012 at 4:21

UserIsCorrupt's user avatar

UserIsCorruptUserIsCorrupt

4,72915 gold badges38 silver badges41 bronze badges

4

answered Nov 12, 2012 at 4:27

admoghal's user avatar

1

In Ubuntu/Mint (Debian based)

$ sudo apt-get install php5-gd

answered Feb 4, 2014 at 14:36

Pierre de LESPINAY's user avatar

5

If you are like me and you are using one of the PHP Docker images as your base, you need to add the gd extension using different instructions then what’s discussed above.

For the php:7.4.1-apache image you need to add in your Dockerfile:

RUN apt-get update && 
    apt-get install -y zlib1g-dev libpng-dev libjpeg-dev

RUN docker-php-ext-configure gd --with-jpeg && 
    docker-php-ext-install gd

These dev packages are needed for compilation of the GD php extension. For me this resulted in activation of GD with PNG and JPEG support in PHP.

answered Jun 18, 2020 at 11:51

Paul's user avatar

PaulPaul

1,24711 silver badges11 bronze badges

2

You can still get Fatal error: Call to undefined function imagecreatefromjpeg() even if GD is installed.

The solution is to install/enable jped lib:

On Ubuntu:

    apt-get install libjpeg-dev
    apt-get install libfreetype6-dev

On CentOS:

    yum install libjpeg-devel
    yum install freetype-devel

If compiling from source add --with-jpeg-dir --with-freetype-dir or --with-jpeg-dir=/usr --with-freetype-dir=/usr.

For more details check https://www.tectut.com/2015/10/solved-call-to-undefined-function-imagecreatefromjpeg/

answered Jan 8, 2018 at 8:06

Mugoma J. Okomba's user avatar

Mugoma J. OkombaMugoma J. Okomba

3,1551 gold badge26 silver badges37 bronze badges

You must enable the library GD2.

Find your (proper) php.ini file

Find the line: ;extension=php_gd2.dll and remove the semicolon in the front.

The line should look like this:

extension=php_gd2.dll

Then restart apache and you should be good to go.

answered Nov 12, 2012 at 4:27

Commander's user avatar

CommanderCommander

1,3121 gold badge13 silver badges29 bronze badges

2

sudo apt-get install phpx.x-gd 
sudo service apache2 restart

x.x is the versión php.

answered Sep 21, 2016 at 9:39

CodeNoob's user avatar

CodeNoobCodeNoob

3354 silver badges17 bronze badges

0

For php 7 on Ubuntu:

sudo apt-get install php7.0-gd

answered May 25, 2017 at 14:17

iKode's user avatar

iKodeiKode

9,02114 gold badges55 silver badges83 bronze badges

After installing php5-gd apache restart is needed.

answered May 31, 2014 at 7:16

Piotr Olaszewski's user avatar

Piotr OlaszewskiPiotr Olaszewski

5,9275 gold badges38 silver badges63 bronze badges

0

In CentOS, RedHat, etc. use below command. don’t forget to restart the Apache. Because the PHP module has to be loaded.

yum -y install php-gd
service httpd restart

answered Aug 12, 2014 at 19:15

Muthukumar Anbalagan's user avatar

I spent so much time trying to figure this out on Windows after installing PHP Version 8.0.11.

I created this phpinfo.php file to check whether GD was loaded:

<?php
if (extension_loaded('gd')) {
  print 'gd loaded';
} else {
  print 'gd NOT loaded';
}

phpinfo(); ?>

If it returns gd NOT loaded then ensure that in your php.ini file you have the following unchecked:

; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
;   extension folders as well as the separate PECL DLL download (PHP 5+).
;   Be sure to appropriately set the extension_dir directive.
;
extension=gd

Further down they’ll be a section for extension_dir on Windows you need to uncheck the following:

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
;extension_dir = "./"
; On windows:
extension_dir = "ext"

You should now see gd loaded when running the phpinfo.php file and any function calls (like imagecreatefromjpeg()) should now work as intended.

answered Sep 28, 2021 at 5:14

fulvio's user avatar

fulviofulvio

26.1k22 gold badges135 silver badges203 bronze badges

1

As mentioned before, you might need GD library installed.

On a shell, check your php version first:
php -v

Then install accordingly. In my system (Linux-Ubuntu) it’s php version 7.0:
sudo apt-get install php7.0-gd

Restart your webserver:
systemctl restart apache2

You should now have GD library installed and enabled.

answered Apr 18, 2020 at 18:51

arakno's user avatar

araknoarakno

4283 silver badges6 bronze badges

after

systemctl restart php-fpm
the Gd library works.

answered Feb 26, 2020 at 23:11

Tktongmaicom Tkt's user avatar

I am replying in 2022, anyone still facing this problem may my answer helpful. If your PHP version,n is 8+ you can add the below line to your php.ini file which is located in the PHP folder.

extension=php_gd.dll

answered Aug 18, 2022 at 6:16

Pisumathu's user avatar

PisumathuPisumathu

4121 gold badge5 silver badges8 bronze badges

I have managed to fix this problem by doing the following:

  1. Find out which version of php you are running by typing this into the terminal:

php --version

My PHP version was 7.4:

PHP 7.4.3 (cli) (built: Nov  2 2022 09:53:44) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies
  1. Install php-7.4-gd

sudo apt-get install php7.4-gd

  1. Restart Apache

systemctl restart apache2

answered Jan 15 at 18:23

George Chalhoub's user avatar

George ChalhoubGeorge Chalhoub

13.9k3 gold badges36 silver badges60 bronze badges

Содержание

  1. Fix – Fatal error: Call to undefined function imagecreatefromjpeg.
  2. Enabling the GD library on Ubuntu / Mint (Debian) servers.
  3. PHP 5.
  4. PHP 7.0
  5. PHP 7.1
  6. Installing GD for PHP 7.2
  7. PHP 7.3
  8. PHP 7.4
  9. PHP 8.
  10. Make sure that you restart your web server.
  11. Enabling PHP GD on Windows.
  12. PHP 8 & GD on Windows.
  13. imagecreatefromjpeg
  14. Описание
  15. Список параметров
  16. Возвращаемые значения
  17. Список изменений
  18. Примеры
  19. User Contributed Notes 34 notes
  20. Solved – Call to undefined function imagecreatefromjpeg
  21. (01) Install libjpeg and freetype
  22. (02) Configure and compile php
  23. (03) Restart Apache

Fix – Fatal error: Call to undefined function imagecreatefromjpeg.

In this guide, we will show you how to fix the following PHP error:

Fatal error: Call to undefined function imagecreatefromjpeg

The fatal error above means that PHP’s GD library has not been installed or enabled. As a result, PHP is unable to find the function imagecreatefromjpeg.

Unfortunately, the GD library is not enabled by default.

As a result, you might run into fatal errors when you attempt to deploy image manipulation functions to a fresh PHP install. Other functions from the library, such as imagecreate and imagecreatefrompng, will also cause the exact same error.

Enabling the GD library on Ubuntu / Mint (Debian) servers.

If you’re running PHP on Ubuntu or Mint, then you can run one of the following commands.

Please note that you will need to know your PHP version before you attempt to run any of these.

PHP 5.

PHP 7.0

With PHP 7 and above, it gets a little trickier. This is because you must use the minor release number as well.

PHP 7.1

Installing GD for PHP 7.2

PHP 7.3

PHP 7.4

As you can see, with PHP 7, you have to specify the exact version that you are using.

PHP 8.

The same goes for PHP 8. For example, if you are using PHP 8.0, then you can use the following command.

For 8.1, you will need to use “php8.1-gd”, and so on.

Make sure that you restart your web server.

Once you have installed the library, make sure that you restart Apache or Nginx for the changes to take effect.

Enabling PHP GD on Windows.

On Windows, you will need to locate your php.ini file and uncomment the following line:

To uncomment the line above, simply remove the semi-colon from the beginning. Once that is done, save the file and then restart your web server.

PHP 8 & GD on Windows.

If you are using GD with PHP 8 on Windows, then you should be aware that the extension is now called php_gd.dll.

In other words, they have taken the “2” out of it.

Источник

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromjpeg — Создаёт новое изображение из файла или URL

Описание

imagecreatefromjpeg() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.

Список параметров

Путь к JPEG картинке.

Возвращаемые значения

Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Версия Описание
8.0.0 В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).

Примеры

Пример #1 Пример обработки ошибки при загрузке JPEG

function LoadJpeg ( $imgname )
<
/* Пытаемся открыть */
$im = @ imagecreatefromjpeg ( $imgname );

/* Если не удалось */
if(! $im )
<
/* Создаём пустое изображение */
$im = imagecreatetruecolor ( 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 , ‘Ошибка загрузки ‘ . $imgname , $tc );
>

header ( ‘Content-Type: image/jpeg’ );

$img = LoadJpeg ( ‘bogus.image’ );

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

Результатом выполнения данного примера будет что-то подобное:

User Contributed Notes 34 notes

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.

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 ;
>
?>

This little function allows you to create an image based on the popular image types without worrying about what it is:

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 ;
>
?>

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-

.
$image = @ ImageCreateFromJpeg ( $image_name );
if (! $image )
<
$image = imagecreatefromstring ( file_get_contents ( $image_name ));
>
.
?>

In PHP 8, you can create an image based on the popular image types without worrying about what it is:

function imageCreateFromAny ( $filepath ): ? GdImage <
return match ( exif_imagetype ( $filepath )) <
// gif
1 => imageCreateFromGif ( $filepath ),
// jpg
2 => imageCreateFromJpeg ( $filepath ),
// png
3 => imageCreateFromPng ( $filepath ),
// bmp
6 => imageCreateFromBmp ( $filepath ),
// not defined
default => null ,
>;
>
?>

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)) )
fclose($fd);
return false;
>
>else
>else <
return false;
>
>

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.

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.

= 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’ );

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:
( «/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.

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

// $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 )
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» );

Источник

Solved – Call to undefined function imagecreatefromjpeg

Even if you are installed php with gd, error message ” undefined function imagecreatefromjpeg () ” may appear on php. specifically when installing fresh opencart web application you may definitely face this issue as I did. In Opencart installation process, installer itself checks whether gd is installed, but unfortunately not identify the other important packages such as libJPEG and libPNG are installed or not. Here is how I fixed the that error on Centos.

Error!

Fatal error: Call to undefined function imagecreatefromjpeg() in /../library/image.php on line 34

(01) Install libjpeg and freetype

Centos :-
yum install libjpeg-devel
yum install freetype-devel

For Ubuntu :-
apt-get install libjpeg-dev
apt-get install libfreetype6-dev

(02) Configure and compile php

make clean
make distclean

***you must clean the php before configuring*
When compile gd extension, use the flag –with-jpeg-dir and –with-freetype-dir

no need to define directory(DIR) location of each flag if you are installed libjpeg and freetype using yum commands, otherwise it may be need to set DIR
location of each.

example php configuration
./configure –with-gd –with-jpeg-dir –with-freetype-dir

(03) Restart Apache

below is the sample output of php info file after successful installation.

Источник

In this guide, we will show you how to fix the following PHP error:

Fatal error: Call to undefined function imagecreatefromjpeg

The fatal error above means that PHP’s GD library has not been installed or enabled. As a result, PHP is unable to find the function imagecreatefromjpeg.

Unfortunately, the GD library is not enabled by default.

As a result, you might run into fatal errors when you attempt to deploy image manipulation functions to a fresh PHP install. Other functions from the library, such as imagecreate and imagecreatefrompng, will also cause the exact same error.

Enabling the GD library on Ubuntu / Mint (Debian) servers.

If you’re running PHP on Ubuntu or Mint, then you can run one of the following commands.

Please note that you will need to know your PHP version before you attempt to run any of these.

PHP 5.

sudo apt-get install php5-gd

PHP 7.0

With PHP 7 and above, it gets a little trickier. This is because you must use the minor release number as well.

sudo apt-get install php7.0-gd

PHP 7.1

sudo apt-get install php7.1-gd

Installing GD for PHP 7.2

sudo apt-get install php7.2-gd

PHP 7.3

sudo apt-get install php7.3-gd

PHP 7.4

sudo apt-get install php7.4-gd

As you can see, with PHP 7, you have to specify the exact version that you are using.

PHP 8.

The same goes for PHP 8. For example, if you are using PHP 8.0, then you can use the following command.

sudo apt install php8.0-gd

For 8.1, you will need to use “php8.1-gd”, and so on.

Make sure that you restart your web server.

Once you have installed the library, make sure that you restart Apache or Nginx for the changes to take effect.

Enabling PHP GD on Windows.

On Windows, you will need to locate your php.ini file and uncomment the following line:

;extension=php_gd2.dll

To uncomment the line above, simply remove the semi-colon from the beginning. Once that is done, save the file and then restart your web server.

PHP 8 & GD on Windows.

If you are using GD with PHP 8 on Windows, then you should be aware that the extension is now called php_gd.dll.

In other words, they have taken the “2” out of it.

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromjpegСоздаёт новое изображение из файла или URL

Описание

imagecreatefromjpeg(string $filename): GdImage|false

Подсказка

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen(). Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.

Список параметров

filename

Путь к JPEG картинке.

Возвращаемые значения

Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Версия Описание
8.0.0 В случае успешного выполнения функция теперь возвращает экземпляр GDImage;
ранее возвращался ресурс (resource).

Примеры

Пример #1 Пример обработки ошибки при загрузке JPEG


<?php
function LoadJpeg($imgname)
{
/* Пытаемся открыть */
$im = @imagecreatefromjpeg($imgname);/* Если не удалось */
if(!$im)
{
/* Создаём пустое изображение */
$im = imagecreatetruecolor(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, 'Ошибка загрузки ' . $imgname, $tc);
}

return

$im;
}
header('Content-Type: image/jpeg');$img = LoadJpeg('bogus.image');imagejpeg($img);
imagedestroy($img);
?>

Результатом выполнения данного примера
будет что-то подобное:

jan at recreatie-zorg dot nl

9 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;
    }
?>


matt dot squirrell dot php at hsmx dot com

10 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

}

?>


sagarsdeshmukh91 at gmail dot com

6 years 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));
}
...
?>


matthieu dot poignant+php at gmail dot com

1 year ago


In PHP 8, you can create an image based on the popular image types without worrying about what it is:

<?php
function imageCreateFromAny($filepath): ?GdImage {
    return
match (exif_imagetype($filepath)) {
       
// gif
       
1 => imageCreateFromGif($filepath),
       
// jpg
       
2 => imageCreateFromJpeg($filepath),
       
// png
       
3 => imageCreateFromPng($filepath),
       
// bmp
       
6 => imageCreateFromBmp($filepath),
       
// not defined
       
default => null,
    };
}
?>


willertan1980 at yahoo dot com

19 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;
    }
}


hvozda at ack dot org

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


Karolis Tamutis karolis.t_AT_gmail.com

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

                        }

?>


anatol at nugob dot org

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


brentwientjes at NOSPAM dot comcast dot net

12 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);  //  resampleimagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
  
imagejpeg($img_dst, $new_img);    //  save new imageunlink($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");?>


sales at wholehogsoftware dot com

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


e dot a dot schultz at gmail dot com

16 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;
    }
}
?>


Jrn Berkefeld

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


bpiere21 at hotmail dot com

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


juozaspo at gmail dot com

12 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);
}   ?>


huguowen at cn dot ibm dot com

15 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!


dmhouse at gmail dot com

15 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

"nn";

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


Anonymous

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


yaroukh at gmail dot com

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


Ray.Paseur sometimes uses Gmail

12 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

?>


info at daleconsulting dot com dot au

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


ben dot lancaster at design-ontap dot co dot uk

16 years ago


It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path

Christoph Ziegenberg

16 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;
    }


JohnBrook at pobox dot com

16 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' );
}
?>


JohnBrook at pobox dot com

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

linus at flowingcreativity dot net

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


ceefour -at!- gauldong.net

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


dmsales at design-monster dot com

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


rodders_plonker at yahoo dot com

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

webmaster at killer dot com dot ar

16 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;


yaroukh at gmail dot com

17 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


nico at anvilstudios dot co dot za

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


pavel.lint at vk.com

10 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" );
?>


cs at kainaw dot com

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

reorganisation at evo-german dot com

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


Same issue as #926 (comment)
The order of docker-php-ext-configure gd matters (I don’t know why) and your duplicate docker-php-ext-install zip went before gd so it installed with different parameters

I moved your apt-get clean to be in the same layer as the install, otherwise it does nothing to the image size

Dockerfile

FROM php:7.4.1-apache

RUN apt-get update && apt-get install -y --no-install-recommends 
  autoconf 
  build-essential 
  apt-utils 
  zlib1g-dev 
  libzip-dev 
  unzip 
  zip 
  libmagick++-dev 
  libmagickwand-dev 
  libpq-dev 
  libfreetype6-dev 
  libjpeg62-turbo-dev 
  libpng-dev 
  libonig-dev && 
  apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

# RUN docker-php-ext-configure gd 
#   --with-png-dir=/usr/include/ 
#   --with-jpeg-dir=/usr/include/ 
#   --with-freetype-dir=/usr/include/

RUN docker-php-ext-configure gd --with-freetype --with-jpeg=/usr/include/ --enable-gd

RUN docker-php-ext-install gd intl pdo_mysql pdo_pgsql mysqli zip

RUN pecl install imagick-3.4.3

RUN pecl install xdebug && docker-php-ext-enable xdebug

RUN docker-php-ext-enable imagick

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Permissions
RUN chown -R root:www-data /var/www/html
RUN chmod u+rwx,g+rx,o+rx /var/www/html
RUN find /var/www/html -type d -exec chmod u+rwx,g+rx,o+rx {} +
RUN find /var/www/html -type f -exec chmod u+rw,g+rw,o+r {} +

WORKDIR /var/www/html

RUN a2enmod rewrite
RUN a2enmod ssl

EXPOSE 80
EXPOSE 443
EXPOSE 587

docker build

$ docker build . -t php:test
Sending build context to Docker daemon  3.072kB
Step 1/18 : FROM php:7.4.1-apache
 ---> 0c37fe4343a5
Step 2/18 : RUN apt-get update && apt-get install -y --no-install-recommends   autoconf   build-essential   apt-utils   zlib1g-dev   libzip-dev   unzip   zip   libmagick++-dev   libmagickwand-dev   libpq-dev   libfreetype6-dev   libjpeg62-turbo-dev   libpng-dev   libonig-dev &&   apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
 ---> Using cache
 ---> 6e9d771b5d62
Step 3/18 : RUN docker-php-ext-configure gd --with-freetype --with-jpeg=/usr/include/ --enable-gd
 ---> Using cache
 ---> 7811ef3d4447
Step 4/18 : RUN docker-php-ext-install gd intl pdo_mysql pdo_pgsql mysqli zip
 ---> Using cache
 ---> 15852a3cdd6f
Step 5/18 : RUN pecl install imagick-3.4.3
 ---> Using cache
 ---> bf38f2fc388a
Step 6/18 : RUN pecl install xdebug && docker-php-ext-enable xdebug
 ---> Using cache
 ---> 2e288cc438cc
Step 7/18 : RUN docker-php-ext-enable imagick
 ---> Using cache
 ---> 0d9565a29625
Step 8/18 : RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
 ---> Using cache
 ---> 0e536a390eaf
Step 9/18 : RUN chown -R root:www-data /var/www/html
 ---> Using cache
 ---> 4b2bf97f6f9f
Step 10/18 : RUN chmod u+rwx,g+rx,o+rx /var/www/html
 ---> Using cache
 ---> 9e03c9e1c607
Step 11/18 : RUN find /var/www/html -type d -exec chmod u+rwx,g+rx,o+rx {} +
 ---> Using cache
 ---> 48fa53c87ac5
Step 12/18 : RUN find /var/www/html -type f -exec chmod u+rw,g+rw,o+r {} +
 ---> Using cache
 ---> 3d61b6c3f1e8
Step 13/18 : WORKDIR /var/www/html
 ---> Using cache
 ---> e6fd15f80c02
Step 14/18 : RUN a2enmod rewrite
 ---> Using cache
 ---> f8f56c4fba27
Step 15/18 : RUN a2enmod ssl
 ---> Using cache
 ---> 82b3ce782d6c
Step 16/18 : EXPOSE 80
 ---> Using cache
 ---> 0ac5de23b494
Step 17/18 : EXPOSE 443
 ---> Using cache
 ---> 8098ccd1ca0b
Step 18/18 : EXPOSE 587
 ---> Using cache
 ---> dccf94427423
Successfully built dccf94427423
Successfully tagged php:test
$ docker run -it --rm php:test php -r 'print_r(gd_info());'
Array
(
    [GD Version] => bundled (2.1.0 compatible)
    [FreeType Support] => 1
    [FreeType Linkage] => with freetype
    [GIF Read Support] => 1
    [GIF Create Support] => 1
    [JPEG Support] => 1
    [PNG Support] => 1
    [WBMP Support] => 1
    [XPM Support] => 
    [XBM Support] => 1
    [WebP Support] => 
    [BMP Support] => 1
    [TGA Read Support] => 1
    [JIS-mapped Japanese Font Support] => 
)

  • #1

Не поддерживаетя функция ImageCreateFromJpeg()

Не поддерживаетя функция:
Fatal error: Call to undefined function ImageCreateFromJpeg() in /var/www/User5/data/modules/catalog/admin/class.katalog.php on line 374
Идем далее:
C трудом, создавая пути /usr/local/jpeg-6b/bin & /usr/local/jpeg-6b/man компилирую
make
make install

Далее скачиваю и конфигурирую gd

http://www.boutell.com/gd/
./configure —prefix=/usr/local/gd —with-jpeg=/usr/local/jpeg-6b

вот такой вот неутешающий результат:

Support for PNG library: no
Support for JPEG library: no
Support for Freetype 2.x library: no
Support for Fontconfig library: no
Support for Xpm library: no
Support for pthreads: yes

не поддерживает jpeg, что делать?

  • #2

libgd есть в php (ext/gd/libgd). Надо только —with-jpeg-dir в configure для php.

  • #3

Скачал с ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz
пеконфигурировал PHP с

‘./configure’ ‘—with-apxs=/usr/local/apache/bin/apxs’ ‘—with-libxml-dir=/usr/local/libxml’ ‘—with-xsl=/usr/local/libxslt’ ‘—with-iconv=/usr/local/iconv’ ‘—enable-track-vars’ ‘—enable-mod_charset’ ‘—with-dom’ ‘—with-dom-xslt’ ‘—with-dom-exslt’ ‘—with-mysql=/usr/local/mysql’ ‘—prefix=/usr/local/php5’ ‘—with-jpeg-dir=/usr/local’

ошибка как была так и осталась
Fatal error: Call to undefined function ImageCreateFromJpeg() in /var/www/User5/data/modules/catalog/admin/class.katalog.php on line 374

Что посоветуете?
Спасибо

  • #4

make clean
configure … —with-gd
make

в config.log найти jpeg и посмотреть что не нравиться

  • #5

при configure не может найти libjpeg, хотя как писал выше скачал ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz и просто установил в /usr/local/
./prefix=/usr/local
make
make install
все нормально прошло

потом
./configure —with-apxs=/usr/local/apache/bin/apxs —with-libxml-dir=/usr/local/libxml —with-xsl=/usr/local/libxslt —with-iconv=/usr/local/iconv —enable-track-vars —enable-mod_charset —with-dom —with-dom-xslt —with-dom-exslt —with-mysql=/usr/local/mysql —prefix=/usr/local/php5 —with-jpeg-dir=/usr/local/bin —with-gd

configure: error: libjpeg.(a|so) not found.

  • #6

Почему —with-jpeg-dir=/usr/local/bin, надо указать -with-jpeg-dir=/usr/local или -with-jpeg-dir=/usr/local/jpeg-6b, тот каталог в котором есть libjpeg.so

  • #7

надо указывать ПРЕФИКС того места, где лежат хидеры и либы.

  • #8

А нет libjpeg.so, вот что есть:

/usr/bin/install -c cjpeg /usr/local/jpeg-6b/bin/cjpeg
/usr/bin/install -c djpeg /usr/local/jpeg-6b/bin/djpeg
/usr/bin/install -c jpegtran /usr/local/jpeg-6b/bin/jpegtran
/usr/bin/install -c rdjpgcom /usr/local/jpeg-6b/bin/rdjpgcom
/usr/bin/install -c wrjpgcom /usr/local/jpeg-6b/bin/wrjpgcom
/usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/jpeg-6b/man/man1/cjpeg.1
/usr/bin/install -c -m 644 ./djpeg.1 /usr/local/jpeg-6b/man/man1/djpeg.1
/usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/jpeg-6b/man/man1/jpegtran.1
/usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/jpeg-6b/man/man1/rdjpgcom.1
/usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/jpeg-6b/man/man1/wrjpgcom.1

  • #9

очевидно, что это не тот пакет, который тебе нужен.

  • #11

Скомпилировал jpeg-6b, получил libjpeg.a

/usr/local/jpeg-6b/lib/libjpeg.a

Указываю:
hosting# ./configure —with-apxs=/usr/local/apache/bin/apxs —with-libxml-dir=/usr/local/libxml —with-xsl=/usr/local/libxslt —with-iconv=/usr/local/iconv —enable-track-vars —enable-mod_charset —with-dom —with-dom-xslt —with-dom-exslt —with-mysql=/usr/local/mysql —prefix=/usr/local/php5 —with-gd —with-jpeg-dir=/usr/local/jpeg-6b/lib

и все равно не видит
configure: error: libjpeg.(a|so) not found.

  • #13

Спасибо, остался один вопрос.
Я скачал gd-2.0.33 и скомпилировал с поддержкой with-jpeg-dir=/usr/local/jpeg-6b

Support for PNG library: no
Support for JPEG library: yes
Support for Freetype 2.x library: no
Support for Fontconfig library: no
Support for Xpm library: no
Support for pthreads: yes

Потом при конфигурировании php просо указал —with-gd=/usr/local/gd, но не указывал with-jpeg-dir=/usr/local/jpeg-6b

make
make install

установил, в связисчем вопрос, как-то отличаются функции из вcтроенного модуля gd и пакета gd который установил я?

  • #14

да, конечно.
старый GD достаточно хреново поддерживался автором, поэтому в bundled больше фиксов и он более приспособлен к PHP.
поэтому он и рекомендуется к использованию.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error uncaught error call to undefined function ereg in
  • Fatal error uncaught error call to undefined function each
  • Fatal error uncaught error call to a member function setpageproperty
  • Fatal error uncaught error call to a member function fetch on boolean in
  • Fatal error uncaught error array callback has to contain indices 0 and 1

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии