我有一臺服務器(我使用GlassFish)。我能夠發送JSON或XML等與http到我的Android設備。我看到一個例子,從android設備上傳一張照片到服務器。這將我選擇的圖像轉換爲字節,轉換爲字符串並返回到我的服務器。所以我可以把它放在我的電腦(服務器)上。 現在我只是想要相反的:從我的電腦獲取圖片並使用URL獲取圖像(位圖)到imageview。但用調試bmp似乎是「空」。谷歌說,因爲我的形象不是一個有效的位圖(所以也許我的服務器編碼是錯的?)。 我需要更改此代碼才能使其工作?將圖片從服務器下載到android並在imageview中顯示
Server代碼:
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;
}
}
,這是Android側(機器人工作室):
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());
}
}
}
我們需要你的日誌! –
使用https://github.com/square/picasso。畢加索易於使用。 – MASh
我沒有看到返回編碼的圖像點。爲什麼你不只是在Android部分返回url,你可以加載它? –