Fatal error uncaught error call to undefined function imagecreate

I'm trying to put some graphics on a web page and at my prototype at the computer it's all working fine at the localhost. But now I uploaded the files to a server and I'm having a problem to plot s...

I’m trying to put some graphics on a web page and at my prototype at the computer it’s all working fine at the localhost. But now I uploaded the files to a server and I’m having a problem to plot some graphics. In my computer they are plotted, but on the server they are not.

I’m getting this error
Fatal error: Call to undefined function ImageCreate() in /home/t1g01/phplot.php on line 248

Line 248

$this->img = ImageCreate($this->image_width, $this->image_height);

I’m using phplot, and I uploaded the files form phplot too. Can anyone help me ?

Sorry for any mistake in English and thank you in advance.

asked Jun 24, 2010 at 3:09

Marcelo's user avatar

If you are using a Linux machine then execute this command from console:

sudo apt-get install php5-gd

to install the php_gd2.dll extension. It will then work after an Apache restart.

PS: should first check your current php version

php -v

In My Case:

PHP 7.3.5-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: May 3 2019
10:00:24) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine
v3.3.5, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache
v7.3.5-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by
Zend Technologies

So, my PHP version is 7.3, so, the command for my version is :

sudo apt-get install php7.3-gd

Diego Favero's user avatar

Diego Favero

1,8412 gold badges22 silver badges32 bronze badges

answered Mar 29, 2014 at 11:23

Jonathan Gurebo's user avatar

Jonathan GureboJonathan Gurebo

1,0891 gold badge11 silver badges21 bronze badges

4

Your server most like does not have GD (the built in PHP image processing library) enabled. You can check this by looking for «GD» in the output of :

<?php
phpinfo();
?>

If not, check the PHP docs on how to enable it: http://www.php.net/manual/en/book.image.php

answered Jun 24, 2010 at 3:12

Mike Sherov's user avatar

Mike SherovMike Sherov

13.2k8 gold badges41 silver badges62 bronze badges

For Fedora, CentOS

dnf install php-gd
systemctl restart httpd.service

On Ubuntu

apt-cache search php*-gd
apt-get install php<version>-gd
systemctl restart apache2.service

Windows users see: http://php.net/manual/en/image.installation.php

answered Jun 17, 2016 at 17:57

Gayan Weerakutti's user avatar

Gayan WeerakuttiGayan Weerakutti

11.1k1 gold badge67 silver badges66 bronze badges

  1. Copy the file php_gd2.dll from your PHP’s ext/ directory to where
    you have your php extensions. (No need to copy if php_gd2.dll is in the extension
    dir already. Look in php.ini for ‘extension_dir’ directive to
    find what is your current extension directory)

  2. Modify your php.ini and change the following line:

;extension=php_gd2.dll

to:

extension=php_gd2.dll

John Conde's user avatar

John Conde

216k98 gold badges453 silver badges495 bronze badges

answered Mar 26, 2012 at 8:28

mymahdi's user avatar

It seems that your GD library is not being used. Double check your php.ini file.

answered Jun 24, 2010 at 3:11

Russell Dias's user avatar

Russell DiasRussell Dias

69.7k5 gold badges52 silver badges71 bronze badges

for any php version the command for ubuntu installation is

apt-get install php-gd

it will install the version that matches your php version, and it will be later updated with you php version.

answered Jul 7, 2020 at 12:57

Oleksandr Grin's user avatar

Oleksandr GrinOleksandr Grin

6531 gold badge8 silver badges12 bronze badges

I know this is an old thread but I’ve just recently came across this same Fatal error: Call to undefined function: imagecreate() issue while doing some QR coding using a fresh Xampp install on Windows.

I resolved the issue by first looking in the php.ini file for the GD extension and fixed the issue by uncommenting
;extension=gd

Afterwards QR code was generated to the browser as expected.

NOTE: Don’t forget to restart Apache to make the change stick.

answered Jul 26, 2021 at 5:12

kwaka's user avatar

kwakakwaka

213 bronze badges

For Ubuntu 16.04:

sudo apt-get install php7.0-gd

Stop and then restart Apache Server.

PS: should first check your current php version

php -v

In My Case:

PHP 7.3.5-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: May 3 2019
10:00:24) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine
v3.3.5, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.5-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

So, my PHP version is 7.3, so, the command for my version is :

