如何获得drawable的id?

时间:2013-09-27 08:00:13

标签: android bitmap resize drawable identifier

我搜索一种方法来有效地调整图像大小,避免“OutOfMemory”。 为此,我尝试了这种方法:http://developer.android.com/training/displaying-bitmaps/index.html 要使用这些方法,我必须有一个可绘制的标识符,所以我创建一个类似的drawable:

Drawable image = Drawable.createFromPath(pathName);

现在我不知道如何获得可绘制的标识符。 方法getIdentifier()意味着有可绘制的名称,但我没有。

2 个答案:

答案 0 :(得分:0)

  

要使用这些方法,我必须有一个可绘制的标识符,所以我创建一个类似的drawable:

     

Drawable image = Drawable.createFromPath(pathName);

首先,您不需要创建drawable。其次,如果您的drawable文件夹中没有图像,则不应使用

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.

答案 1 :(得分:0)

感谢您的回答。 在#39; ve中最终选择此方法来调整图片大小:

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());
            }
        }
    }
相关问题