2012-11-20 54 views
2

我是Android和Java的新手。我一直在研究我的任務,即Image Downloader。我必須使用進度條下載圖像並在網格視圖中顯示它們。我創建了兩個類1. URLImageAdapter 2. CacheActivity。一切正常,但現在我想將這些圖像保存到SD卡。我一直在尋找應該做什麼方法和更改?任何幫助?謝謝。 我已在Android清單文件中添加權限。Android將多張圖片保存到SD卡中

public class URLImageAdapter extends BaseAdapter { 

private class Image { 
    String url; 
    Bitmap thumb; 
} 

private Image[] images; 
private Context myContext; 
public LoadThumbsTask thumbnailGen; 
private Object previousList; 


public URLImageAdapter(Context c) { 
    myContext = c; 
    thumbnailGen = new LoadThumbsTask(); 

    if (previousList != null) { 
     images = (Image[]) previousList; 
     thumbnailGen.execute(images); 
     return; 
    } 

    images = new Image[imageURLs.length]; 

    for (int i = 0, j = imageURLs.length; i < j; i++) { 
     images[i] = new Image(); 
     images[i].url = imageURLs[i]; 
    } 

    thumbnailGen.execute(images); 

} 

public int getCount() { 
    return images.length; 
} 

public Object getItem(int position) { 
    return images[position].url; 
} 

public long getItemId(int position) { 
    return position; 
} 

public Object getData() { 
    if (thumbnailGen != null 
      && thumbnailGen.getStatus() != AsyncTask.Status.FINISHED) { 
     thumbnailGen.cancel(true); 
    } 

    return images; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    ImageView imgView; 

    Image cached = images[position]; 

    if (convertView == null) { 

     imgView = new ImageView(myContext); 
     imgView.setLayoutParams(new GridView.LayoutParams(100, 100)); 

    } else { 

     imgView = (ImageView) convertView; 

    } 

    if (cached.thumb == null) { 

     imgView.setImageResource(R.drawable.ic_action_search); 
     imgView.setScaleType(ScaleType.CENTER); 

    } else { 

     imgView.setScaleType(ScaleType.FIT_CENTER); 
     imgView.setImageBitmap(cached.thumb); 

    } 

    return imgView; 
} 

private void cacheUpdated() { 
    this.notifyDataSetChanged(); 
} 


private Bitmap loadThumb(String url) { 

    Bitmap thumb = null; 

    BitmapFactory.Options opts = new BitmapFactory.Options(); 
    opts.inSampleSize = 4; 

    try { 

     URL u = new URL(url); 
     URLConnection c = u.openConnection(); 
     c.connect(); 

     BufferedInputStream stream = new BufferedInputStream(
       c.getInputStream()); 

     thumb = BitmapFactory.decodeStream(stream, null, opts); 


     stream.close(); 

    } catch (MalformedURLException e) { 
     Log.e("ERROR", "malformed url: " + url); 
    } catch (IOException e) { 
     Log.e("ERROR", "An error has occurred downloading the image: " 
       + url); 
    } 

    return thumb; 
} 

private class LoadThumbsTask extends AsyncTask<Image, Void, Void> { 

    /*private ProgressDialog dialog; 
     @Override 
     protected void onPreExecute() { 
     this.dialog = ProgressDialog.show(myContext, "Please wait", 
      "Downloading.....", true); 
       } 

      @Override 
      protected void onPostExecute(Void unused) { 
    //Intent for next activity 
    this.dialog.dismiss(); 
    }*/ 

    @Override 
    protected Void doInBackground(Image... cache) { 

     BitmapFactory.Options opts = new BitmapFactory.Options(); 
     opts.inSampleSize = 4; 

     for (Image i : cache) { 

      if (isCancelled()) 
       return null; 

      if (i.thumb != null) 
       continue; 

      SystemClock.sleep(500); 

      i.thumb = loadThumb(i.url); 

      publishProgress(); 
     } 

     return null; 

    } 

    @Override 
    protected void onProgressUpdate(Void... param) { 
     cacheUpdated(); 
    } 
} 

private String[] imageURLs = { 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2851.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3226.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3228.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3251.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3268.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3275.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3346.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3365.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3374.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3385.jpg", 
     "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3392.jpg", }; 
} 

CacheActivity

