从URL下载图像并将其保存到内部存储内存的最佳方式

Ume*_*wat 8 android

我正在开发一个应用程序,我想从URL下载图像.我需要立即下载这些图像并将其存储到内部存储中.有200多张图片供下载.请告诉我在最短的时间内下载这些图像的最佳方法.如果有任何第三方库,请告诉我们.

ast*_*ter 26

考虑将毕加索用于你的目的.我在我的一个项目中使用它.要在外部磁盘上保存图像,您可以使用以下命令:

 Picasso.with(mContext)
        .load(ImageUrl)
        .into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                try {
                    String root = Environment.getExternalStorageDirectory().toString();
                    File myDir = new File(root + "/yourDirectory");

                    if (!myDir.exists()) {
                        myDir.mkdirs();
                    }

                    String name = new Date().toString() + ".jpg";
                    myDir = new File(myDir, name);
                    FileOutputStream out = new FileOutputStream(myDir);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

                    out.flush();
                    out.close();                        
                } catch(Exception e){
                    // some action
                }
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        }
    );
Run Code Online (Sandbox Code Playgroud)

从这里您可以下载此库.


Joã*_*cos 7

你可以从这样的网址下载图像:

URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
Run Code Online (Sandbox Code Playgroud)

然后你可能想要保存图像,所以:

FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
Run Code Online (Sandbox Code Playgroud)