我想知道是否有一种方法可以将图像编码为base64(如果它是一个资源)
例如,如果我使用GD加载图像
$image = imagecreatefromjpeg("captcha/$captcha-$num.jpg");
// Add some filters
imagefilter($image, IMG_FILTER_PIXELATE, 1, true);
imagefilter($image, IMG_FILTER_MEAN_REMOVAL);
如果这是我的代码而不是保存图像并使用它来显示它
<img src='someimage.jpg'>
我希望将其显示为数据URI而不必保存它,例如
<img data='src="data:image/jpeg;base64,BASE64_HERE'>
我怎样才能做到这一点?
解决方法:
$image = imagecreatefromjpeg("captcha/$captcha-$num.jpg");
// Add some filters
imagefilter($image, IMG_FILTER_PIXELATE, 1, true);
imagefilter($image, IMG_FILTER_MEAN_REMOVAL);
ob_start(); // Let's start output buffering.
imagejpeg($image); //This will normally output the image, but because of ob_start(), it won't.
$contents = ob_get_contents(); //Instead, output above is saved to $contents
ob_end_clean(); //End the output buffer.
$dataUri = "data:image/jpeg;base64," . base64_encode($contents);