无法在 PHP 中使用 MIME 类型“image/x-ms-bmp”从 BMP 创建 GD 图像资源
题
我正在尝试从 BMP 图像创建 GD 图像资源,但是我没有运气。
所讨论的 BMP 图像是使用 Photoshop 创建并保存的。我也尝试了在网上找到的几个 BMP,它们给出了相同的结果。
getimagesize() 告诉我 BMP 图像的图像类型为 IMAGETYPE_BMP (6),MIME 类型为“image/x-ms-bmp”。
我尝试通过 imagecreatefromwbmp() 和 imagecreatefromxbm() 运行图像,但都无法识别它。我还尝试通过 imagecreatefromstring() 运行它,但错误提示“数据不是可识别的格式”。
我在 Windows 机器上运行 XAMPP,运行 PHP 5.3.1 和 GD 2.0.34,并启用 WBMP 和 XBM 支持。我还在运行 PHP 5.2.6 和 GD 2.0.34 且启用了 WBMP 和 XBM 支持的 Linux 服务器上尝试过此操作,结果相同。
有什么想法可以如何从此 BMP 创建 GD 图像资源吗?实际上可能吗?
解决方案
据我所知,它不支持BMP图像。这 imagecreatefromwbmp()
方法用于处理无线位图 (WBMP) 文件,而不是您那里的普通 BMP。这 imagecreatefromxbm()
用于处理 XBM 格式(同样,与 BMP 不同)。
我会通过重新打开 Photoshop 并重新保存为 PNG 或 JPG 来解决此问题。假设您已安装/编译了具有适当支持的 PHP,您将能够很好地使用其中一种或两种图像格式。
其他提示
Github 上有一个新的开源项目,允许在 PHP 中读取和保存 BMP 文件(和其他文件格式)。它非常容易使用。
该项目名为 PHP 图像魔术师.
您正在寻找的解决方案在这里:http://tr.php.net/imagecreate
滚动到下面的注释以找到名为“的函数”从BMP创建图像”。它将帮助您从 bmp 图像创建图像。
创建图像后,您可以使用 图像jpeg() 函数将图像保存为 jpeg 格式。
使用功能:
function imagecreatefrombmp( $filename )
{
$file = fopen( $filename, "rb" );
$read = fread( $file, 10 );
while( !feof( $file ) && $read != "" )
{
$read .= fread( $file, 1024 );
}
$temp = unpack( "H*", $read );
$hex = $temp[1];
$header = substr( $hex, 0, 104 );
$body = str_split( substr( $hex, 108 ), 6 );
if( substr( $header, 0, 4 ) == "424d" )
{
$header = substr( $header, 4 );
// Remove some stuff?
$header = substr( $header, 32 );
// Get the width
$width = hexdec( substr( $header, 0, 2 ) );
// Remove some stuff?
$header = substr( $header, 8 );
// Get the height
$height = hexdec( substr( $header, 0, 2 ) );
unset( $header );
}
$x = 0;
$y = 1;
$image = imagecreatetruecolor( $width, $height );
foreach( $body as $rgb )
{
$r = hexdec( substr( $rgb, 4, 2 ) );
$g = hexdec( substr( $rgb, 2, 2 ) );
$b = hexdec( substr( $rgb, 0, 2 ) );
$color = imagecolorallocate( $image, $r, $g, $b );
imagesetpixel( $image, $x, $height-$y, $color );
$x++;
if( $x >= $width )
{
$x = 0;
$y++;
}
}
return $image;
}