sudo apt-get install php7.3-gd

Diego Favero's user avatar

Diego Favero

1,8412 gold badges22 silver badges32 bronze badges

answered Feb 20, 2018 at 9:48

Abdul Rahman's user avatar

Abdul RahmanAbdul Rahman

1,6393 gold badges24 silver badges38 bronze badges

Update for PHP 7.4.0 >

You should not install any external libraries !

As stated in PHP docs:

As of PHP 7.4.0, —with-png-dir and —with-zlib-dir have been removed. libpng and zlib are required.

PHP 7.4.0 and newer versions comes bundled with libpng and zlib by default.

So all you merely need to do is to uncomment gd extension in php.ini file:

;extension=gd -> extension=gd

Problem solved :)

answered Jan 11 at 22:53

Urax's user avatar

UraxUrax

688 bronze badges

Dont forget restart apache or php-fpm if not running after installation

answered Feb 19, 2022 at 13:47

Muhammad Hafid's user avatar

1

Рекурсивный акроним словосочетания «PHP: Hypertext Preprocessor»
Добро пожаловать на форум PHP программистов!

Главная
Документация
Новости
Форум

За последние 24 часа нас посетили 11467 программистов и 1168 роботов. Сейчас ищут 307 программистов …

Fatal error: Call to undefined function imagecreate()

Тема в разделе «PHP для новичков», создана пользователем dio4, 22 июл 2008.


  1. dio4

    dio4
    Guest

    Добрый день! У меня php 5.2.1, ОС Ubuntu 7.04(со всеми последними обновлениями). При обращении к функции imagecreate в куске кода
    <?php
    $height = 200;
    $width = 200;
    $im = imagecreate($width, $height);
    выдается ошибка: Fatal error: Call to undefined function imagecreate()
    кроме того, при вводе в командной строке #root@ubuntu:/var/www# php —rf imagecreate получаю —
    Exception: Function imagecreate() does not exist
    а у товарища вывод выглядит так:
    #php —rf imagecreate
    Function [ <internal:gd> function imagecreate ] {

    — Parameters [2] {
    Parameter #0 [ <required> $x_size ]
    Parameter #1 [ <required> $y_size ]
    }
    }
    помогите разобраться в чем дело. Спасибо заранее.

    #1


    dio4,

    22 июл 2008


  2. Cron

    Cron
    Активный пользователь

    С нами с:
    10 июл 2008
    Сообщения:
    289
    Симпатии:
    0
    Адрес:
    Украина, Сумы

    посмотри phpinfo() поддержка gd2 включена?

    #2


    Cron,

    22 июл 2008


  3. dio4

    dio4
    Guest

    Может вы сразу подскажете где она должна включаться, а я проверю? Спасибо.

    #3


    dio4,

    22 июл 2008


  4. Cron

    Cron
    Активный пользователь

    С нами с:
    10 июл 2008
    Сообщения:
    289
    Симпатии:
    0
    Адрес:
    Украина, Сумы

    в php.ini должны быть раскомментированы extension=php_gd2.dll

    #4


    Cron,

    22 июл 2008


  5. dio4

    dio4
    Guest

    ну, в линуксе явно не может быть никаких .dll это уж точно. Но я посмотрел, ничего похожего нет. Есть только строка, касаемая gd:
    [gd]
    ; Tell the jpeg decode to libjpeg warnings and try to create
    ; a gd image. The warning will then be displayed as notices
    ; disabled by default
    ;gd.jpeg_ignore_warning = 0
    Это все :)

    #5


    dio4,

    22 июл 2008


  6. Sergey89

    Sergey89
    Активный пользователь

    С нами с:
    4 янв 2007
    Сообщения:
    4.796
    Симпатии:
    0

    Код (Text):
    1. apt-get install php-gd2

    #6


    Sergey89,

    22 июл 2008


  7. dio4

    dio4
    Guest

    Для Sergey89: вы совершенно правы :), только не php-gd2, а php5-gd. Все заработало. Спасибо всем, а Sergey89 особенно. :)

    #7


    dio4,

    22 июл 2008


  8. dio4

    dio4
    Guest

    теперь вот что вижу :
    root@ubuntu:~# php —rf imagecreate
    Function [ <internal> public function imagecreate ] {

    — Parameters [2] {
    Parameter #0 [ <required> $x_size ]
    Parameter #1 [ <required> $y_size ]
    }
    }

    #8


    dio4,

    22 июл 2008

