chinabugotech/hutool · error · IllegalArgumentException
RGB must be 0~255!
Error message
RGB must be 0~255!
What it means
ColorUtil.toHex(int r, int g, int b) requires each channel in [0,255]. Any channel below 0 or above 255 throws IllegalArgumentException before formatting the hex color string.
Source
Thrown at hutool-core/src/main/java/cn/hutool/core/img/ColorUtil.java:50
* @return 16进制的颜色值,例如#fcf6d6
* @since 4.1.14
*/
public static String toHex(Color color) {
return toHex(color.getRed(), color.getGreen(), color.getBlue());
}
/**
* RGB颜色值转换成十六进制颜色码
*
* @param r 红(R)
* @param g 绿(G)
* @param b 蓝(B)
* @return 返回字符串形式的 十六进制颜色码 如
*/
public static String toHex(int r, int g, int b) {
// rgb 小于 255
if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
throw new IllegalArgumentException("RGB must be 0~255!");
}
return String.format("#%02X%02X%02X", r, g, b);
}
/**
* 将颜色值转换成具体的颜色类型 汇集了常用的颜色集,支持以下几种形式:
*
* <pre>
* 1. 颜色的英文名(大小写皆可)
* 2. 16进制表示,例如:#fcf6d6或者$fcf6d6
* 3. RGB形式,例如:13,148,252
* </pre>
* <p>
* 方法来自:com.lnwazg.kit
*
* @param colorName 颜色的英文名,16进制表示或RGB表示
* @return {@link Color}
* @since 4.1.14View on GitHub (pinned to 8870454b2a)
Solutions
- Clamp each channel to [0,255] with Math.max(0, Math.min(255, v)) before calling toHex.
- Validate/parse user-supplied RGB strings and reject or clamp out-of-range values explicitly.
- When extracting channels from a packed int, mask with 0xff to guarantee range.
Example fix
// before
String hex = ColorUtil.toHex(r, g, b); // r may be 300 or -5
// after
String hex = ColorUtil.toHex(clamp(r), clamp(g), clamp(b));
// where
int clamp(int v){ return Math.max(0, Math.min(255, v)); } Defensive patterns
Strategy: validation
Validate before calling
int clamp(int v){ return Math.max(0, Math.min(255, v)); }
// then ColorUtil.toHex(clamp(r), clamp(g), clamp(b)) Type guard
boolean validChannel(int v){ return v>=0 && v<=255; } Try / catch
try { hex = ColorUtil.toHex(r,g,b); }
catch (IllegalArgumentException e){ if(e.getMessage().contains("0~255")) { hex = ColorUtil.toHex(clamp(r),clamp(g),clamp(b)); } else throw e; } Prevention
- Always mask packed-int channels with 0xff.
- Clamp outputs of any RGB-space conversion.
- Validate parsed RGB strings before use.
When it happens
Trigger: Passing RGB values read from a signed computation that overflow (e.g. from getRGB bit-twiddling), negative values from arithmetic, or un-sanitized user input parsed from a string like '300,0,0'.
Common situations: Manual color parsing from text fields; converting HSB/CMYK to RGB without clamping; feeding raw int channels from color pickers.
Related errors
AI-assisted analysis of chinabugotech/hutool@8870454b2a (2026-08-14).
Data as JSON: /api/errors/7675a604c97d6f03.
Report an issue: GitHub.