Uncaught error call to undefined function gregwar captcha imagecreatetruecolor

Проблема с imagecreatetruecolor Cramac Новичок Проблема с imagecreatetruecolor Не работает функция imagecreatetruecolor. В чем дело? Возможно надо ГД2, если да, то где скачать под винды? Стоит ВинХП, ГД1.6.2. Фанат oncle terrible Sapfir Guest Повторяй за мной: 1). Иди в папку где у тебя распакован php. 2). Там открой папку extensions. В ней найди файл […]

Содержание

  1. Проблема с imagecreatetruecolor
  2. Cramac
  3. Фанат
  4. Sapfir
  5. Cramac
  6. Фанат
  7. Cramac
  8. Проблема с imagecreatetruecolor
  9. c0dex
  10. Фанат
  11. Ulibka
  12. c0dex
  13. c0dex
  14. Ulibka
  15. Ulibka
  16. «вызов функции undefined function imagecreatetruecolor» в PHP и pChart
  17. ОТВЕТЫ
  18. Ответ 1
  19. Ответ 2
  20. Ответ 3
  21. Ответ 4
  22. Ответ 5
  23. Ответ 6
  24. imagecreatetruecolor
  25. Описание
  26. Список параметров
  27. Возвращаемые значения
  28. Список изменений
  29. Примеры
  30. Смотрите также
  31. User Contributed Notes 37 notes

Проблема с imagecreatetruecolor

Cramac

Новичок

Проблема с imagecreatetruecolor

Не работает функция imagecreatetruecolor. В чем дело?
Возможно надо ГД2, если да, то где скачать под винды?

Стоит ВинХП, ГД1.6.2.

Фанат

oncle terrible

Sapfir

Guest

Повторяй за мной:

1). Иди в папку где у тебя распакован php.

2). Там открой папку extensions. В ней найди файл php_gd2.dll. Копируй его

3). Иди в папку где УСТАНОВЛЕН РНР (предположительно C:php3 или С:php4) и вставляй туда файл.

4). Открой свой php.ini (в папке Windows) найди строчку ;extension=php_gd2.dll и убери знак «;» в начале.

5). Улыбайся, радуйся.

Cramac

Новичок

Фанат

oncle terrible

Cramac

Новичок

Одну проблему решил, теперь другая, перестал работать вот такой скриптик:

header («Content-type: image/JPEG»);
$org_h = imagesy($src );
$org_w = imagesx($src );
if($org_h > $org_w ) <
$x_img=»800″;
$x_k= ($x_img * 100) / $org_h;
> else <
$y_img=»800″;
$y_k= ($y_img * 100) / $org_w;
>
if ($x_img==»»)<$x_img= ($org_h * $y_k)/100;>
else <$y_img=($org_w * $x_k)/100;>

// height is bigger than width
$cfg[height] = $x_img;
$cfg[width]= floor($cfg[height] * $org_w / $org_h );
$cfg[dstX]= ($y_img — $cfg[width]) / 2;
$cfg[dstY]= 0;
> else <
// width is bigger than height
$cfg[width]= $y_img;
$cfg[height] = floor($cfg[width] * $org_h / $org_w );
$cfg[dstX]= 0;
$cfg[dstY]= ($x_img — $cfg[height]) / 2;
>

ImageCopyResized($img, $src, $cfg[dstX], $cfg[dstY], 0, 0, $cfg[width], $cfg[height], $org_w, $org_h );
##################
Imagejpeg($img);
##################
ImageDestroy($img );

при передаче всех данных ничего не происходит, а у хостера работает.
пытаюсь вот так открыть resize.php?name=selk001.jpg
а наме не передается.
Что не так?

ПС. Обновил то быстро, главное чтоб теперь не зря 6.5 мегов скачал.

Источник

Проблема с imagecreatetruecolor

c0dex

web.dev 2002-.

@Ulibka, Call to undefined function imagecreatetruecolor() дальше в гугол

PS: надо убедиться в том, что ты верную строчку нашел и раскомментил и в НУЖНОМ файле. Нету у тебя библиотеки GD

Фанат

oncle terrible

Ulibka

Новичок

Нашел еще параметр , установил
extension_dir = «C:xamppphpext»

Если extension_dir не выставить, то возникает ошибка
PHP Startup: Unable to load dynamic library ‘C:phpextphp_gd2.dll’

стоит строка
extension=php_gd2.dll

Ошибки пропали, но картинка все равно не появляется.
Может быть проблема в Xampp ?

P.S. apache я конечно перезагружал

c0dex

web.dev 2002-.

@Ulibka, тебя не смущает:

c0dex

web.dev 2002-.

Ulibka

Новичок

Смущает
Xampp поставил на SSD (диск F)
PHP стоит на F:xamppphp
В директории F:xamppphp лежит php.ini

Пробовал ставить
extension_dir = F:/xampp/php/ext

Программа не работает (картинки не видно)
Снес xampp, поставил на C: Apache (httpd-2.4.29-Win64-VC15 from Apache lounge)
Поставил на C: в директорию PHP сам php 7 (php-7.2.1-Win32-VC15-x64 thread safe.zip)
Выставил
extension_dir = c:/php/ext
та же фигня — не работает

Ulibka

Новичок

