调整大小后尝试在base64中编码图像

时间:2011-09-22 20:33:04

标签: php xml base64

在php中,我试图在调整大小后在base64中编码图像。当我直接对其进行编码而没有调整大小时,它工作正常

$bitmapNode = $dom->createElement( "bitmap" );
$bitmapNode->appendChild( $dom->createTextNode(base64_encode(file_get_contents($url)))  );
$root->appendChild( $bitmapNode );

但是当我在编码之前尝试进行调整大小时,它不再起作用,并且xml节点的内容为空。

$image = open_image($url);
if ($image === false) { die ('Unable to open image'); }
// Do the actual creation
$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled($im2, $image, 0, 0, 0, 0, 256, 256, imagesx($image), imagesy($image));
$bitmapNode = $dom->createElement( "bitmap" );
$bitmapNode->appendChild( $dom->createTextNode(base64_encode($im2)) );
$root->appendChild( $bitmapNode );

我有什么问题吗?

1 个答案:

答案 0 :(得分:2)

$im2只是一个GD资源句柄。它不是图像数据本身。要捕获已调整大小的图像,您必须保存它,然后保存保存数据的base64_encode:

imagecopyresample($im2 ....);
ob_start();
imagejpeg($im2, null);
$img = ob_get_clean();
$bitmapNode->appendChild($dom->createTextNode(base64_encode($img)));

注意使用输出缓冲。 GD图像功能没有直接返回结果图像数据的方法。您只能写入文件,或直接输出到浏览器。因此,使用ob函数可以捕获数据,而无需使用临时文件。

相关问题