开发者

Trying to encode an image in base64 after resizing

开发者 https://www.devze.com 2023-04-07 00:40 出处:网络
In php, I\'m trying to encode an image in base64 after a resize. When I encode it directly with no resize it\'s working fine

In php, I'm trying to encode an image in base64 after a resize. When I encode it directly with no resize it's working fine

$bitmapNode = $dom->createElement( "b开发者_JAVA百科itmap" );
$bitmapNode->appendChild( $dom->createTextNode(base64_encode(file_get_contents($url)))  );
$root->appendChild( $bitmapNode );

But when I'm trying to do a resize before the encoding it doesn't work anymore and the content of the xml node is empty.

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

Is there something I'm doing wrong?


$im2 is just a GD resource handle. it is NOT the image data itself. To capture the resized image, you'll have to save it and then base64_encode that saved data:

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

Note the use of output buffering. The GD image functions do not have a method to directly return the resulting image data. You can only write to a file, or output directly to the browser. So using the ob functions lets you capture the data without having to resort to a temporary file.

0

精彩评论

暂无评论...
验证码 换一张
取 消