Может быть я все таки в пяти строках программы ошибся ?
Но ведь это я тупо записал пример (наверно даже из документации)

Источник

«вызов функции undefined function imagecreatetruecolor» в PHP и pChart

Я пытаюсь интегрировать «pChart» с моим PHP-кодом. Когда я пытаюсь запустить образцы, он дает мне сообщение об ошибке call to undefined function imagecreatetruecolor . Рекомендованным решением было загрузить эту dll «php_gd2.dll», поэтому я раскомментировал extension=php_gd2.dll в файле php.ini.

Даже после этого я получаю ту же ошибку. Я попытался перезапустить сервер и машину.

ОТВЕТЫ

Ответ 1

Используйте следующий код, чтобы проверить, есть ли расширение GD:

Если вы получили сообщение, которое оно не установлено, проверьте следующие шаги:

  • phpinfo() и найдите путь php.ini
  • edit php.ini : extension_dir =
  • изменить php.ini : extension = php_gd2.dll//раскомментировать или добавить
  • Перезапустить веб-сервер
  • Запустите тест script снова

Ответ 2

В Ubuntu/Linux Mint Platform (под root) используйте следующую команду:

Ответ 3

Я встретил эту проблему только сейчас. Вы должны выполнить sudo apt install php7.0-gd или vim свой php.ini открыть расширение = php_gd2.dll

Ответ 4

У меня такая же ошибка:

и мое решение было следующим:

отредактировать файл php.ini и раскомментировать содержимое строки extension = gd.so «, сохранить и повторить попытку

Ответ 5

Ответ 6

Этот ответ является обновлением 9 лет спустя, но PHP сильно изменился. Пожалуйста, проголосуйте за Святой Воланд, из которого это происходит.

Используйте следующий код на своем веб-сервере, чтобы проверить, есть ли у вас расширение GD:

«; //display GD function list

Если вы получили сообщение о том, что оно не установлено, выполните следующие действия:

  1. Посмотрите на вывод phpinfo(), чтобы определить ваш php.ini
  2. Отредактируйте php.ini и включите расширение GD:
    • Более новый PHP (7.3, fg):
      • extension = gd2//раскомментируем
    • Более старый PHP (5.x, 7.0, вы должны обновить):
      • extension_dir = & lt; путь к вашим расширениям & gt;//раскомментируем или добавляем
      • extension = php_gd2.dll//раскомментируем или добавляем
  3. GD для 7.x не может быть установлен
    • (для Ubuntu, таких как OS) sudo apt install php7.3-gd # заменить версию своей
  4. Перезапустите веб-сервер
  5. Запустите тестовый скрипт еще раз
  6. (Удалите тестовый скрипт, когда все работает, это может быть дыра в безопасности)

Как видите, точный метод очень зависит от версии. Я надеюсь, что эта дополнительная информация поможет другим разобраться, какие именно шаги им могут понадобиться.

Источник

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecreatetruecolor — Создание нового полноцветного изображения

Описание

imagecreatetruecolor() возвращает объект, представляющий чёрное изображение заданного размера.

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

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

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

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

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

Примеры

Пример #1 Создание нового потока GD изображения и вывод картинки.

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

Смотрите также

  • imagedestroy() — Уничтожение изображения
  • imagecreate() — Создание нового палитрового изображения

User Contributed Notes 37 notes

If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

= imagecreatetruecolor ( 800 , 600 );
imagesavealpha ( $png , true );

$trans_colour = imagecolorallocatealpha ( $png , 0 , 0 , 0 , 127 );
imagefill ( $png , 0 , 0 , $trans_colour );

$red = imagecolorallocate ( $png , 255 , 0 , 0 );
imagefilledellipse ( $png , 400 , 300 , 400 , 300 , $red );

header ( «Content-type: image/png» );
imagepng ( $png );
?>

What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).

The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)

HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?

I worked on a script where I delt with large images. Very often the error «out of memory» occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn’t find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

//————————————————— ENOUGH MEMORY ?
function enoughmem ( $x , $y , $rgb = 3 ) <
return ( $x * $y * $rgb * 1.7 MAXMEM — memory_get_usage () );
>

//————————————————— SIMPLE EXAMPLE
list ( $x , $y ) = @ getimagesize ( ‘your_img.jpg’ ); //— get size of img —
if ( enoughmem ( $x , $y )) <
$img = @ imagecreatefromjpeg ( ‘your_img.jpg’ ); //— open img file —
$thumb = 200 ; //— max. size of thumb —
if ( $x > $y ) <
$tx = $thumb ; //— landscape —
$ty = round ( $thumb / $x * $y );
> else <
$tx = round ( $thumb / $y * $x ); //— portrait —
$ty = $thumb ;
>
if ( enoughmem ( $tx , $ty )) <
$thb = imagecreatetruecolor ( $tx , $ty ); //— create thumbnail —
imagecopyresampled ( $thb , $img , 0 , 0 , 0 , 0 , $tx , $ty , $x , $y );
imagejpeg ( $thb , ‘your_thumbnail.jpg’ , 80 );
imagedestroy ( $thb );
>
imagedestroy ( $img );
>

//—————————————————
//— to check the memory working with —
//— b/w-image or gif use: —
//—————————————————
$check = enoughmem ( $x , $y , 1 );
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.

