我得到了一個.png圖像的URL,需要下載並設置爲ImageView的源。我是迄今爲止的初學者,所以有幾件事我不明白: 1)我在哪裏存儲文件? 2)如何將它設置爲Java代碼中的ImageView? 3)如何正確覆蓋AsyncTask方法?Android:如何使用Async下載.png文件並將其設置爲ImageView?
在此先感謝,非常感謝任何幫助。
我得到了一個.png圖像的URL,需要下載並設置爲ImageView的源。我是迄今爲止的初學者,所以有幾件事我不明白: 1)我在哪裏存儲文件? 2)如何將它設置爲Java代碼中的ImageView? 3)如何正確覆蓋AsyncTask方法?Android:如何使用Async下載.png文件並將其設置爲ImageView?
在此先感謝,非常感謝任何幫助。
我不確定你可以從下載中明確地建立一個PNG。然而,這裏是我用下載圖片,並顯示他們到Imageviews:
首先,你下載的圖像:
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
,然後創建一個位圖和它關聯到的ImageView:
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
就是這樣。
編輯
其實,你可以通過這樣的文件保存:
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
您可以明確地建立從下載一個PNG。
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100
是您的壓縮(PNG的一般都是無損因此100%)
out
是你的FileOutputStream中您要保存爲PNG的文件。