更新于 2026/02/27

Java中获取到的颜色是负数

这几天写图片处理相关的代码的时候遇到个问题,BufferedImage.getRGB()的返回值有时会是负数

百度一番之后找到了原因:

颜色的取值范围0x00000000-0xffffffff,会超过int类型的最大值

为了能让其正常取值,超过int最大值的会变成 他本身 - 1 - 0xffffffff

这里我写了一段转化的代码供参考

/**
 * 处理颜色补码(- -> +)
 * 将可能为负的颜色转成正数的Long
 *
 * @param color 可能为负数的颜色
 * @return 经过转换的颜色
 */
fun fromRgb(color: Int): Long {
    return (if (color < 0) 0xffffffff + color + 1 else color).toLong()
}

/**
 * 处理颜色补码(+ -> -)
 * 将长度超过Int的颜色转成可能为负的Int颜色
 *
 * @param color 正数颜色, Long
 * @return 经过转换的颜色
 */
fun toRgb(color: Long): Int {
    return (if (color > Int.MAX_VALUE) (color - 1 - 0xffffffff) else color).toInt()
}