There is no need to allocate colors with imagecreatetruecolor. All [256 x 256 x 256 x 128] true colors are already allocated, and you can use the color indexes directly.

Examples :
Blue => color index 255.
White => color index 16777215 (= 255*256² + 255*256+255).
Full transparent => color index 2130706432 (= 127*256^3).

using imagecolorallocate to specify the image’s background color does not work with truecolor-image.

instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:

$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);

If you want to place an image on a larger canvas you’ve previously created with imagecreatetruecolor(), but you don’t want the default black background to surround it: use imagefill() AFTER imagecopyresampled().

I have no idea why this should be the case, but it works!

A note to post by Justin Greer @ 18-Nov-2003 10:40:

While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice ’cause Justin’s post is in the top and it can make people go the wrong way: Justin’s way of detecting which imagecreate function to use is too complicated, while there’s an easy standard way:

if ( function_exists ( ‘imagecreatetruecolor’ ) <
// use imagecreatetruecolor
> else <
// use imagecreate
>

If you want a simple way to mirror images, use the function I’ve included below.

function image_mirror ( $input_image_resource )
<
$width = imagesx ( $input_image_resource );
$height = imagesy ( $input_image_resource );
$output_image_resource = imagecreatetruecolor ( $width , $height );
$y = 1 ;

while ( $y $height )
<
for ( $i = 1 ; $i $width ; $i ++ )
imagesetpixel ( $output_image_resource , $i , $y , imagecolorat ( $input_image_resource , ( $i ), ( $height — $y ) ) );
$y = $y + 1 ;
>

return $output_image_resource ;
>
?>
Example Usage:
// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.

// I suggest checking $HTTP_REFERER for security.

// $_GET[‘file’] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)

if ( isset( $_GET [ ‘file’ ] ) )
<
$filename = «./» . basename ( $_GET [ ‘file’ ] ) . «.jpg» ;
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
$output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
if ( imagejpeg ( $output_resource_image , $filename , 75 ) )
echo «Image resaved successfully» ;
else
echo «Image couldn’t be written over (Check permissions)!» ;
>
?>

A very simple and efficient way to create RGB color from hexadecimal (HTML) notation:

function color_hex2dec ( $color ) <
return array ( hexdec ( substr ( $color , 0 , 2 )), hexdec ( substr ( $color , 2 , 2 )), hexdec ( substr ( $color , 4 , 2 )));
>

list ( $r , $g , $b ) = color_hex2dec ( ‘FFEECC’ );

I had a strange bug occurring under Debian Linux with PHP5.

In file B (where I create the image) I included a file (file A). The image that was produced was always corrupt. When I did not include file A, everything was fine.

After 2 hours of searching I found that there were some extra spaces and linefeeds after the PHP closing tag ?> in file A. After removing those chars, everything works fine again.

Obviously those extra bytes of file A were added to the image and corrupted it.

I know it’s not a discussion board, but when incorrect info is posted, it should be corrected.

The function_exists() check does not work correctly because if PHP is compiled with an older GD library, the imagecreatetruecolor() function still exists — it just gives a fatal error when called, stating that GD2 is required. Therefore, the function_exists() method will fail on any new-ish copy of PHP that only has GD 1.x. (That includes most of the 4.1.x and 4.2.x installs I’ve seen.)

Unfortunately the @imagecreatetruecolor() method doesn’t even work because php dies with a fatal error noting that GD 2 is required. You can’t even capture this error with a custom error handler.

I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I’ve thrown at it (even CLI versions.) It’s obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn’t slow down further.

function gd_version() <
static $gd_version_number = null;
if ($gd_version_number === null) <
// Use output buffering to get results from phpinfo()
// without disturbing the page we’re in. Output
// buffering is «stackable» so we don’t even have to
// worry about previous or encompassing buffering.
ob_start();
phpinfo(8);
$module_info = ob_get_contents();
ob_end_clean();
if (preg_match(«/bgds+versionb[^dnr]+?([d.]+)/i»,
$module_info,$matches)) <
$gd_version_number = $matches[1];
> else <
$gd_version_number = 0;
>
>
return $gd_version_number;
>

Then you can simply use it something like this:

if (gd_version() >= 2) <
$image = ImageCreateTrueColor($width, $height);
> else <
$image = ImageCreate($width, $height);
>

Regarding choosing the TrueColor or the plain version of imagecreate automatically, I’ve found that the following works for me:

=@ ImageCreateTrueColor ( $width , $height )
or $newImg = ImageCreate ( $width , $height );

I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can’t change the PHP-install
on the hosting side:

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);

Here is my solution for creating images with the same code for both GD 2:

$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img)

Because imagecreatetruecolor exist both in gd and gd2,
you can’t use function_exists or get_extension_funcs to check for gd2 !
But . there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.

Then you can check gd2 with this function:

$rep=false;
if(isset($GLOBALS[«gBGDVersion»]))
<
$rep=$GLOBALS[«gBGDVersion»];
>
else
<
if(function_exists(«gd_info»))
<
$gdver=gd_info();
if(strstr($gdver[«GD Version»],»1.»)!=false)
<
$rep=false;
>
else
<
$rep=true;
>
>
else
<
$size=40;
$font= your font file path here;
$b=imagettfbbox ($size,0,$font,»abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ»);

