PHP JPEG Functions Not Working

2020-04-12 09:30发布

问题:

Any PHP functions that deal with JPEGs don't seem to be working on my server.

This code:

<?php
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
header('Content-type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>

creates an empty file.

Using a GIF or PNG function will create an image containing the text "A Simple Text String" as expected.

This:

$im = imagecreatefromjpeg("test.jpg");

returns

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'test.jpg' is not a valid JPEG file in /path/to/test.php on line 2

A phpinfo() shows:

gd
GD Support  enabled
GD Version  2.0 or higher
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.3.9
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled 

And the webserver can read any relevant files.

GIF and PNG functions work fine, and as expected.

Any ideas?

EDIT:

Found this in my Apache error log file:

gd-jpeg: JPEG library reports unrecoverable error: Wrong JPEG library version: library is 80, caller expects 62

回答1:

Your error log clearly shows that your PHP is compiled against/requires libjpeg version 62, while the library on your server is version 80.

Either install the correct version of libjpeg, or recompile gd/php.



回答2:

It appears that the file test.jpg doesn't exist, or isn't the correct filetype headers (eg, if someone renames a test.png as test.jpg it will still have the .png headers). Try creating a new test.jpg file using an image editing program and see if it works.



回答3:

An answer that worked for me was to work around the image altogether and trearit as a string.

Ill try to do it the standard way, but if it doesnt work, try it as a string

      $src = imagecreatefromjpeg($file);
      if (!$src) {
      $src = imagecreatefromstring(file_get_contents($file));
      }

There are apparently some issue wilth older versions or combos of GD an PHP.

In my case I had an image using a newer version/compression of jpeg 7 I think.



标签: php gd jpeg