代码之家  ›  专栏  ›  技术社区  ›  Athira

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

  •  0
  • Athira  · 技术社区  · 6 年前

    得到 bitmap url 使用时间太长- BitmapFactory.decodeStream(url.openConnection().getInputStream())

    有没有更好的方法将url转换为 位图 并且保存 image 在设备中?因为我的应用应该可以脱机工作。

    3 回复  |  直到 5 年前
        1
  •  0
  •   Parth Suthar    6 年前
    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());
                                }
                            });
    

    像这样从图像url加载位图。。

        2
  •  0
  •   AA Shakil    6 年前

    试试这个代码。它作品。。。 它会下载图片的网址并保存在手机的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;
    
        3
  •  0
  •   AA Shakil    6 年前

    你可以用 Picasso Bitmap Url 把它们藏起来。

    所以,它节省了你的时间。

    你只要加上这一行就行了。

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