[英]How to convert hex to rgb using Java?
如何在 Java 中將十六進制顏色轉換為 RGB 代碼? 大多數在 Google 中,示例是關於如何從 RGB 轉換為十六進制的。
實際上,有一種更簡單的(內置)方法可以做到這一點:
Color.decode("#FFCCEE");
我想這應該這樣做:
/**
*
* @param colorStr e.g. "#FFFFFF"
* @return
*/
public static Color hex2Rgb(String colorStr) {
return new Color(
Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
public static void main(String[] args) {
int hex = 0x123456;
int r = (hex & 0xFF0000) >> 16;
int g = (hex & 0xFF00) >> 8;
int b = (hex & 0xFF);
}
對於Android開發,我使用:
int color = Color.parseColor("#123456");
這是一個同時處理 RGB 和 RGBA 版本的版本:
/**
* Converts a hex string to a color. If it can't be converted null is returned.
* @param hex (i.e. #CCCCCCFF or CCCCCC)
* @return Color
*/
public static Color HexToColor(String hex)
{
hex = hex.replace("#", "");
switch (hex.length()) {
case 6:
return new Color(
Integer.valueOf(hex.substring(0, 2), 16),
Integer.valueOf(hex.substring(2, 4), 16),
Integer.valueOf(hex.substring(4, 6), 16));
case 8:
return new Color(
Integer.valueOf(hex.substring(0, 2), 16),
Integer.valueOf(hex.substring(2, 4), 16),
Integer.valueOf(hex.substring(4, 6), 16),
Integer.valueOf(hex.substring(6, 8), 16));
}
return null;
}
您可以簡單地執行以下操作:
public static int[] getRGB(final String rgb)
{
final int[] ret = new int[3];
for (int i = 0; i < 3; i++)
{
ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
}
return ret;
}
例如
getRGB("444444") = 68,68,68
getRGB("FFFFFF") = 255,255,255
十六進制顏色代碼是#RRGGBB
RR、GG、BB 是 0-255 范圍內的十六進制值
讓我們調用 RR XY 其中 X 和 Y 是十六進制字符 0-9A-F,A=10,F=15
十進制值為 X*16+Y
如果 RR = B7,則 B 的小數點為 11,因此值為 11*16 + 7 = 183
public int[] getRGB(String rgb){
int[] ret = new int[3];
for(int i=0; i<3; i++){
ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
}
return ret;
}
public int hexToInt(char a, char b){
int x = a < 65 ? a-48 : a-55;
int y = b < 65 ? b-48 : b-55;
return x*16+y;
}
對於JavaFX
import javafx.scene.paint.Color;
.
Color whiteColor = Color.valueOf("#ffffff");
許多這些解決方案都有效,但這是另一種選擇。
String hex="#00FF00"; // green
long thisCol=Long.decode(hex)+4278190080L;
int useColour=(int)thisCol;
如果您不添加 4278190080 (#FF000000),則顏色的 Alpha 為 0 並且不會顯示。
將其轉換為整數,然后根據原始十六進制字符串的長度(分別為 3、6、9 或 12)將其 divmod 兩次 16、256、4096 或 65536。
對於 Android Kotlin開發人員:
"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
fun String?.longARGB(): String? {
if (this == null || !startsWith("#")) return null
// #RRGGBB or #AARRGGBB
if (length == 7 || length == 9) return this
// #RGB or #ARGB
if (length in 4..5) {
val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
if (length == 5) {
return "$rgb${this[4]}${this[4]}"
}
return rgb
}
return null
}
要詳細說明@xhh 提供的答案,您可以在返回之前附加紅色、綠色和藍色以將字符串格式化為“rgb(0,0,0)”。
/**
*
* @param colorStr e.g. "#FFFFFF"
* @return String - formatted "rgb(0,0,0)"
*/
public static String hex2Rgb(String colorStr) {
Color c = new Color(
Integer.valueOf(hexString.substring(1, 3), 16),
Integer.valueOf(hexString.substring(3, 5), 16),
Integer.valueOf(hexString.substring(5, 7), 16));
StringBuffer sb = new StringBuffer();
sb.append("rgb(");
sb.append(c.getRed());
sb.append(",");
sb.append(c.getGreen());
sb.append(",");
sb.append(c.getBlue());
sb.append(")");
return sb.toString();
}
如果您不想使用 AWT Color.decode,則只需復制該方法的內容:
int i = Integer.decode("#FFFFFF");
int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};
Integer.decode 處理 # 或 0x,具體取決於字符串的格式
最簡單的方法:
// 0000FF
public static Color hex2Rgb(String colorStr) {
return new Color(Integer.valueOf(colorStr, 16));
}
public static Color hex2Rgb(String colorStr) {
try {
// Create the color
return new Color(
// Using Integer.parseInt() with a radix of 16
// on string elements of 2 characters. Example: "FF 05 E5"
Integer.parseInt(colorStr.substring(0, 2), 16),
Integer.parseInt(colorStr.substring(2, 4), 16),
Integer.parseInt(colorStr.substring(4, 6), 16));
} catch (StringIndexOutOfBoundsException e){
// If a string with a length smaller than 6 is inputted
return new Color(0,0,0);
}
}
public static String rgbToHex(Color color) {
// Integer.toHexString(), built in Java method Use this to add a second 0 if the
// .Get the different RGB values and convert them. output will only be one character.
return Integer.toHexString(color.getRed()).toUpperCase() + (color.getRed() < 16 ? 0 : "") + // Add String
Integer.toHexString(color.getGreen()).toUpperCase() + (color.getGreen() < 16 ? 0 : "") +
Integer.toHexString(color.getBlue()).toUpperCase() + (color.getBlue() < 16 ? 0 : "");
}
我認為這會奏效。
十六進制是基數 16,因此您可以使用 parseLong 使用基數 16 解析字符串:
Color newColor = new Color((int) Long.parseLong("FF7F0055", 16));
如果需要解碼以下格式#RRGGBBAA 的 HEXA 字符串,可以使用以下命令:
private static Color convert(String hexa) {
var value = Long.decode(hexa);
return new Color(
(int) (value >> 24) & 0xFF,
(int) (value >> 16) & 0xFF,
(int) (value >> 8) & 0xFF,
(int) (value & 0xFF)
);
}
此外,如果要確保格式正確,可以使用此方法獲得統一的結果:
private static String format(String raw) {
var builder = new StringBuilder(raw);
if (builder.charAt(0) != '#') {
builder.insert(0, '#');
}
if (builder.length() == 9) {
return builder.toString();
} else if (builder.length() == 7) {
return builder.append("ff").toString();
} else if (builder.length() == 4) {
builder.insert(builder.length(), 'f');
} else if (builder.length() != 5) {
throw new IllegalStateException("unsupported format");
}
for (int index = 1; index <= 7; index += 2) {
builder.insert(index, builder.charAt(index));
}
return builder.toString();
}
此方法會將所有可接受的格式(#RGB、#RGBA、#RRGGBB、RGB、RGBA、RRGGBB)轉換為#RRGGBBAA
前幾天我一直在解決類似的問題,發現將十六進制顏色字符串轉換為 int 數組 [alpha, r, g, b] 很方便:
/**
* Hex color string to int[] array converter
*
* @param hexARGB should be color hex string: #AARRGGBB or #RRGGBB
* @return int[] array: [alpha, r, g, b]
* @throws IllegalArgumentException
*/
public static int[] hexStringToARGB(String hexARGB) throws IllegalArgumentException {
if (!hexARGB.startsWith("#") || !(hexARGB.length() == 7 || hexARGB.length() == 9)) {
throw new IllegalArgumentException("Hex color string is incorrect!");
}
int[] intARGB = new int[4];
if (hexARGB.length() == 9) {
intARGB[0] = Integer.valueOf(hexARGB.substring(1, 3), 16); // alpha
intARGB[1] = Integer.valueOf(hexARGB.substring(3, 5), 16); // red
intARGB[2] = Integer.valueOf(hexARGB.substring(5, 7), 16); // green
intARGB[3] = Integer.valueOf(hexARGB.substring(7), 16); // blue
} else hexStringToARGB("#FF" + hexARGB.substring(1));
return intARGB;
}
這是處理 RGBA 版本的另一個更快的版本:
public static int hexToIntColor(String hex){
int Alpha = Integer.valueOf(hex.substring(0, 2), 16);
int Red = Integer.valueOf(hex.substring(2, 4), 16);
int Green = Integer.valueOf(hex.substring(4, 6), 16);
int Blue = Integer.valueOf(hex.substring(6, 8), 16);
Alpha = (Alpha << 24) & 0xFF000000;
Red = (Red << 16) & 0x00FF0000;
Green = (Green << 8) & 0x0000FF00;
Blue = Blue & 0x000000FF;
return Alpha | Red | Green | Blue;
}
For shortened hex code like #fff or #000
int red = "colorString".charAt(1) == '0' ? 0 :
"colorString".charAt(1) == 'f' ? 255 : 228;
int green =
"colorString".charAt(2) == '0' ? 0 : "colorString".charAt(2) == 'f' ?
255 : 228;
int blue = "colorString".charAt(3) == '0' ? 0 :
"colorString".charAt(3) == 'f' ? 255 : 228;
Color.rgb(red, green,blue);
十六進制顏色代碼已經是 rgb。 格式為#RRGGBB
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.