我是一个php noob,被迫向现有的php服务器添加次要功能。我的任务是让我的php服务器将图像列表返回给客户端,然后将其显示在页面上。
我的JavaScript客户端代码在这里:
const http = new XMLHttpRequest();
const url = "http://myaddress.com/myphpserver?";
http.open("GET", url);
http.send();
http.onreadystatechange = (e) => {
console.log(http.responseText);
}
我已经在服务器上尝试了以下代码:
$im = imagecreatefrompng("myImage.png");
header('Content-Type: image/png');
imagepng($im);
找到了here,但无济于事
我的http.responseText
始终为空。我会以错误的方式处理吗?
答案 0 :(得分:2)
不需要从PHP发送图像作为响应。
您应该改为返回带有URL的JSON图像。像这样:
{
"images": [{
"url": "http://myaddress.com/image_of_cat.jpg"
},
{
"url": "http://myaddress.com/image_of_cat.jpg"
}
]
}
然后使用javascript,只需使用该URL设置src
标记的<img>
属性即可。
现在,您只需要设置一个非常简单的服务器即可提供文件夹中的图像
答案 1 :(得分:1)
不回答OP的问题。回答那些实际上希望PHP发送原始图像而不是图像链接的Google员工:
<?php
/* Must be done before headers are sent */
header('Content-Type: image/jpeg');
$path = 'myfolder/myimage.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>
(部分使用another stackoverflow answer on a different question来编码图像,但是如果您已经从其他位置编码了该字符串,那么也可以替换$ base64字符串)