我有一个服务器(我使用 GlassFish)。我可以使用 http 将 Json 或 XML 等发送到我的 android 设备。我看到了一个将图片从我的 android 设备上传到服务器的示例。将我选择的图像转换为字节,转换为字符串并返回到我的服务器。所以我可以把它放在我的电脑(服务器)上。现在我只想要相反的东西:从我的 PC 获取图片并使用 URL 将图像(此处为位图)获取到 imageview。但调试 bmp 似乎是“空”。谷歌说这是因为我的图像不是有效的位图(所以我的服务器编码可能有问题?)。我需要对此代码进行哪些更改才能使其正常工作?
服务器代码:
public class getImage{
String imageDataString = null;
@GET
@Path("imageid/{id}")
public String findImageById(@PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
这是安卓端(安卓工作室):
public class XMLTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
原文由 Axxeption 发布,翻译遵循 CC BY-SA 4.0 许可协议
您尝试过
HttpURlConnection
吗?这是一个示例代码:
我希望我能帮忙