Why not just use function_exists?

Just because they have version 2.0 GD doesn’t mean that they haven’t disabled that function.

Also instead of determining which one you have on your machine and then writing setup specific code, you can write a universal code usable on either setups.

if (function_exists(imagecreatetruecolor))<
use imagecreatetruecolor()
>else<
use imagecreate()
>

Here is answer for first question ‘why do I need true color images’.

True color images you need when you want to work with images such as photos (snapshots), video frames and so on.

When you need to combine some these images for user, or to send him only small part of your image, and you try to use 256 colors, image will be ugly (try it if you want). Some colors will change dramatically.

«Antialias» lines which you may see are probably the result of using JPEG compression. JPEG is not looseless compression so «small image details may be changed» in order to reduce image size dramatically. On really true-color images such as your snapshots of landscape and so on and using small compression level you will hardly see differences. But on exact objects, such as lines, circles, which you draw on solid background using single color, you can see that if you save and load this image that some details are changed.

This little function does it for you:

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands

Thanks to OverFlow636 at gmail dot com and kuya1284 at techie dot com for their original coding which this function is based upon.

PHP lacks an imagecreatefromtga function, so I have prepared a simple function to include in your library if you deal with TGA images. In addition to creating an image from TGA, it also, optionally, will output an array with the dimensions of the image because getimagesize() does not function with TGA files.

Hopefully this function will eventually be unneeded if GD is ever updated to support the TGA format.

Please keep in mind that TGA’s come in many different compressions, color settings, and as a result this function will not work 100% of the time. Resulting images will fit the symptoms kuya1284 at techie dot com mentioned, and as a result you may need to create a second function. Keep in mind that using her code causes the «mirror» effect on images that load properly with the following function.

function imagecreatefromtga ( $filename , $return_array = 0 )
<
$handle = fopen ( $filename , ‘rb’ );
$data = fread ( $handle , filesize ( $filename ) );
fclose ( $handle );

$pointer = 18 ;
$x = 0 ;
$y = 0 ;
$w = base_convert ( bin2hex ( strrev ( substr ( $data , 12 , 2 ) ) ), 16 , 10 );
$h = base_convert ( bin2hex ( strrev ( substr ( $data , 14 , 2 ) ) ), 16 , 10 );
$img = imagecreatetruecolor ( $w , $h );

while ( $pointer strlen ( $data ) )
<
imagesetpixel ( $img , $x , $y , base_convert ( bin2hex ( strrev ( substr ( $data , $pointer , 3 ) ) ), 16 , 10 ) );
$x ++;

if ( $return_array )
return array ( $img , $w , $h );
else
return $img ;
>
?>

Example Usage

// the image ( resource image )
$image = $array [ 0 ];

// its dimensions ( integers )
$dimensions [ ‘width’ ] = $array [ 1 ];
$dimensions [ ‘height’ ] = $array [ 2 ];

// Delete the image resource array entry to free memory
imagedestroy ( $array [ 0 ]);
?>

The second variable, $return_array is optional. If you simply want to load a TGA, leave the variable off the function’s call as such:

imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.

imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).

kai wrote:
//using imagecolorallocate to specify the image’s background
//color does not work with truecolor-image.
//
//instead you have to use imagefill to force flood-filling the
//image with the backgorund-color previously allocated:
//
//$bgColor = imagecolorallocate($img, 255,255,255);
//imagefill($img , 0,0 , $bgColor);

even this doesn’t work for my configuration — fedora core2, php 4.3.8 + gd bundled (2.0.23 compatible) and I have to do this:
$img = imagecreatetruecolor($x, $y);
$bgColor = imagecolorallocate($img, 255,255,255);
imagefilledrectangle($img, 0, 0, $x-1, $y-1, $bgColor);

I put this together — combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.

// Set the content-type

header ( ‘Content-type: image/png’ );

// Create the image
$im = imagecreatetruecolor ( 175 , 15 );
imagesavealpha ( $im , true );

// Create some colors
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
$grey = imagecolorallocate ( $im , 128 , 128 , 128 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );
imagefilledrectangle ( $im , 0 , 0 , 150 , 25 , $black );
$trans_colour = imagecolorallocatealpha ( $im , 0 , 0 , 0 , 127 );
imagefill ( $im , 0 , 0 , $trans_colour );

// The text to draw
$text = $_GET [ ‘text’ ];
// Replace path by your own font path
$font = ‘catriel regular.ttf’ ;

// Add some shadow to the text
imagettftext ( $im , 9 , 0 , 13 , 16 , $black , $font , $text );

// Add the text
imagettftext ( $im , 9 , 0 , 12 , 15 , $white , $font , $text );

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng ( $im );
imagedestroy ( $im );
?>

Источник

  • #1

Проблема с imagecreatetruecolor

Не работает функция imagecreatetruecolor. В чем дело?
Возможно надо ГД2, если да, то где скачать под винды?

Стоит ВинХП, ГД1.6.2.

Фанат


  • #2

скачивать ничего не надо.
гд второй версии стоит во всех вменяемых по сроку давности версиях пхп.
попробуй вопсользоваться поиском по форуму на тему как совершить пару примитивных действий на предмет ее установки

Sapfir

Guest


  • #3

Повторяй за мной:

1). Иди в папку где у тебя распакован php.

2). Там открой папку extensions. В ней найди файл php_gd2.dll. Копируй его

3). Иди в папку где УСТАНОВЛЕН РНР (предположительно C:php3 или С:php4) и вставляй туда файл.

4). Открой свой php.ini (в папке Windows) найди строчку ;extension=php_gd2.dll и убери знак «;» в начале.

5). Улыбайся, радуйся…

  • #4

Все выше написанное было сделано давно, единственное что помогло, так это обновление ПХП до ПХП 4.3.4

Фанат


  • #6

Одну проблему решил, теперь другая, перестал работать вот такой скриптик:

##################
$src = ImageCreateFromJPEG(«./foto/».$name);
##################

header («Content-type: image/JPEG»);
$org_h = imagesy($src );
$org_w = imagesx($src );
if($org_h > $org_w ) {
$x_img=»800″;
$x_k= ($x_img * 100) / $org_h;
} else {
$y_img=»800″;
$y_k= ($y_img * 100) / $org_w;
}
if ($x_img==»»){$x_img= ($org_h * $y_k)/100;}
else {$y_img=($org_w * $x_k)/100;}

if($org_h > $org_w ) {

// height is bigger than width
$cfg[height] = $x_img;
$cfg[width]= floor($cfg[height] * $org_w / $org_h );
$cfg[dstX]= ($y_img — $cfg[width]) / 2;
$cfg[dstY]= 0;
} else {
// width is bigger than height
$cfg[width]= $y_img;
$cfg[height] = floor($cfg[width] * $org_h / $org_w );
$cfg[dstX]= 0;
$cfg[dstY]= ($x_img — $cfg[height]) / 2;
}

$img = ImageCreateTrueColor($y_img,$x_img);

ImageCopyResized($img, $src, $cfg[dstX], $cfg[dstY], 0, 0, $cfg[width], $cfg[height], $org_w, $org_h );
##################
Imagejpeg($img);
##################
ImageDestroy($img );

при передаче всех данных ничего не происходит, а у хостера работает.
пытаюсь вот так открыть resize.php?name=selk001.jpg
а наме не передается.
Что не так?

ПС. Обновил то быстро, главное чтоб теперь не зря 6.5 мегов скачал…

Фанат


  • #7

обновить ПХП — НИКОГДА не зря, запомни это.

значит, ты совсем не умеешь отлаживать программы?
и если что-то не работает, то остается только опустить руки, или, на крайний случай, обратиться в форум — там сидят телепаты, которые определят, почему у тебя перестал работать скрипт.
я тебя правильно понял?

А каких-то идей у тебя нету, как попытаться узнать — почему скрипт перестал работать?

например, может быть, он выдает сообщение об ошибке, но что-то мешает тебе его увидеть?

Фанат


  • #8

про генерацию превьюшек на лету даже и писать ничего не буду. устал.
в конце концов, если серверу больше нечем другим заняться, то и пофиг.
а когда у него вдруг начнет все тормозить, тогда он сам прибежит сюда плакаться.

  • #9

в том то и проблема что ничего не выдает.
Пустой экран и ни одной ошибки

А чот вы можете предложить на замену такого способа?

Фанат


  • #10

если браузеру в самом начале скрипта сказать, что дальше идет картинка
header («Content-type: image/JPEG»);
а не непосредственно перед тем, как ее выаодить — то и будет пустой экран.
Еще, если в пхп запрещен вывод ошибок на экран, то экран тоже будет пустым.

«пустой экран» — это не синоним «ничего не выдает»

lucas

Guest


  • #11

Убери хидер и все увидишь сам. ([f]globals[/f])

  • #12

ту lucas.
Спасиб, помогло.

А чем можно заменить такой способ?

Фанат


  • #13

на замену такого способа можно предложить не генерить превьюшку на лету каждый раз при запросе, а сгенерить заранее,

Фанат


  • #14

как всегда, спасибы меня обходют стороной :)))

  • #15

Фанат тебе тож спасиб.
А заранее делать, это создать превьюшку и записать ее, а потом просто грузить рисунок с диска?

Фанат


  • #16

конечно.
у тебя же лежат сами картинки?
ну так превьюшки, размером 2-3 килобайта и вовсе не проблема хранить.

но зато при просмотре галереи в 10 картинок у тебя не будет запускаться 10 пхп скриптов, отъедать память и процессор, распаковывая картинку из сжатого джпг в битмап и так далее.

  • #17

Спасиб.
Будем переделывать.

  • #18

Та же самая проблема :)
Windows, Xampp (PHP 7), php_gd2.dll имеется,
В php.ini строчку раскоментировал:
extension=php_gd2.dll

Header поставил.

Подскажите пожалуйста, может быть в xampp библиотеку gd2 надо как то по особому подключать ?

Ошибка:
Call to undefined function imagecreatetruecolor()

PHP:

<?php
 
    
Header("Content-type: image/JPEG");


 // Создаём пустое изображение и добавляем текст
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Выводим изображение
imagejpeg($im);

// Освобождаем память
imagedestroy($im);


?>

c0dex


  • #20

У меня php в процессе изучения — но за 14 лет проблема почему то осталась :)
Header стоит, dll есть , строчку в php.ini раскоментировал — что еще может быть ?
Или проблема в xampp ? и надо apache отдельно ставить и отдельно php (mysql я и так отдельно от xampp поставил)

Hello there again, i’m using a shopping cart called plaincart, everything works perfectly but the image upload, i was told it has something to do with GD not being enabled, i’m running wamp on a local machine, using PHP version : 5.2.4 and the error message is get is:

Fatal error: Call to undefined function imagecreatetruecolor() in Z:wampwwwplaincartadminlibraryfunctions.php on line 223

the php code is:

<?php

/*
Check if a session user id exist or not. If not set redirect
to login page. If the user session id exist and there's found
$_GET['logout'] in the query string logout the user
*/
function checkUser()
{
// if the session id is not set, redirect to login page
if (!isset($_SESSION['plaincart_user_id'])) {
	header('Location: ' . WEB_ROOT . 'admin/login.php');
	exit;
}

// the user want to logout
if (isset($_GET['logout'])) {
	doLogout();
}
}

/*

*/
function doLogin()
{
// if we found an error save the error message in this variable
$errorMessage = '';

$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];

// first, make sure the username & password are not empty
if ($userName == '') {
	$errorMessage = 'You must enter your username';
} else if ($password == '') {
	$errorMessage = 'You must enter the password';
} else {
	// check the database and see if the username and password combo do match
	$sql = "SELECT user_id
	        FROM tbl_user 
			WHERE user_name = '$userName' AND user_password = md5('$password')";
	$result = dbQuery($sql);

	if (dbNumRows($result) == 1) {
		$row = dbFetchAssoc($result);
		$_SESSION['plaincart_user_id'] = $row['user_id'];

		// log the time when the user last login
		$sql = "UPDATE tbl_user 
		        SET user_last_login = NOW() 
				WHERE user_id = '{$row['user_id']}'";
		dbQuery($sql);

		// now that the user is verified we move on to the next page
            // if the user had been in the admin pages before we move to
		// the last page visited
		if (isset($_SESSION['login_return_url'])) {
			header('Location: ' . $_SESSION['login_return_url']);
			exit;
		} else {
			header('Location: index.php');
			exit;
		}
	} else {
		$errorMessage = 'Wrong username or password';
	}		

}

return $errorMessage;
}

/*
Logout a user
*/
function doLogout()
{
if (isset($_SESSION['plaincart_user_id'])) {
	unset($_SESSION['plaincart_user_id']);
	session_unregister('plaincart_user_id');
}

header('Location: login.php');
exit;
}


/*
Generate combo box options containing the categories we have.
if $catId is set then that category is selected
*/
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
		FROM tbl_category
		ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
	list($id, $parentId, $name) = $row;

	if ($parentId == 0) {
		// we create a new array for each top level categories
		$categories[$id] = array('name' => $name, 'children' => array());
	} else {
		// the child categories are put int the parent category's array
		$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);	
	}
}	

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
	$name     = $value['name'];
	$children = $value['children'];

	$list .= "<optgroup label="$name">"; 

	foreach ($children as $child) {
		$list .= "<option value="{$child['id']}"";
		if ($child['id'] == $catId) {
			$list.= " selected";
		}

		$list .= ">{$child['name']}</option>rn";
	}

	$list .= "</optgroup>";
}

return $list;
}

/*
If you want to be able to add products to the first level category
replace the above function with the one below
*/
/*

function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
		FROM tbl_category
		ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
	list($id, $parentId, $name) = $row;

	if ($parentId == 0) {
		// we create a new array for each top level categories
		$categories[$id] = array('name' => $name, 'children' => array());
	} else {
		// the child categories are put int the parent category's array
		$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);	
	}
}	

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
	$name     = $value['name'];
	$children = $value['children'];

	$list .= "<option value="$key"";
	if ($key == $catId) {
		$list.= " selected";
	}

	$list .= ">$name</option>rn";

	foreach ($children as $child) {
		$list .= "<option value="{$child['id']}"";
		if ($child['id'] == $catId) {
			$list.= " selected";
		}

		$list .= ">  {$child['name']}</option>rn";
	}
}

return $list;
}
*/

/*
Create a thumbnail of $srcFile and save it to $destFile.
The thumbnail will be $width pixels.
*/
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
$thumbnail = '';

if (file_exists($srcFile)  && isset($destFile))
{
	$size        = getimagesize($srcFile);
	$w           = number_format($width, 0, ',', '');
	$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

	$thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($thumbnail);
}

/*
Copy an image to a destination file. The destination
image size will be $w X $h pixels
*/
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}

/*
Create the paging links
*/
function getPagingNav($sql, $pageNum, $rowsPerPage, $queryString = '')
{
$result  = mysql_query($sql) or die('Error, query failed. ' . mysql_error());
$row     = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

$self = $_SERVER['PHP_SELF'];

// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link

// print 'previous' link only if we're not
// on page one
if ($pageNum > 1)
{
	$page = $pageNum - 1;
	$prev = " <a href="$self?page=$page{$queryString}">[Prev]</a> ";

	$first = " <a href="$self?page=1{$queryString}">[First Page]</a> ";
}
else
{
	$prev  = ' [Prev] ';       // we're on page one, don't enable 'previous' link
	$first = ' [First Page] '; // nor 'first page' link
}

// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
	$page = $pageNum + 1;
	$next = " <a href="$self?page=$page{$queryString}">[Next]</a> ";

	$last = " <a href="$self?page=$maxPage{$queryString}{$queryString}">[Last Page]</a> ";
}
else
{
	$next = ' [Next] ';      // we're on the last page, don't enable 'next' link
	$last = ' [Last Page] '; // nor 'last page' link
}

// return the page navigation link
return $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; 
}
?>

I am trying to integrate «pChart» with my PHP code. When I am trying to run the samples it gives me an error stating call to undefined function imagecreatetruecolor. The suggestion solution was to load this dll «php_gd2.dll» so I have uncommented extension=php_gd2.dll in php.ini file.

Even after that I get the same error. I have tried restarting the server & machine too.

7 Answers

Use the following code to test if you have GD extension:

<?php
$testGD = get_extension_funcs("gd"); // Grab function list 
if (!$testGD){ echo "GD not even installed."; exit; }
echo"<pre>".print_r($testGD,true)."</pre>";

If you get the message that it’s not installed, then check the following steps:

  1. phpinfo() and look up php.ini path
  2. edit php.ini: extension_dir=<path to your extensions>
  3. edit php.ini: extension=php_gd2.dll //uncomment or add
  4. Restart web server
  5. Run the test script again

In Ubuntu/Linux Mint Platform (under root), use the following command:

apt-get update && apt-get -y install php5-gd

For PHP 7.2

sudo apt-get install php7.2-gd

I met this problem just now.
You should exec sudo apt install php7.0-gd or vim your php.ini
reopen extension=php_gd2.dll

This answer is an update 9 years later, but PHP has changed a lot. Please upvote the St. Woland from which this is derived…

Use the following code on your web server to test if you have GD extension:

<?php
    $testGD = get_extension_funcs("gd"); // Grab function list 
    if (!$testGD){
        echo "GD not even installed.";
        phpinfo();  // Display the php configuration for the web server
        exit;
    }
    echo"<pre>".print_r($testGD,true)."</pre>";  //display GD function list

If you get the message that it’s not installed, then check the following steps:

  1. Look at the output of phpinfo() to identify your php.ini
  2. Edit php.ini and enable the GD extension:
    • Newer PHP (7.3, fg):
      • extension=gd2 //uncomment
    • Older PHP (5.x, 7.0, you should upgrade):
      • extension_dir=<path to your extensions> //uncomment or add
      • extension=php_gd2.dll //uncomment or add
  3. GD for 7.x may not be installed
    • (for Ubuntu like OS’es) sudo apt install php7.3-gd # replace version to yours
  4. Restart web server
  5. Run the test script again
  6. (Remove test script when all is working, it can be a security hole)

As you can see the exact method is very version dependent. I hope this additional information can help others sort out the exact steps they might need.

I have same error:

PHP Fatal error:  Call to undefined function imagecreatetruecolor() in /var/www/webphp/php/captcha.php on line 251

and my solution was this:

$ locate php.ini
    /etc/php56/php.ini

edit file php.ini and uncomment line content «extension=gd.so«, save and try again

i have many version of php and i use the php-fpm. for me for php 8.0 helped is uncomment ;extension=gd in /etc/php/8.0/cli/php.ini and uncomment ;extension=gd2 in /etc/php/8.0/fpm/php.ini then install gd library as sudo apt-get install php8.0-gd.

sunsgneayo

Hello! I found Gregwar/Captcha not fully compatible with PHP 8+ environments. Can I trouble you to adapt it? thank you very much!

rodrigoprimo

nirvana72

Deprecated: Implicit conversion from float 42.5 to int loses precision in /workspace/wali-crm/api/vendor/gregwar/captcha/src/Gregwar/Captcha/CaptchaBuilder.php on line 365

kargirwar

I am getting this:

«PHP message: PHP Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given in vendor/gregwar/captcha/CaptchaBuilder.php:333»

The calling code is just this:

$builder = new CaptchaBuilder;
$builder->build();

PHP version 8.0.13

S1SYPHOS

Hey there,
I just released v2 of my fork. I migrated issues & open PRs, added some new features, fixed bugs, added GIF & PNG support, some helper functions & extended its test suite — today I saw your statement in #102 that it’s been a long time and I guess you’ve got many other things on your plate ..

Many thanks for this library,
cheers

S1SYPHOS

leni-mv

Hi,

I have a problem to install this library. When I run :
$ composer require gregwar/captcha

I have this error :
Package gregwar/captcha has requirements incompatible with your PHP version, PHP extensions and
Composer version:
— gregwar/captcha v1.1.9 requires ext-gd * but it is not present.

I have php 8.1.1 and composer 2.3.5 versions and I have loaded ext-gd * in composer.json :
$ composer require "ext-gd:*" --ignore-platform-reqs

"require": { "phpmailer/phpmailer": "^6.6", "ext-gd": "*" }

I have reload my VsCode But I have this error again.

Thanks for your time ! Sorry for my english and have a nice day !

jnahmias

