在java/android中,如何从位图字节数组中提取每个像素的颜色值,并将一个颜色通道存储在另一个字节数组中?

wbgh16ku  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(317)

嗨,我想提取整数颜色值为每个像素出一个字节数组,这类似于位图。
有时,尤其是在旧设备上,我会遇到outofmemory异常。我假设这个异常是由于位图内部存储的方式引起的,因为在较新的设备(api 26及以上)上,位图存储在本机堆中,而在较旧的设备上,像素数据存储在dalvik堆中。
我使用此代码提取像素颜色值:

  1. //here I am reading in my bitmap from the disk
  2. byte[] bytes = byteArrayOutputStream.toByteArray();
  3. //convert byte array to Bitmap
  4. Bitmap inputBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  5. //make it mutable
  6. inputBitmap = inputBitmap.copy(Bitmap.Config.ARGB_8888, true);
  7. //create color pixel array (1 int value resembles the color value of the pixel)
  8. int[] pixels = new int[width * height];
  9. //get the color values from the bitmap
  10. inputBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
  11. //I only need the green color values so to store it I need another byte array
  12. byte [] buffer = new byte[width*height];
  13. //store the green value in the new byte buffer array where one byte resembles the green proportion of the origin color pixel
  14. for(int i = 0; i < pixels.length; i++) {
  15. buffer[i] = (byte) ((Color.green(pixels[i]))-128);
  16. }

此代码在较新的设备上运行得非常好,但在内存有限的较旧设备上,它将引发oom异常。
有没有什么有效的方法可以只从起始字节数组中提取绿色值,而不创建占用内存的位图示例?
当然,上面的代码是异步运行的,并且对很多位图使用多核。因此,我需要一种有效的方法从字节数组中提取绿色值,并将颜色值存储在字节数组中:

  1. private byte[] getGreenColorValues(byte[] bitmapFromDisk){
  2. ...
  3. return greenColorValuesArray;
  4. }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题