public class CacheActivity extends Activity { 

Button btnStartProgress; 
ProgressDialog progressBar; 
private int progressBarStatus = 0; 
private Handler progressBarHandler = new Handler(); 
private GridView gridview; 
private long fileSize = 0; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_cache); 
    gridview = (GridView) findViewById(R.id.grid_view); 
    addListenerOnButton(); 
} 




public void addListenerOnButton() { 

    btnStartProgress = (Button) findViewById(R.id.btnStartProgress); 
    btnStartProgress.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 

      progressBar = new ProgressDialog(v.getContext()); 
      progressBar.setCancelable(true); 
      progressBar.setMessage("File downloading ..."); 
      progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      progressBar.setProgress(0); 
      progressBar.setMax(100); 
      progressBar.show(); 

      progressBarStatus = 0; 

      fileSize = 0; 

      new Thread(new Runnable() { 
       public void run() { 
        while (progressBarStatus < 100) { 

         progressBarStatus = doInBackground(); 


         try { 
          Thread.sleep(7500); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 

         progressBarHandler.post(new Runnable() { 
          public void run() { 
           progressBar.setProgress(progressBarStatus); 
          } 
         }); 
        } 

        if (progressBarStatus >= 100) { 

         try { 
          Thread.sleep(450); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 

         progressBar.dismiss(); 

        } 
       } 
      }).start(); 
      try { 
       gridview.setAdapter(new URLImageAdapter(CacheActivity.this)); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

    }); 

} 

public int doInBackground() { 

    while (fileSize <= 1000000) { 

     fileSize++; 

     if (fileSize == 100000) { 
      return 10; 
     } else if (fileSize == 200000) { 
      return 20; 
     } else if (fileSize == 300000) { 
      return 30; 
     }else if (fileSize == 400000) { 
      return 40; 
     }else if (fileSize == 500000) { 
      return 50; 
     }else if (fileSize == 600000) { 
      return 60; 
     }else if (fileSize == 700000) { 
      return 70; 
     }else if (fileSize == 800000) { 
      return 80; 
     }else if (fileSize == 900000) { 
      return 90; 
     } 

    } 

    return 100; 

} 

} 

回答

2

 imgView.setScaleType(ScaleType.FIT_CENTER); 
     imgView.setImageBitmap(cached.thumb); 
     saveDataInSdCard(cached.thumb,position); 


private void saveDataInSdCard(Bitmap bt,int i) { 
    OutputStream fOut = null; 
    Uri outputFileUri; 
    try { 
     File root = new File(Environment.getExternalStorageDirectory() 
       + File.separator + "urFlodername" + File.separator); 
     root.mkdirs(); 
     sdImageMainDirectory = new File(root,i+"myPicName.jpg"); 
     outputFileUri = Uri.fromFile(sdImageMainDirectory); 
     fOut = new FileOutputStream(sdImageMainDirectory); 
    } catch (Exception e) { 

    } 

    Bitmap bm =bt; 
    try { 
     bm.compress(Bitmap.CompressFormat.PNG, 100, fOut); 
     fOut.flush(); 
     fOut.close(); 
    } catch (Exception e) { 
    }  

} 



add permission  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
1

基本上你已經下載的圖像加載到一個位圖。所以你的大部分工作都完成了。接下來你需要做的是

OutputStream fout = null; 
       File file = new File(name); 
       try { 
        fout = new FileOutputStream(file); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
       thumb.compress(Bitmap.CompressFormat.JPEG, 100, fout); 
       try { 
        fout.flush(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        fout.close(); 
       }      
+0

但我應該在哪裏應用此方法?請你能更詳細和具體。請 –

+0

一旦您的下載完成並且位圖加載了流,請應用此方法。 –

+1

謝謝羅伊斯頓平託 –

1

http://negativeprobability.blogspot.in/2011/08/lazy-loading-of-images-in-listview.html

imagecursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + ""); 

下調用此之下梅索德在getView()上面的鏈接將幫助你在做一些更好的改變您的碼。一種常見的情況是將圖像添加到Listview。例如,如果您正在製作雞尾酒配方應用程序,則需要在雞尾酒名稱旁邊添加圖片。有時應該從互聯網上檢索圖像,然後顯示。不幸的是,這很難做到。如果你試過了,你可能會注意到性能問題,或者一些奇怪的故障。在本教程中,我將向您展示如何下載圖像並顯示它們。我們也會討論一些陷阱,比如回收和併發。

+0

謝謝你kailash pawar –