2011-08-25 67 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