-4

我想从 url 下载图像并在存储后将其存储到内存中获取存储在内存中的图像并在 imageview 中显示

4

1 回答 1

1

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

  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);

 }

希望能帮助到你。

于 2016-05-31T06:11:07.603 回答