2010-07-28 49 views
4

我得到了一个.png图像的URL,需要下载并设置为ImageView的源。我是迄今为止的初学者,所以有几件事我不明白: 1)我在哪里存储文件? 2)如何将它设置为Java代码中的ImageView? 3)如何正确覆盖AsyncTask方法?Android:如何使用Async下载.png文件并将其设置为ImageView?

在此先感谢,非常感谢任何帮助。

回答

7

我不确定你可以从下载中明确地建立一个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(); 
4

您可以明确地建立从下载一个PNG。

bm.compress(Bitmap.CompressFormat.PNG, 100, out); 

100是您的压缩(PNG的一般都是无损因此100%)

out是你的FileOutputStream中您要保存为PNG的文件。

相关问题