如何以最快的方式将图像URL转换为位图并保存?

时间:2018-06-11 11:33:07

标签: android file url bitmapimage

从图片bitmap获取url在使用时需要花费太多时间 - BitmapFactory.decodeStream(url.openConnection().getInputStream())

有没有更好的方法将网址转换为bitmap并在设备中保存image? 我一直在使用多种方法来保存像asynctask,picasso等图像。所有这些都需要花费太多时间。这就是为什么我不得不问这个问题。

3 个答案:

答案 0 :(得分:0)

试试这段代码。它有用...... 它将Downlaod图像形式的url并保存在移动设备的SD卡中

try
 {   
      URL url =  new URL("Enter the URL to be downloaded");
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);                   
  urlConnection.connect();                  
  File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
  String filename="downloadedFile.png";   
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot,filename);
  if(file.createNewFile())
  {
    file.createNewFile();
  }                 
  FileOutputStream fileOutput = new FileOutputStream(file);
  InputStream inputStream = urlConnection.getInputStream();
  int totalSize = urlConnection.getContentLength();
  int downloadedSize = 0;   
  byte[] buffer = new byte[1024];
  int bufferLength = 0;
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
  {                 
    fileOutput.write(buffer, 0, bufferLength);                  
    downloadedSize += bufferLength;                 
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }             
  fileOutput.close();
  if(downloadedSize==totalSize) filepath=file.getPath();    
} 
catch (MalformedURLException e) 
{
  e.printStackTrace();
} 
catch (IOException e)
{
  filepath=null;
  e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;

答案 1 :(得分:0)

您可以使用Picasso。从Bitmap加载Url并缓存它们很容易。

因此,它可以节省您的时间。

只是你要添加这一行。

Picasso.with(getContext()).load(Uri).into(ImageView);

答案 2 :(得分:0)

Glide.with(this)
                        .load(strUrl)
                        .into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                saveMyBitmap(((BitmapDrawable) resource).getBitmap());
                            }
                        });

从图像网址加载位图,就像这样..