繁体   English   中英

从drawable创建文件

[英]Create a file from drawable

我的可绘制文件夹中有大量资源。所有资源的大小都超过 500KB。 我必须在 srollView 中一次加载所有这 25 张图像。 像往常一样,我用完了 memory。 有没有办法以编程方式减小图像的大小。

我得到了这个 function 但它的参数是一个文件,我不知道如何从可绘制文件创建一个文件。


private Bitmap decodeFile(File f){
    Bitmap b = null;
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
    } catch (FileNotFoundException e) {
    }
    return b;
}

在经过多次遍历后,我必须通过这个屏幕循环多次 go,系统显示低 memory 并且它正在从堆栈中删除后面的其他视图,但我实际上需要它。 请帮我。

您可以使用以下代码从可绘制资源中打开 InputStream:

InputStream is = getResources().openRawResource(id);

这里id是您的可绘制资源的标识符。 例如: R.drawable.abc

现在使用这个输入 stream 你可以创建一个文件。 如果您还需要有关如何使用此输入 stream 创建文件的帮助,请告诉我。

更新:将数据写入文件:

try
    {
    File f=new File("your file name");
    InputStream inputStream = getResources().openRawResource(id);
    OutputStream out=new FileOutputStream(f);
    byte buf[]=new byte[1024];
    int len;
    while((len=inputStream.read(buf))>0)
    out.write(buf,0,len);
    out.close();
    inputStream.close();
    }
    catch (IOException e){}
    }

我喜欢快捷方式,所以我更喜欢使用

要从可绘制文件创建文件,请参阅

把这个放在你的build.gradle

compile 'id.zelory:compressor:1.0.4'

并且无论您想压缩图像放在哪里

 Bitmap compressedImageFile = Compressor.getDefault(context).compressToBitmap(your_file);

README.md 提供了更多信息。 对不起,6年后才给出答案。

兄弟有两种方法

  1. 最简单的一个使用一些 3rd 方库
  2. 或使用 Bitmap class 缩小可绘制对象

只需使用Bitmap.createScaledBitmap方法来压缩drawables

脚步:

// Step 1 加载drawable并将其转换为bitmap

Bitmap b = BitmapFactory.decodeResource( context, resId )

// 第 2 步重新缩放您的 Bitmap

Bitmap nBitmap = b.createScaledBitmap( getResources() , newHieght , newWidth , true );  

// 第 3 步从 bitmap 创建一个可绘制对象

BitmapDrawable drawable = new BitmapDrawable(nBitmap);

我强烈建议您使用第 3 部分库,因为这种方法非常昂贵

https://github.com/Tourenathan-G5organisation/SiliCompressor

我从@mudit 的回答中得到提示,并从 Input Stream 创建了可绘制对象。 然后将drawable加载到Adapter中的ImageView。

InputStream inputStream = mContext.getResources().openRawResource(R.drawable.your_id);

Bitmap b = BitmapFactory.decodeStream(inputStream);
b.setDensity(Bitmap.DENSITY_NONE);
Drawable d = new BitmapDrawable(b);
mImageView.setImageDrawable(d);

是解决方案的详细版本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM