下载图像在Android应用程序中被破坏

Han*_*naa 2 android android-networking android-image android-internet

我只需要下载图像,但问题是图像损坏了!我找到了许多下载图像的方法,但仍然出现了这个问题.

我尝试这样做:

File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file2 = new File(path,"DemoPictureX.png");
InputStream is=(InputStream) new URL("http://androidsaveitem.appspot.com/downloadjpg").getContent();
OutputStream os = new FileOutputStream(file2);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);

is.close();
os.close();
Run Code Online (Sandbox Code Playgroud)

我认为它只是阅读图像中的一些行!

Tim*_*Tim 6

你需要一个循环并从流中读取一个较小的缓冲区(如1024字节).

  URL url = new URL("your url here");
  URLConnection connection = url.openConnection();
  InputStream is = connection.getInputStream();
  BufferedInputStream bis = new BufferedInputStream(is);
  FileOutputStream fos = new FileOutputStream(targetFile);
  byte buffer[] = new byte[1024];
  int read;
  while ((read = bis.read(buffer)) > 0) {
    fos.write(buffer, 0, read);
  }
  fos.flush();
  fos.close();
  bis.close();
  is.close();
Run Code Online (Sandbox Code Playgroud)

这应该适合你