(Вы должны войти или зарегистрироваться, чтобы разместить сообщение.)

Показать игнорируемое содержимое

Ваше имя или e-mail:
У Вас уже есть учётная запись?
  • Нет, зарегистрироваться сейчас.
  • Да, мой пароль:
  • Забыли пароль?

Запомнить меня

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

imagecreateCreate a new palette based image

Description

imagecreate(int $width, int $height): GdImage|false

In general, we recommend the use of
imagecreatetruecolor() instead of
imagecreate() so that image processing occurs on the
highest quality image possible. If you want to output a palette image, then
imagetruecolortopalette() should be called immediately
before saving the image with imagepng() or
imagegif().

Parameters

width

The image width.

height

The image height.

Return Values

Returns an image object on success, false on errors.

Changelog

Version Description
8.0.0 On success, this function returns a GDImage instance now;
previously, a resource was returned.

Examples

Example #1
Creating a new GD image stream and outputting an image.


<?php
header
("Content-Type: image/png");
$im = @imagecreate(110, 20)
or die(
"Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

The above example will output
something similar to:

See Also

  • imagedestroy() — Destroy an image
  • imagecreatetruecolor() — Create a new true color image

DHKold

17 years ago


to create an image from a BMP file, I made this function, that return a resource like the others ImageCreateFrom function:

<?php
/*********************************************/
/* Fonction: ImageCreateFromBMP              */
/* Author:   DHKold                          */
/* Contact:  admin@dhkold.com                */
/* Date:     The 15th of June 2005           */
/* Version:  2.0B                            */
/*********************************************/
function ImageCreateFromBMP($filename)
{
//Ouverture du fichier en mode binaire
  
if (! $f1 = fopen($filename,"rb")) return FALSE;//1 : Chargement des ent?tes FICHIER
  
$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if (
$FILE['file_type'] != 19778) return FALSE;//2 : Chargement des ent?tes BMP
  
$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
  
$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if (
$BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
  
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
  
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
  
$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
  
$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
  
$BMP['decal'] = 4-(4*$BMP['decal']);
   if (
$BMP['decal'] == 4) $BMP['decal'] = 0;//3 : Chargement des couleurs de la palette
  
$PALETTE = array();
   if (
$BMP['colors'] < 16777216)
   {
   
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }
//4 : Cr?ation de l'image
  
$IMG = fread($f1,$BMP['size_bitmap']);
  
$VIDE = chr(0);$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
  
$P = 0;
  
$Y = $BMP['height']-1;
   while (
$Y >= 0)
   {
   
$X=0;
    while (
$X < $BMP['width'])
    {
     if (
$BMP['bits_per_pixel'] == 24)
       
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
     elseif (
$BMP['bits_per_pixel'] == 16)
     { 
       
$COLOR = unpack("n",substr($IMG,$P,2));
       
$COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif (
$BMP['bits_per_pixel'] == 8)
     { 
       
$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
       
$COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif (
$BMP['bits_per_pixel'] == 4)
     {
       
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if ((
$P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
       
$COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif (
$BMP['bits_per_pixel'] == 1)
     {
       
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if     ((
$P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
        elseif ((
$P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
        elseif ((
$P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
        elseif ((
$P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
        elseif ((
$P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
        elseif ((
$P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
        elseif ((
$P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
        elseif ((
$P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
       
$COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     else
        return
FALSE;
    
imagesetpixel($res,$X,$Y,$COLOR[1]);
    
$X++;
    
$P += $BMP['bytes_per_pixel'];
    }
   
$Y--;
   
$P+=$BMP['decal'];
   }
//Fermeture du fichier
  
fclose($f1);

return

$res;
}
?>


Sohel Taslim

15 years ago


It is easy and simple example to convert Text to Image with selected font.
It helps me to display Bangla text as image when users have no installed bangla font.

I hope it can help you too!

<?php
//Kip the font file together or write proper location.
makeImageF("Life in PHP.","CENTURY.TTF");

function

makeImageF($text, $font="CENTURY.TTF", $W=200, $H=20, $X=0, $Y=0, $fsize=18, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){$im = @imagecreate($W, $H)
        or die(
"Cannot Initialize new GD image stream");$background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
   
$text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.imagettftext($im, $fsize, $X, $Y, $fsize, $text_color, $font, $text);header("Content-type: image/gif");               
    return
imagegif($im);
}
?>


wouter at rusman dot net

21 years ago


to compile GD support on some linux distributions you have to include these with the ./configure command :

--with=gd=/usr --with-jpeg=/usr --with-png=/usr --with-zlib=/usr

(i had to include this on Redhat 6.1)

this becase the libraries are in /usr/lib instead of /lib


tore at kyberheimen dot com

20 years ago


GD UPGRADE PROBLEM:
I used imagecreate with gd 1.6 to make resized images of big photos. Then, when using the same script on gd 2.0, the colors got all wrong.
Using imagecreatetruecolor() fixed the problem!

php at silisoftware dot com

20 years ago


Don't try and create an image with a really large width and/or height. First, $width x $height is (at least) the bytes of memory that need to be allocated. Secondly, if you exceed the range of int for either parameter, Apache crashes (before allocating any memory).
Don't ask how I figured this out ;)

altype at bellsouth dot net

21 years ago


ImagePNG($pic,"./dir/pic.png");

To save image as a file, I had to create a directory "dir" and CHMOD 777 to give read, write, and execute permission for everyone - or it wouldn't save it...


robert at scpallas dot de

21 years ago


The function ImageCreate() creates a PALETTE image.
The function ImageCreateFromJPEG() creates a TRUE COLOR image.

When you use GD 2.0 you will get an error when you try to use ImageCopy()
with one True color image and one Palette image.

Be sure to convert one of the images before using ImageCopy() or use ImageCreateTrueColor() instead of ImageCreate().


JamesM

12 years ago


doesnt ruin the image but adds display to the output.
this will generate an image with a random color. if you like it you can use it because you have the RBG result too.
<?php
header
("content-type:image/png");
$im = imagecreate(100, 100);
$a = sprintf('%04x',mt_rand(0, 65535));
$b = sprintf('%04x',mt_rand(0, 65535));
$c = sprintf('%04x',mt_rand(0, 65535));
$white = imagecolorallocate($im,$a,$b,$c);
imagepng($im);
imagedestroy($im);
echo
"nnn$a-$b-$c";
?>

kim at kimmccall dot org

22 years ago


How I fixed my "undefined function imagecreate()" problem:

I was having the same problem many have reported where most of PHP worked but the gd functions didn't.  I'd installed the RedHat rpm php-4.0.1pl2.  It said (phpinfo.php) that it had been configured with the '--with-gd=shared' option.  In my /usr/lib directory, I had both libgd.so.1.8.3 and libgd.a.  I decided to compile with the static library instead, so I downloaded the sources and built with all the same configuration flags except that I used --with-gd=/usr.  Now my gd library works!!!

scottlindh pwnd at hushmail dot com

15 years ago


to install on UBUNTU do the following..

sudo apt-get install php5-gd

After installing the package I restarted the apache

sudo /etc/init.d/apache reload

goto love ubuntu...


sk89q

14 years ago


Loads a file based on its filetype and returns false if it fails.

<?php
function imagecreatefromfile($path, $user_functions = false)
{
   
$info = @getimagesize($path);

        if(!

$info)
    {
        return
false;
    }
$functions = array(
       
IMAGETYPE_GIF => 'imagecreatefromgif',
       
IMAGETYPE_JPEG => 'imagecreatefromjpeg',
       
IMAGETYPE_PNG => 'imagecreatefrompng',
       
IMAGETYPE_WBMP => 'imagecreatefromwbmp',
       
IMAGETYPE_XBM => 'imagecreatefromwxbm',
        );

        if(

$user_functions)
    {
       
$functions[IMAGETYPE_BMP] = 'imagecreatefrombmp';
    }

        if(!

$functions[$info[2]])
    {
        return
false;
    }

        if(!

function_exists($functions[$info[2]]))
    {
        return
false;
    }

        return

$functions[$info[2]]($path);
}
?>


tassader at xmail dot cz

19 years ago


It seems that imagecreate creates a grayscale image with gd2

Anonymous

18 years ago


This is how you can create a thumbnail with maximum height and width. This way it will fit nicely in a gallery table. In this example $im is the source image
<?
    //calculate thumb size
            $ow = imagesx($im);
            $oh = imagesy($im);
            $maxh = 100;
            $maxw = 150;
            $new_h = $oh;
            $new_w = $ow;

            if($oh > $maxh || $ow > $maxw){
               $new_h = ($oh > $ow) ? $maxh : $oh*($maxw/$ow);
               $new_w = $new_h/$oh*$ow;
            }

            //create dst image
            $dst_img = ImageCreateTrueColor($new_w,$new_h);
            //resize and copy image
            ImageCopyResized($dst_img, $im, 0,0,0,0, $new_w, $new_h, ImageSX($im), ImageSY($im));   
            $function_image_new($dst_img,$galdir.$file);
?>


cstevens at gencom dot us

18 years ago


Here's how I resolved the "Fatal error: Call to undefined function: imagecreate()" error using Gentoo:

1) add a USE flag for gdb in /etc/make.conf

     USE="3dnow avi [whatever else you have] gdb"

   Note: here's a list of all of the USE flags:
   http://www.gentoo.org/dyn/use-index.xml

2) unmerged mod_php

*Note* It could take awhile to "remerge" as it may need to compile several dependancies...do this during not production hours and have a backup if you absolutely cannot have downtime

   emerge -C mod_php

3) emerged mod_php

   emerge -p mod_php
    # find out if it's going to take awhile

4) edit /etc/php/apach2-php4/php.ini
     uncomment the "extension=php_gd2.dll" line

5) Restart apache2

    /etc/init.d/apache2 restart

Hope this helps!

--
Cooper Stevenson
GenCom
http://www.gencom.us


help at nanomc dot com

17 years ago


// A simple XY graph

<html>

<head>

       
<title>XY Graph</title>

<h2>Practice XY Graph</h2>

</head>

<body>

<?php

$left
= 0;

$top = 0;

$x_size = 400;

$y_size = 400;
$char_width = 8;

$char_height = 11;
$x_start = $x_left + 100;

$y_start = $top + $char_height * 1.5;

$x_end = $x_start + $x_size;

$y_end = $y_start + $y_size;

$right = $x_start + $x_size + 40;

$bottom = $y_start + $y_size + $char_height * 1.5;
$graph_n = 100;

for(
$i = 0; $i < $graph_n; $i++ )

    {

   
$graph_x[$i] = $i;

   
$graph_y[$i] = $i * $i;

    }
$min_x = 9e99;

   
$min_y = 9e99;

   
$max_x = -9e99;

   
$max_y = -9e99;
$avg_y = 0.0;

   
    for(

$i = 0; $i < $graph_n; $i++ )

        {

        if(
$graph_x[$i] < $min_x )

           
$min_x = $graph_x[$i];

        if(

$graph_x[$i] > $max_x )

           
$max_x = $graph_x[$i];

        if(

$graph_y[$i] < $min_y )

           
$min_y = $graph_y[$i];

        if(

$graph_y[$i] > $max_y )

           
$max_y = $graph_y[$i];
$avg_y += $graph_y[$i];

        }
$avg_y = $avg_y / $graph_n;
$min_x = 0;

   
$min_y = 0;

   
$max_x += $max_x * 0.05;

   
$max_y += $max_y * 0.05;
$image = ImageCreate($right - $left, $bottom - $top);

$background_color = imagecolorallocate($image, 255, 255, 255);

$text_color = imagecolorallocate($image, 233, 14, 91);
$grey = ImageColorAllocate($image, 204, 204, 204);

$white = imagecolorallocate($image, 255, 255, 255);

$black = imagecolorallocate($image, 0, 0, 0);

$red = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, $left, $top, $right - 1, $bottom - 1, $black );

imagerectangle($image, $x_start, $y_start, $x_end, $y_end, $grey );

for(

$i = 0; $i < $graph_n; $i++ )

   {

  
$pt_x = $x_start + ($x_end-$x_start)*($graph_x[$i]-$min_x)/($max_x-$min_x);

  
$pt_y = $y_end - ($y_end - $y_start)*($graph_y[$i]-$min_y)/($max_y-$min_y);
//  imagesetpixel( $image, $pt_x, $pt_y, $black );

  
imagechar($image, 2, $pt_x - 3, $pt_y - 10, '.', $black);

   }
$string = sprintf("%2.5f", $max_y);

imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_start - $char_width, $string, $black);
$string = sprintf("%2.5f", $min_y);

imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_end - $char_height, $string, $black);
$string = sprintf("%2.5f", $min_x);

imagestring($image, 4, $x_start - (strlen($string) * $char_width)/2, $y_end, $string, $black);
$string = sprintf("%2.5f", $max_x);

imagestring($image, 4, $x_end - (strlen($string) * $char_width) / 2, $y_end, $string, $black);
$x_title = 'x axis';

$y_title = 'y axis';
imagestring($image, 4, $x_start + ($x_end - $x_start) / 2 - strlen($x_title) * $char_width / 2, $y_end, $x_title, $black);
imagestring($image, 4, $char_width, ($y_end - $y_start) / 2, $y_title, $black);
header('Content-type: image/png');

$filename = sprintf("%d.png", time());

ImagePNG($image,$filename);

ImageDestroy($image);
printf("<img src='%s'> ", $filename);

?>

</body>

</html>


marc at gutt dot it

7 years ago

foxlovr1 at cox dot net

18 years ago


You can set it up so you can write a text which is controled from the URL.

Like this...

<?php
header
("Content-type: image/png");
$im = @imagecreate(128, 16) or die("Cannot Initialize new GD image stream");
$bc = imagecolorallocate($im, 0, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 4, 4$t, $tc);
imagepng($im);
imagedestroy($im);
?>

Then when you use the image, use this...

<img src="http://www.yourdomain.com/stuff/cool_image.php?t=Text">

This will create an image with a cyan background, and in black text it will say "Text"

EMail me at foxlovr1@cox.net or aquafox90@yahoo.com for comments/questions.


removethisbeforebayet at removethistooenseirb dot fr

22 years ago


Pay attention to a problem I encountered.

Png images created with the PHP function seems to be very badly recognised by old browsers, especially -well, mainly - by IE 4.0 (crash of the browser).

I think this is probably due to the fact that, when IE 4.0 was released, the png format was either very recent, either not very used, because of the widespread jpeg and gif formats...

So, if you plan to dynamically create images for a web site to be seen by IE 4.0 users, think of it...

May'be the jpeg format will do the job better.

sjnorrie at hotmail dot com

19 years ago


On windows.

When you get undefined function image* it means the gd library isnt being used. Check the php.ini file. Make sure the php_gd.dll isnt commented out. Restarting apache should result in the image functions working.


andrus at vnet dot ee

21 years ago


Dont forget to use ImageDestoy after showed image. I forgot it, my webpage had about 15 pictures what was generated by GD and webserver died very fastly (server was Dual Xeon 900MHz and 4G RAM :[[ ). It died cos of not enough memory :

Your PHP installation does not have the GD Library installed or it is not enabled.

The GD Library is bundled with PHP, but needs to be enabled during installation.

You will need Administrator rights to your server to enable the GD Library. If you do not have Administrator access, please contact your support and ask them to enable it for you.

It is recommended that your GD Library version is later than gd-2.0.28. Versions older than gd-2.0.28 may not have GIF support. Versions lower than 2 do not support true color images.

=======================================
Linux / Unix – Administrators (root access)
=======================================
Your PHP would need to be compiled with the GD Library.

Here is a quote from http://www.php.net/gd

«To enable GD-support configure PHP –with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option –with-gd. GD library requires libpng and libjpeg to compile.»

Please refer to the PHP manual / installation instructions for more info.

It is also possible to get pre-compiled binaries of PHP with the GD Library built in.

On some systems, you will be able to install by simply typing this in:

yum install gd php-gd

=======================================
Windows users – Administrators
=======================================

If you are hosting on Windows and have Administrator access, you can easily enable the GD Library that is distributed with PHP.

Please see PHP the documentation to learn how to enable extensions in Windows.

Roughly, here is what you need to do:

1. Copy the file php_gd2.dll from your PHP’s ext/ directory to where
you have your php extensions. (No need to copy if php_gd2.dll is in the extension
dir already. Look in php.ini for ‘extension_dir’ directive to
find what is your current extension directory)

2. Modify your php.ini and change the following line:

;extension=php_gd2.dll

to:

extension=php_gd2.dll

3. Restart your web server.

Processing image with GD: Call to undefined function: imagegif()JavaScript Error when viewing the grid.

Содержание

  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.

Источник

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

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

  • 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 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии