Fatal error imagecreatefrompng gd png fatal libpng error read error truncated data

PHP Fatal error: imagecreatefrompng(): fatal libpng error: Read Error: truncated data in phar:///media/pictures/gayfurries/e6brs/e6BRS.phar/app.php on line 743 This error appeared after picture 541...

@ghost

PHP Fatal error: imagecreatefrompng(): fatal libpng error: Read Error: truncated data in phar:///media/pictures/gayfurries/e6brs/e6BRS.phar/app.php on line 743

This error appeared after picture 541/1671 of a Tumblr rip I did on my blog. The picture that it threw this error on is in fact truncated, hence the error message, but isn’t there a fail-safe that can be implicated to work around this? Had I not been at my computer while this was running, I would’ve come back hours later to realize that the tool had thrown an error message hours before.

@jacklul

@Youboontoo There wasn’t any fail-safe because I didn’t know about this issue before, all errors from ‘imagecreate’ were warnings for me.

Will apply a fix soon.

@ghost

The same error is occurring, even after updating the script:

[1/1131] Searching 'tumblr_oves74yED51tek5qpo1_raw.png':
Trying md5 sum... no matching posts found!
Trying reverse search...PHP Fatal error: imagecreatefrompng(): gd-png: fatal libpng error: Read Error: truncated data in phar:///media/pictures/gayfurries/e6brs/e621BRS.phar/app.php on line 744

However, I think the gd-png part is new… Lemme check if all my binaries are up to date.

@ghost

Nope, everything is up to date.

uname -a:
Linux tux-server 4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tues Oct 10 16:30:51 UTC 2017 i686 i686 i686 GNU/Linux

php -v:
PHP 7.0.22-0ubuntu0.16.04.1 (cli) ( NTS )

@jacklul

@Youboontoo Can I have the problematic image so I can test it?

@ghost

tumblr_oves74yed51tek5qpo1_raw

Like I mentioned earlier, the picture is in fact truncated, so that’s what is causing this issue.

@jacklul

@Youboontoo I Googled a bit and it seems to be some kind of bug in PHP on Linux, could you try with PHP 5.6?
This issue does not happen for me on Windows PHP 5.6 and 7.1.

Also, remember you can use config variable USE_CONVERSION=false to prevent conversion before uploading, this will get rid of the issue but slow down uploads (unless you have beast upload speed).

@ghost

@ghost

Rolling back now, will post results shortly

@ghost

php -v:
PHP 5.6.32-ubuntu16.04.1+deb.sury.org+1 (cli)

Error message is still same as above, will test on Windows next.

@ghost

Windows does not reproduce the same error message.

[1051/1131] Searching 'tumblr_oves74yED51tek5qpo1_raw.png':
 Trying md5 sum... no matching posts found!
 Trying reverse search... error: cannot create JPEG - expected resource input

Perhaps with the Linux script, you could try using ImageMagick to convert the pictures? I believe IM has more tolerance for corrupted pictures.

jacklul

added a commit
that referenced
this issue

Nov 9, 2017

@jacklul

@jacklul

@ghost

I can confirm that this fixed the issue. Thanks for your patience.

Когда я пытаюсь использовать функции php-gd на некорректных изображениях png, у меня появляется фатальная ошибка PHP. Кажется, это какая-то ошибка, потому что в соответствии с документацией функций (например, imagecreatefrompng):

* @return resource an image resource identifier on success, false on errors.

Но когда я пытаюсь сделать это с моим неправильным изображением, у меня есть:

Fatal error: imagecreatefrompng(): gd-png: fatal libpng error: Read Error: truncated data in /var/www/common/models/Utils.php on line 61

Код, который приводит к этой ошибке, прост:

$handle = imagecreatefrompng($fname);

После этой строки код не выполняется.

То же самое относится и к imagecreatefromstring при попытке создать изображение из той же строки.

Я не могу «исправить» эту картинку, потому что она предоставлена пользователем, поэтому мне нужно разобраться с этими случаями.

Я пытался использовать блок try...catch следующим образом:

echo 'start'."n";
try {
    imagecreatefromstring($result);
} catch (Throwable $e) {
    echo 'error'."n";
    return null;
}
echo 'success'."n";

Но скрипт выдает только «start», а затем умирает и показывает описание ошибки, которое я выложил выше.

Ubuntu 16.04.2, PHP 7.0, расширение php7.0-gd, обе являются последней версией.

Так что я не могу справиться с этим с помощью try … catch, и я вообще не знаю, как с этим справиться или исправить. Любые идеи?

UPD: Кажется, это действительно странная ошибка со средой, потому что, когда я запускаю тот же код в Windows (с PHP 7.0), он выдает правильную ошибку «Предупреждение».

UPD2 . Похоже, это свежая ошибка https: // bugs .php.net / bug.php ? ID = 73986

3 ответа

Лучший ответ

Немного опоздал на вечеринку, но я тоже столкнулся с этой проблемой и не могу дождаться, когда исправление ошибки будет включено в мою Ubuntu LTS. Единственный чистый обходной путь, который я нашел, — это на самом деле использовать Imagick :: valid (), чтобы проверить изображение действительный.

function imageIsValid($path)
{
    try
    {
        $imagick = new Imagick($path);

        return $imagick->valid();
    }
    catch (Exception $e)
    {
        return false;
    }
}

Конечно, на вашем сервере / хостинге должно быть установлено расширение php imagick …


3

JulienV
22 Янв 2018 в 16:55

Поскольку в PHP7 все ошибки являются исключениями, вы можете просто поместить хрупкую часть кода в блок try-catch, чтобы перехватить исключение Throwable и обработать его соответствующим образом.


0

emix
18 Июл 2017 в 19:42

Кажется, это свежая ошибка (и, возможно, не закрытая): https: //bugs.php .net / bug.php ? ID = 73986

Поэтому, пока я не найду лучший способ, я думаю, что это единственный способ проверить изображение. Это плохой код, и я знаю это, но у меня нет других идей. Идея состоит в том, чтобы попытаться создать изображение в другом потоке, и возвращаемое значение проверки зависит от его вывода.

$fname = tempnam('/tmp', 'test_');
$handle = fopen($fname, 'w');
fwrite($handle, $result);
fclose($handle);

$output = `php -r "imagecreatefrompng('$fname');" 2>&1`;
unlink($fname);

if (!empty($output)) {
    return null; // error
}
// good image

Оператор Backtrick выполнит команду в оболочке. Чем он выдаст ошибку в stderr. 2>&1 используется для вывода потока stderr в поток stdout, чтобы к нему можно было обратиться через оператор обратного хода.


1

SeRRgIO
18 Июл 2017 в 20:38

Содержание

  1. Solved (ish) gd-png: fatal libpng error: bad parameters to zlib
  2. spectrumcs
  3. Как игнорировать fatal error?
  4. antono
  5. Апокалипсис
  6. mishco
  7. Фанат
  8. jonjonson
  9. Фанат
  10. antono
  11. Фанат
  12. antono
  13. Апокалипсис
  14. tony2001
  15. Фанат
  16. antono
  17. tony2001
  18. Mr_Max
  19. antono
  20. tony2001
  21. Strange GD error when working on PNG images from PHP on FreeBSD
  22. 7 Answers 7
  23. Warning: imagecreatefromstring() when saving content with pasted PNGs #40
  24. Comments
  25. imagecreatefrompng
  26. Описание
  27. Список параметров
  28. Возвращаемые значения
  29. Список изменений
  30. Примеры
  31. User Contributed Notes 7 notes

Solved (ish) gd-png: fatal libpng error: bad parameters to zlib

spectrumcs

I’m migrating a WordPress site from one server another and I’ve run to to a problem with some of the images not being displayed. The images are being piped though a PHP script to dynamically resize them. After some investigation I’ve noticed that the issue is only effecting PNG images and found errors relating to gd-png in the webserver logs. As a test I created a simple php script (at the bottom of this post) which just opens a PNG with imagecreatefrompng and every time access the script via a browser I get the following errors.

I have tried several different png’s from several different sources in case the png’s where the problem, but alias it seems to effect all png’s regardless of origin.

Most interestingly, if I run the same script from the command line (su’d to the webserver user!) I do not get the errors (I get the raw PNG but that’s expected).

I’m not sure if that makes it a PHP problem or an apache24 problem, but I can’t think of any reason why running the script via the webserver should cause such a problem. No permission issues are in play.

I have two webservers setup very similar, both experience the same problem.

My apologies if this is not the correct place to report such a problem. I have also posted this problem to PHP’s Bug Tracking System (https://bugs.php.net/bug.php?id=70276) but I’m not 100% sure its a PHP problem (because it works via the CLI).

Note, I spent quite a few hours on this yesterday evening and was running PHP 5.6.11 at the time but I have this morning upgraded to 5.6.12 , however the problem persists.

Источник

Как игнорировать fatal error?

antono

Новичок

Как игнорировать fatal error?

Функция imagecreatefrompng на некоторых картинках выдает fatal error и останавливает скрипт. Как игнорировать эту ошибку чтобы скрипт продолжал дальше работать?

Апокалипсис

тех дир matras.ru

[m]error_reporting[/m]
заглушить ф-цию -> @

Но лучше искать проблему в коде.

Алгоритмик 🙂

mishco

Фанат

oncle terrible

мля.
граждане отвечающие.
ВОПРОС ЧИТАТЬ НЕ ПРОБОВАЛИ?

antono
вообще, очень странные вещи ты пишешь.
если imagecreatefrompng не может создать картинку, то она выдает не фатальную ошибку.

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

jonjonson

Охренеть

Фанат

oncle terrible

antono

Новичок

Вот что вываливает:

Fatal error: imagecreatefrompng(): gd-png: fatal libpng error: IDAT: CRC error in /home/test/site.ru/phpbb/test.php on line 13

Дело не в нехватке памяти, т.к. картинки маленькие по 10-20 кб.

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

Фанат

oncle terrible

antono

Новичок

Апокалипсис

тех дир matras.ru

tony2001

TeaM PHPClub

Фанат

oncle terrible

Апокалипсис
иди учи матчасть

antono

Новичок

***** спасибо, применил скрипт из листинга 2.
Делаю лог скрипта на жеский диск, затем при его остановке запускаю его заново.

Кстати пробовал запускать imagecreatefrompng на 3 различных хостингах и на локальном компьютере — везде fatal error.

tony2001

TeaM PHPClub

Mr_Max

Первый класс. Зимние каникулы ^_^

antono

Новичок

Версии: 4.4.2, 4.3.10

Вот попробовал на PHP 5 версии, выдает 3 варнинга и не прекращает работу:

Warning: imagecreatefrompng() [function.imagecreatefrompng]: gd-png: fatal libpng error: Extra compressed data in /usr/home/admin/domains/site.ru/public_html/1.php on line 6

Warning: imagecreatefrompng() [function.imagecreatefrompng]: gd-png error: setjmp returns error condition in /usr/home/admin/domains/site.ru/public_html/1.php on line 6

Warning: imagecreatefrompng() [function.imagecreatefrompng]: ‘image.png’ is not a valid PNG file in /usr/home/admin/domains/site.ru/public_html/1.php on line 6

tony2001

TeaM PHPClub

>Версии: 4.4.2, 4.3.10
о, ну это уже прошлый век.

>Вот попробовал на PHP 5 версии, выдает 3 варнинга и не прекращает работу
ч. и т.д.

Источник

Strange GD error when working on PNG images from PHP on FreeBSD

I have a problem with my FreeBSD 7.1 server. PHP’s GD implementation no longer works on PNG images. Whenever the system tries to work with PNG images, I get these three error messages:

I’ve been trying to solve this half a day now, and the best clue I’ve found is another guy having the same problem – no solution there, though.

The code in question is fairly simple, it just calls imagecreatefrompng($filename);

Package versions of all the packages I can think of that might be related:

7 Answers 7

Before updating always read

Sometimes you’ll need to do recursive portupgrade i.e.

This command solve my problem:

portupgrade -fr png-1.2.40

If you are using portmaster, this will work:

This is very older bug in freebsd.

In extensions.ini the string extension=gd.so needs to be the first line.

It could be problem with PNG image. Try very basic code with very small black and white PNG image. If that also generates same errors in log files then you could consider installing PHP from source so that modules like php_gd get updated to latest version.

You can also try setting

in case they give some better error message on screen. Remember to make display_errors=Off after you have finished debugging on a production server.

I had a recent problem similar to this. After upgrading one of the packages on my 7.2 system, the gd-driven captcha on my phpBB2 installation stopped working. I re-built all of the php ports and it fixed itself.

I know that’s a bit vauge, but sometimes things will break over months of incremental upgrades due to dependencies getting out of whack.

No answer but since I cannot leave any comment; I have a 7.2 system with exactly the same problem and exactly the same versions. Even tried downgrading libpng to no avail. Doing a binary upgrade from 7.1. to 7.2 was extremely painless and well worth it but don’t think that will fix the problem 🙂

I also installed pecl-imagick to see if I could use that instead but to my surprise I got similar errors. I tried lots of other software that depends on libpng but they could all load the images giving errors in php5-gd and pecl-imagick just fine. This made me exclude libpng, which at first I thought was the problem. My next guess is that something in the php API has changed, I will try to downgrade php and see if that helps.

Источник

Warning: imagecreatefromstring() when saving content with pasted PNGs #40

I’m trying to save content into a docuwiki page, but coming unstuck when I try more than three images. The first two process correctly, but the third (and subsequent) always fail.

Warning: imagecreatefromstring(): gd-png: fatal libpng error: invalid stored block lengths in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): gd-png error: setjmp returns error condition in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): Passed data is not in ‘PNG’ format in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): Couldn’t create GD Image Stream out of Data in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3
Clipboard paste: invalid png image format

Warning: imagecreatefromstring(): gd-png: fatal libpng error: invalid code lengths set in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): gd-png error: setjmp returns error condition in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): Passed data is not in ‘PNG’ format in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3

Warning: imagecreatefromstring(): Couldn’t create GD Image Stream out of Data in /home/public_html/doku/lib/plugins/ckgedit/action/save.php(77) : runtime-created function on line 3
Clipboard paste: invalid png image format

The text was updated successfully, but these errors were encountered:

Источник

imagecreatefrompng

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

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

Описание

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

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

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

Путь к изображению PNG.

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

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

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

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

Примеры

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

function LoadPNG ( $imgname )
<
/* Пытаемся открыть */
$im = @ imagecreatefrompng ( $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/png’ );

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

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

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

User Contributed Notes 7 notes

If you’re trying to load a translucent png-24 image but are finding an absence of transparency (like it’s black), you need to enable alpha channel AND save the setting. I’m new to GD and it took me almost two hours to figure this out.

= imageCreateFromPng ( $strImagePath );
imageAlphaBlending ( $imgPng , true );
imageSaveAlpha ( $imgPng , true );

/* Output image to browser */
header ( «Content-type: image/png» );
imagePng ( $imgPng );
?>

I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

Usually the memory_limit var on php.ini is set to 8M. Unfortunately, the required amount of memory to manage a PNG image about 1000×1000 could be bigger !

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value

1-The following value works for me:
$required_memory = Round($width * $height * $size[‘bits’]);

2-Use somthing like:
$new_limit=memory_get_usage() + $required_memory;
ini_set(«memory_limit», $new_limit);

Because gd and imagick do not support animated PNG (at this moment), i wrote a simple function to determine if given PNG is APNG or not. It does not validate PNG, only checks whenever «acTL» chunk appears before «IDAT» like the specification says: https://wiki.mozilla.org/APNG_Specification

function is_apng ( string $filename ): bool
<
$f = new SplFileObject ( $filename , ‘rb’ );
$header = $f -> fread ( 8 );
if ( $header !== «x89PNGrnx1An» ) <
return false ;
>
while (! $f -> eof ()) <
$bytes = $f -> fread ( 4 );
if ( strlen ( $bytes ) 4 ) <
return false ;
>
$length = unpack ( ‘N’ , $bytes )[ 1 ];
$chunkname = $f -> fread ( 4 );
switch ( $chunkname ) <
case ‘acTL’ :
return true ;
case ‘IDAT’ :
return false ;
>
$f -> fseek ( $length + 4 , SEEK_CUR );
>
return false ;
>

When using imagecreatepng with alpha blending you will lose the blending.

To over come this use something like the following
= imagecreatetruecolor ( $width , $height );
$srcimage = imagecreatefrompng ( $src );
imagecopyresampled ( $dstimage , $srcimage , 0 , 0 , 0 , 0 , $width , $height , $width , $height );
?>
Where $width and $height are the width and height of the $src image.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.

Источник

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

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

  • Fatal error igi cd not found please insert cd in drive
  • Fatal error icon
  • Fatal error hid h no such file or directory
  • Fatal error has occurred this connection is terminated tlauncher
  • Fatal error gta 5 решение

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

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