[英]PHP convert an image made in the file into base64
I have an image that I have created by combining images based on database data, and was wondering hw to convert that to base 64. I tried this but the characters returned can not be decoded into an image: 我有一个通过基于数据库数据组合图像而创建的图像,并且想将硬件将其转换为base64。我尝试了此操作,但是返回的字符无法解码为图像:
$encode ="data:image/png";
imagepng($image);
echo (base64_encode($encode));
I saw this among others but that requires a path that I don't have. 我看到了这一点 ,但这需要一条我没有的道路。 Thanks for any help.
谢谢你的帮助。
The following will allow you to get the image data without having to create a temporary file (I've had nightmares with temporary files before when too many users were online...) 以下内容将使您无需创建临时文件即可获取图像数据(在有太多用户在线之前,我曾做过带有临时文件的噩梦...)
ob_start(function($c) {return "data:image/png;base64,".base64_encode($c);});
imagepng($image);
ob_end_flush();
This will output something similar to: 这将输出类似于:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAAAXNSR0IArs4c6QAAAAxQTFRFAGVygICA/8wz/+aZTn6FEAAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2wkZEwoSgxq4wwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAS0lEQVQI1w3EMQ3AMAwEwMdTEmWRSF68h0RQBIKl5vkUirdGX99wuKUPKkjJkfM4jueE+ivo7VW6wDCCq1VtEdtiIMY2BGlgwUU+P38ZK+RwskeQAAAAAElFTkSuQmCC
Which is suitable for use inside an <img src="..." />
. 适合在
<img src="..." />
。
// Define the function first
function ob_base64_encode($c) {
return "data:image/png;base64,".base64_encode($c);
}
// And pass its name as a string
ob_start('ob_base64_encode');
imagepng($image);
ob_end_flush();
You are encoding the string "data:image/png" - naturally you won't be able to decode it into an image. 您正在编码字符串“ data:image / png”-自然地您将无法将其解码为图像。 Assuming
$image
contains valid image data, you should be able to simply do 假设
$image
包含有效的图像数据,您应该能够简单地执行
imagepng($image, $temp_file_name);
base64_encode(file_get_contents($temp_file_name));
from manuals: http://php.net/manual/en/function.base64-encode.php#105200 从手册中获取: http : //php.net/manual/zh/function.base64-encode.php#105200
/**
* Returns base64 encoded string prepended by "data:image/"
*
* @param $filename string
* @param $filetype string
* @return string
*/
function base64_encode_image($filename=string, $filetype=string)
{
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype
. ';base64,' . base64_encode($imgbinary);
}
}
Function code by luke at lukeoliff.com. luke的功能代码,位于lukeoliff.com。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.