android - 以良好的质量和内存效率从资源中缩小位图

标签 android resources bitmap scale

我想缩小 500x500 像素的资源以始终适应由屏幕宽度决定的特定尺寸。

目前我使用来自 Android 开发者网站 ( Loading Large Bitmaps Efficiently ) 的代码,但质量不如我在 ImageView 中使用 500x500px 资源(作为 xml 中的源)和只缩放 ImageView 而不是位图。

但它很慢,我也想缩放 Bitmap,以提高内存效率和速度。

编辑:我想要缩放的可绘制对象位于我应用程序的 drawable 文件夹中。

Edit2:我目前的方法。

enter image description here

左图是来自Loading Large Bitmaps Efficiently的方法没有任何修改。中心图像是使用@Salman Zaidi 提供的方法完成的,稍作修改:o.inPreferredConfig = Config.ARGB_8888;o2.inPreferredConfig = Config.ARGB_8888;

右边的图像是 ImageView ,其中图像源在 xml 中定义,我希望通过缩放位图达到质量。

最佳答案

private Bitmap decodeImage(File f) {
    Bitmap b = null;
    try {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

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

        float sc = 0.0f;
        int scale = 1;
        //if image height is greater than width
        if (o.outHeight > o.outWidth) {
            sc = o.outHeight / 400;
            scale = Math.round(sc);
        } 
        //if image width is greater than height
        else {
            sc = o.outWidth / 400;
            scale = Math.round(sc);
        }

        // 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 (IOException e) {
    }
    return b;
}

此处“400”是新宽度(如果图像处于纵向模式)或新高度(如果图像处于横向模式)。您可以设置自己选择的值。缩放位图不会占用太多内存空间。

关于android - 以良好的质量和内存效率从资源中缩小位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199671/

相关文章:

android - Android NDK 的 ARM NEON 调试

java - 在 Eclipse 中链接文本资源

image - 将位图图像加载到特定大小

c# - C#中int数组转BMP

algorithm - 水平翻转一位位图线

android - 如何在 onSaveInstanceState(Bundle outState) 中保存 ListView,以便我可以在 Android 中恢复它?

Java:有关可运行的帮助

ruby - 学习更高级的 Ruby OOP 构造的最佳方法是什么?

java - 如何在java/android中解密大文件

elasticsearch - Elasticsearch ES_Java_Opts和Kubernetes资源限制之间有什么关系