什么可以导致php gd在调整大小后产生黑色图像?以下代码始终为每个有效的jpeg文件输出黑色图像.
<?php
$filename = 'test.jpg';
$percent = 0.5;
header('Content-Type: image/jpeg');
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb);
imagedestroy($thumb);
?>
Run Code Online (Sandbox Code Playgroud)
输出gd_info():
Array
(
[GD Version] => bundled (2.1.0 compatible)
[FreeType Support] => 1
[FreeType Linkage] => with freetype
[T1Lib Support] =>
[GIF Read Support] => 1
[GIF Create Support] => 1
[JPEG Support] => 1
[PNG Support] => 1
[WBMP Support] => 1
[XPM Support] =>
[XBM Support] => 1
[JIS-mapped Japanese Font Support] =>
)
Run Code Online (Sandbox Code Playgroud)
代码似乎在其他环境中工作.可能它与操作系统,安装包,库等有关?
研究
只是想重现你的情况.使用开箱即用的PHP和Apache运行代码显示以下内容
http://localhost/无法显示图像" ",因为它包含错误.
尽管浏览器告诉您存在一些错误,但由于响应中返回的标头Content-Type: image/jpeg因此迫使浏览器将其解释为图像,因此无法看到它们.通过删除header和设置以下将输出错误.
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
...
//header('Content-Type: image/jpeg');
...
Run Code Online (Sandbox Code Playgroud)
回答
什么可以导致php gd在调整大小后产生黑色图像?
由于gd_info输出证明GD扩展已加载,请检查文件名(linux是caseSensitive)和权限是否正确.如果Apache正在运行www-data(组)
sudo chown :www-data test.jpg && sudo chmod 660 test.jpg
Run Code Online (Sandbox Code Playgroud)
代码改进/解决方案
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
if (extension_loaded('gd') && function_exists('gd_info'))
{
$filename = 'test.jpg';
if (file_exists($filename) && is_readable($filename))
{
$percent = 0.5;
header('Content-Type: image/jpeg');
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb);
imagedestroy($thumb);
}
else
{
trigger_error('File or permission problems');
}
}
else
{
trigger_error('GD extension not loaded');
}
Run Code Online (Sandbox Code Playgroud)
评论
这应该用作临时解决方案(开发环境).恕我直言,错误应由中央错误处理程序处理,display_errors应该false在生产中.此外,Fatal error默认情况下会记录错误(在这种情况下会有错误) - 检查日志以获取更多(频繁,更好).此外,在linux(with apt)上,one-liner将在您的系统上安装GD:
sudo apt-get update && sudo apt-get install php5-gd && sudo /etc/init.d/apache2 restart
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2585 次 |
| 最近记录: |