2013-09-27 26 views
0

我搜索一種方法來有效地調整圖像大小,避免「OutOfMemory」。 要做到這一點,我已經試過這個方法:http://developer.android.com/training/displaying-bitmaps/index.html 要使用這些方法,我必須有一個繪製標識,所以我創建一個這樣的繪製:如何獲取drawable的id?

Drawable image = Drawable.createFromPath(pathName); 

現在我不知道怎麼弄可繪製的標識符。 方法getIdentifier()意味着有可繪名稱,但我hav'nt。

+0

? – pskink

+0

我需要ID使用mehod:BitmapFactory.decodeResource(res,drawableID,options); – Maxime

+0

@Maxime:你不能直接通過R.drawable.yourImageName獲取id嗎? – epiphany27

回答

0

要使用這些方法我必須有一個可拉伸的標識符,所以我創建一個這樣的可拉伸:

繪製的圖像= Drawable.createFromPath(pathName中);

首先,您不需要創建drawable。其次,如果你沒有在你的繪製文件夾中有一個形象則u不應使用

BitmapFactory.decodeResource(res, resId, options) 

BitmapFactory也有其他的方法,如

BitmapFactory.decodeFile (String filePath, options); //it takes your image filepath 
(in case your image is in Sdcard) as a string. 
or, 
BitmapFactory.decodeStream (InputStream, options); // if the image is placed in your asset folder instead of drawables. 
0

謝謝您的回答。 我終於選擇滿足這種方法來調整圖片:爲什麼YPU需要一個ID

private void resizeBitmap(String path) { 
     Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     int sampleSize = 0; 
     boolean done = false; 
     Bitmap source = null; 
     while (!done) { 
      options.inJustDecodeBounds = false; 
      sampleSize++; 
      try { 
       options.inSampleSize = sampleSize; 
       source = BitmapFactory.decodeFile(path, options); 
       done = true; 
      } catch (OutOfMemoryError e) { 

      } 
      if (sampleSize > 20) { 
       // Exit to avoid infinite loop 
       done = true; 
      } 
     } 
     if (source != null) { 
      try { 
       FileOutputStream out = new FileOutputStream(path); 
       source.compress(Bitmap.CompressFormat.JPEG, 90, out); 
       out.close(); 
      } catch (Exception e) { 
       Log.e("RESIZE PICTURE", "Unable to resize picture after download : "+e.getMessage()); 
      } 
     } 
    }