android 从 url 下载图像存储在内存中,然后在 imageview 中显示该图像

android download the image from url store in internal memory then display that image in imageview

我想从url下载图片,存入内存后获取内存中的图片,并在imageview中显示

您可以使用此代码下载图片

  URL url = new URL(<your url>);
  InputStream in = new BufferedInputStream(url.openStream());
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  byte[] buf = new byte[1024];
  int n = in.read(buf);
 while (n!=-1)
 {
  out.write(buf, 0, n);
   n=in.read(buf)
  }
 out.close();
 in.close();
 byte[] response = out.toByteArray();

下面的代码将其保存到内部存储

  FileOutputStream fos = new FileOutputStream(filePath);
  fos.write(response);
  fos.close();

其中内部存储的文件路径是

  String filePath=getFilesDir().getPath() + File.separator + "image_" + <some unique identifier like int or string that is different for different images>

并在 imageView 中显示使用

  File imgFile = new  File(filePath);

if(imgFile.exists()){

Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

myImage.setImageBitmap(myBitmap);

 }

希望对您有所帮助。