使用json_encode和PHP处理base64编码图像
My PHP class returns a small base64 encoded image, link this:
class Service
{
function getLogo()
{
$image = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c
QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA";
return 'data:image/png;base64,' . $image;
}
}
Returning the image using json_encode
will add
after each line of $image
:
$service = new Service();
$response = array('name' => $service->getName(), 'logo' => $service->getLogo());
header('Content-type: application/json');
echo json_encode($response);
How to handle it correctly?
我的PHP类返回一个小的base64编码图像,链接: p>
class Service
{
函数getLogo()
{
$ image =“iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8 / 9hAAAAAXNSR0IArs4c
QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAAAAAAAgAgAgAAHAwA”;
返回'data:image / png; base64,'。 $ image;
}
}
code> pre>
使用 json_encode code>返回图像将添加
code >在每行 $ image code>之后: p>
$ service = new Service();
$ response = array('name'=> $ service-> getName(),'logo'=> $ service-> getLogo());
header('Content-type:application / json');
echo json_encode($ response);
pre>
如何正确处理? p>
div>
You've mangled your base64 data by splitting it across two lines. it should be
function getLogo() {
$image = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4cQAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA";
return 'data:image/png;base64,' . $image;
}
with no line breaks.
The answer is given by Marc B. This is just a comment. If code formatting really is that important to you that you can't tolerate long lines (why?), you could always format the PHP thus:
class Service
{
function getLogo()
{
$image = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c';
$image .= 'QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA';
return 'data:image/png;base64,' . $image;
}
}