我目前正在从位图中提取 RGB 值。在互联网上,样本看起来都非常相似:
int colour = bitmap.getPixel(x, y);
int red = Color.red(colour);
int blue = Color.blue(colour);
int green = Color.green(colour);
int alpha = Color.alpha(colour);
有一件事我不明白:每个人都在使用 int
来保存值。我正在考虑使用 short
来节省内存。有什么好的理由不使用我在这里缺少的 short
吗?将值转换为 short
不值得吗?
最佳答案
Is there any good reason not to use short that I am missing here?
在大多数情况下 int
,每个 int
四个 channel 更好。
Is it not worth casting the value to short?
这不值得。
TL;NR
这在很大程度上取决于您如何处理这些值:
如果你将它们存储在
short[]
中,这将比将它们存储在int[]
中更有效,假设你使用一个int
每个 channel 的颜色值。另外,请考虑 JeppeSRC 所说的:您可以只使用byte[]
并且,当您使用该值时,您将转换回具有零扩展的int
,如下所示:int channelColorValue = (int) myBytes[i] & 0xff;
这将防止使用错误的负值。
如果您只使用几个局部变量,那甚至没有关系,但请记住,在字节码级别,Java 仅对 32 或 64 个整数执行操作,请参阅 this .在这种情况下,使用
short
而不是int
不会增加内存,两者都需要 32 位。内存效率最高的解决方案实际上是将所有值保存在一个
int[]
中,每个 int 有 4 个 channel (alpha、红色、绿色、蓝色) .您可以解压缩int
并使用位操作选择单个 channel 颜色值,这正是您使用的方法所做的。示例:int alpha = color >>> 24;
关于android - 保存位图的 RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244038/