2016-12-01 21 views
-2

必须在recycleview上显示图像和贴纸列表(webp格式)。在imageview上显示贴纸时发生内存不足

要在imageView上显示贴纸,请使用[repository](https://github.com/EverythingMe/webp-android)。该存储库是在这个交(WebP for Android

贴纸文件是从外部存储readed建议 溶液之一,则转换为字节阵列中,通过使用存储库的库,字节数组转换为位图,最后的位图被示出在ImageView的。下面的代码转换标签文件为位图

private void ShowStickerOnImageView(String stickerPath){ 
File file = new File(stickerPath); 
int size = (int) file.length(); 
byte[] bytes = new byte[size]; 

BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file)); 
buf.read(bytes, 0, bytes.length); 
buf.close(); 

Bitmap bitmap = null; 
boolean NATIVE_WEB_P_SUPPORT = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; 
if (!NATIVE_WEB_P_SUPPORT) { 
    bitmap = WebPDecoder.getInstance().decodeWebP(bytes); 
} else { 
    bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
} 

holder.imageView.setImageBitmap(bitmap); 
} 

..... 

public Bitmap decodeWebP(byte[] encoded, int w, int h) { 
int[] width = new int[]{w}; 
int[] height = new int[]{h}; 

byte[] decoded = decodeRGBAnative(encoded, encoded.length, width, height); 
if (decoded.length == 0) return null; 

int[] pixels = new int[decoded.length/4]; 
ByteBuffer.wrap(decoded).asIntBuffer().get(pixels); 

return Bitmap.createBitmap(pixels, width[0], height[0], Bitmap.Config.ARGB_8888); 
} 

当“NATIVE_WEB_P_SUPPORT”是假的,“decodeWebP”方法被调用,这个方法做工精细的大部分时间,但有时“内存不足”的错误是在发生这种情况方法。大多数时候,这个错误是发生在这些线路

int[] pixels = new int[decoded.length/4]; 
ByteBuffer.wrap(decoded).asIntBuffer().get(pixels); 
return Bitmap.createBitmap(pixels, width[0], height[0], Bitmap.Config.ARGB_8888); 

我发现贴纸的文件,它的字节数组长度大,我可以减少标签的文件大小以编程方式?我想找到解决方案,以减少字节数组的大小。

回答

0

您正在创建一个Bitmap,它被用作原始大小,但应用于ImageView。降低BitmapView的大小:

Bitmap yourThumbnail= Bitmap.createScaledBitmap(
    theOriginalBitmap, 
    desiredWidth, 
    desiredHeight, 
    false 
); 

请注意:

public static Bitmap createBitmap(int colors[], int width, int height, Config config) { 
    return createBitmap(null, colors, 0, width, width, height, config); 
} 

会打电话的

public static Bitmap createBitmap(DisplayMetrics display, int colors[], 
     int offset, int stride, int width, int height, Config config) 

这会导致:

Bitmap bm = nativeCreate(colors, offset, stride, width, height, 
         config.nativeInt, false); 

基本上,你c annot在内存中创建一个巨大的Bitmap,无缘无故。如果这是针对手机的,则假定应用程序的大小为20 MB。 800 * 600 * 4图像,长度1920000字节。降低图像质量,例如使用RGB_565(每像素半个字节,与RGB_8888相比),或者预先重新缩放源位图。

+0

使用RGB_565会导致图像质量下降,特别是如果在贴纸中使用文本 –

+0

就像回答一样,您遇到的主要问题是创建比您的显示更大的“位图”。要么不加载它,改变原始的位图或文件,然后加载缩放版本,或者获得你的'View'大小,然后根据这个大小加载'Bitmap'。没有使用“预安卓4.0”默认库。原因是这样的,如果你需要在低资源设备上显示一个大的'Bitmap',请在google上寻找帮助,但是不要指望'Magically.load(largeBitmap)'函数 – Bonatti