我需要从远程服务器上的映像创建一个ImageIcon。当我用像http://www.server.com/1.png
这样的网址加载它时,它工作得很好。
但最近服务器发生了变化,图像存储在web根目录之外,必须通过http://www.server.com/get_image.php?id=1
之类的东西访问,get_image.php会输出正确的标题来提供图像。当我用这种类型的URL创建一个ImageIcon时,它加载失败,没有抛出任何异常,getImageLoadStatus()返回MediaTracker.ERRORED。
我该怎么做,有什么想法吗?
谢谢。
编辑:这是Java代码。
ImageIcon labelIcon = new ImageIcon(new URL(IMAGE_URL));
System.out.println(labelIcon.getImageLoadStatus());
我也尝试了以下方法,但也不起作用。
ImageIcon labelIcon = new ImageIcon();
BufferedImage image = ImageIO.read(new URL(IMAGE_URL));
labelIcon.setImage(image);
编辑:这是来自get_image.php的代码。$DB是global.php中包含的一个对象,用于与MySQL数据库交互。我已经验证了返回的MIME类型是image/png。
<?php
if (isset($_GET['uid']))
{
require_once('./include/global.php');
getUpload(intval($_GET['uid']));
}
function getUpload($id)
{
global $DB;
$query = "SELECT `name`, `mime_type` FROM `uploads` WHERE `id` = " . $id . " LIMIT 1";
$arrUpload = $DB->getSingleRecord($query);
if (count($arrUpload) > 0)
{
$file = UPLOADS_ROOT . $arrUpload['name'];
header("Content-type: " . $arrUpload['mime_type']);
header("Content-Disposition: filename=" . $arrUpload['name']);
readfile($file);
}
else
{
header("HTTP/1.1 404 Not Found");
}
die();
}
?>
发布于 2010-01-21 23:30:49
ImageIcon(URL)
可能失败的原因之一是响应没有返回状态200。确保URL没有返回重定向(状态301/302)左右。另外,请确保请求参数名称正确。您在URL中使用了id
,但PHP脚本要求使用uid
。
要想了解一下Java代码实际得到的响应头,可以试试下面这个:
URL url = new URL("http://www.server.com/get_image.php?id=1");
URLConnection connection = url.openConnection();
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
发布于 2010-01-21 22:56:34
服务器可能返回了错误的内容类型:请确保在响应中将content-type标头正确设置为image/png
。
https://stackoverflow.com/questions/2113541
复制相似问题