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


Trying to encode an image in base64 after resizing

在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 );

我做错了什么吗?

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

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

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