Hello,
I am interested in packaging this library for inclusion in Debian GNU/Linux. To comply with the Debian Free Software Guidelines, we need to ascertain the licensing/copyright of all files. However, I do not see any information for the six captcha fonts. Would you please share some background on their provenance and some sort of statement from their creators that allows them to be distributed.
Thanks!
—Joe

ZhangChengLin

Can individual letters use different colors?
Can you use other background confusion? Confused as small letters?

E.g:
https://www.php.cn/captcha.html

jonny77

here is my gd info :
image
php version:7.4.8

—enable-gd-native-ttf is not available when configure in 7.3 + , so how to resolve this problem??

sscotti

Not sure this is still being maintained, but after I upgraded my PHP version to 8.1 I am seeing this error message.

PHP Deprecated: Implicit conversion from float 42.5 to int loses precision in CaptchaBuilder.php on line 365
PHP Deprecated: Implicit conversion from float 3.3333333333333335 to int loses precision in CaptchaBuilder.php on line 608

Seems to be related to:

https://php.watch/versions/8.1/deprecate-implicit-conversion-incompatible-float-string

alex-gevatter

I did not use the provided «testPhrase» method for the validation of the user’s CAPTCHA input string because I thought that this would be exaggerated only to compare two strings. This sometimes led to unsolvable CAPTCHAS, since one of the randomly selected fonts contains only uppercase letters. For example, if the generated phrase is «AbCdE», it becomes «ABCDE» in the CAPTCHA image. If you use the «testPhrase» method to validate the user input, this is not a problem. But if you do the validation yourself, as I did, you can end up with intractable CAPTCHAS.
The documentation states: «You can compare the phrase with user input». I think it would be better to write «must» or «should» here instead of «can» and explain why. A hint that a self-implemented case-sensitive string comparison leads to serious problems due to the upper-case font used would not be bad at this point either.

shaanaliyev

I saw erroneous narration in some examples. You can proceed with the following logic for the real solution.

<a href="#" onclick="document.getElementById('captcha').src = '/captcha'; return false">
       <img id="captcha" src="/captcha" alt="captcha image">
</a>

/captcha file where you use the output it directly feature

$builder = new CaptchaBuilder;
$builder->build();
header('Content-type: image/jpeg');
$builder->output();

AnnoyingTechnology

When a picture generated uses uppercase letters, ->getPhrase() returns a lowercase phrase.

javansolo

run on php 8 and get error
Call to undefined function GregwarCaptchaimagecreatetruecolor()

composervendorgregwarcaptchasrcGregwarCaptchaCaptchaBuilder.php:423

nkornev

Is there anything that prevents it from working with Finder 2.8?

I am using this package through gregwar/captcha-bundle, which will work with Symfony 2.8. However, gregwar/captcha requires Finder 3.0 or above. As the result, I get gregwar/captcha v1.1.3 which is not compatible with PHP 7, while Symfony 2.8 is.

ZhangChengLin

Is the background useless? It is still related to distort in line 480, because $bg in line 480 does not necessarily work.
I am not quite sure, so I dare not submit a PR rashly, please confirm.

$image = $this->distort($image, $width, $height, $bg);

kaysonwu

GIF can increase the difficulty of recognition.

anoduck

I have ran into a sticky wicket where I am attempting to add a simple captcha page to my site and currently within the site folder super globals are disabled. So, I am getting all sorts of errors. I attempted to enable super globals programmatically just for the needed phrase and it is giving me the error Call to a member function enable_super_globals() on null. So I was wondering if there was another way to use PhraseBuilder::comparePhrases that does not entail use of the _server global?

Here is the important block of code where I am running into issues.

$captcha = new CaptchaBuilder();
$captcha->build();
session_start();
global $request;
global $config;
$request->enable_super_globals();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Checking that the posted phrase match the phrase stored in the session
if (isset($_SESSION['phrase']) && PhraseBuilder::comparePhrases($_SESSION['phrase'], $_POST['phrase'])) {
  header("Location: index.php");
	//echo "<h1>Captcha is valid !</h1>";
    } else {
	echo "<h1>Captcha is not valid!</h1>";
    }
    // The phrase can't be used twice
  unset($_SESSION['phrase']);
};
$request->disable_super_globals()

I know this is not technically an «issue», but figured it would not hurt asking for a little help sorting this one out.

zakir1929

Hello Guys!!!

I see there is an error in php 7.4 version with Call to undefined function GregwarCaptchaimagejpeg()

this error is coming up on line number 565 in below file vendor/gregwar/captcha/src/Gregwar/Captcha/CaptchaBuilder.php

Can you please see it and fix it !!!

Thanks

adspirkova

Hi!

We are using the library on our website and it doesn’t store the expected code on the first attempt. The captcha is only once in the form. I’ve already went through issues here and tried many things but none of them worked.
I send get and post requests with Axios, with credentials and Cookie set to ‘secure’.
We authorize user with session id stored in Cookie.

Is there anything else I miss in implementing the captcha to React using axios?

Понравилась статья? Поделить с друзьями:
  • Uncaught error call to undefined function curl init
  • Uncaught error call to a member function includecomponent on null in
  • Uncaught error call to a member function gettvvalue on null in
  • Uncaught error bootstrap s javascript requires jquery
  • Uncaught error addcase cannot be called with two reducers for the same action type