我有一张.png图片的URL需要下载,并将其设置为ImageView的来源。我是一个初学者,有几个问题不明白:
1)我应该把文件存储在哪里?
2)如何在Java代码中将其设置为ImageView?
3)如何正确地重写AsyncTask方法?
谢谢提前,非常感谢任何形式的帮助。
谢谢提前,非常感谢任何形式的帮助。
我不确定您是否可以直接从下载构建一个png。但是这是我用来下载图像并将其显示在ImageView中的方法:
首先,您需要下载图像:
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;
}
}
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();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100
是你的压缩比(PNG通常是无损压缩,所以为100%)
out
是你要保存PNG文件的FileOutputStream。