2011-08-25 61 views
0

這是我創建把位圖入高速緩存的方法..如何縮放位圖放置,並最初從緩存加載?

 //Caching method to cache images loaded from the URL's. 
    public void putBitmapInDiskCache(URI imageUri, Bitmap avatar) { 
      File cacheDir = new File(MainMenu.this.getCacheDir(), "thumbnails"); 
      cacheDir.mkdirs(); 
      File cacheFile = new File(cacheDir, ""+imageUri.hashCode()); 
      try {  
      cacheFile.createNewFile();  
      FileOutputStream fos = new FileOutputStream(cacheFile);  
      avatar.compress(CompressFormat.PNG, 100, fos); 


      fos.flush();  
      fos.close();  
      } catch (Exception e) {  
      Log.e("error", "Error when saving image to cache. ", e);  

      } 



      } 

唯一的問題是我最初設定的位圖的寬度和高度參數時,它被下載。但是當它被放入緩存並被拉出時,它就會失去寬度和高度,並變得很大。當它從屏幕上滾動時,它會再次正確設置。內在地失去了它的寬度和高度。

編輯:我用我的getimagefromCache()方法加載位圖。

public void getImagesfromCache() throws MalformedURLException{ 
if(new File(new File(this.getApplicationContext().getCacheDir(), "thumbnails"),"" + imageCacheUri.hashCode()).exists()){ 
String cacheFile = this.getApplicationContext().getCacheDir() +"/thumbnails/"+ imageCacheUri.hashCode(); 
      ImageView i = new ImageView(this.getApplicationContext()); 
      FileInputStream fis = null; 
      try { 
       fis = new FileInputStream(cacheFile); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      Bitmap bm = BitmapFactory.decodeStream(fis); 

      i.setImageBitmap(bm); 
      i.setTag(mImageURLs); 
      putBitmapInDiskCache(imageCacheUri, bm); 



     //Set the BaseAdapter to a gallery, holding the images 
      ((Gallery) findViewById(R.id.gallery)) 
       .setAdapter(new ImageAdapter(MainMenu.this)); 
+0

如何加載位圖圖像。看看代碼會更好 – Ronnie

+0

看看我的編輯 – yoshi24

+0

你爲什麼叫putBitmapInDiskCache得到? – Ronnie

回答

2

上有createBitmap方法,讓你調整你的位圖,這樣你就可以用你想要的分辨率將其存儲在Matrix參數。請參閱here(順便提一下,這是一本很好的教程)。

+0

你能提供與我的情況相關的代碼嗎? – yoshi24

+0

您是否注意到我在帖子中提供的鏈接?在那裏你可能會發現與我所說的相關的代碼。問題是你可以使用它來正確縮放你的Bitmap,所以它會達到你想要的分辨率。值得一試。鏈接(再次)是:http://www.anddev.org/resize_and_rotate_image_-_example-t621.html – Alesqui