java rgb颜色_Java RGB颜色与HEX颜色转换

package com.what21.swing.image.demo01;

public class RGB {

int red;

int green;

int blue;

public RGB(){ }

public RGB(int red, int green, int blue) {

this.red = red;

this.blue = blue;

this.green = green;

}

public String toString() {

return "RGB {" + red + ", " + green + ", " + blue + "}";

}

}

package com.what21.swing.image.demo01;

import java.util.regex.Pattern;

public class Converter {

/**

* RGB颜色 转 HEX颜色

*

* @param red

* @param green

* @param blue

* @return

*/

public static String toHEX(int red, int green, int blue) {

if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0

|| blue > 255) {

return "";

}

String redStr = Integer.toHexString(red);

String greenStr = Integer.toHexString(green);

String blueStr = Integer.toHexString(blue);

return ("#" + redStr + greenStr + blueStr).toUpperCase();

}

/**

* RGB颜色 转 HEX颜色

*

* @param rgb

* @return

*/

public static String toHEX(RGB rgb){

return toHEX(rgb.red,rgb.green,rgb.blue);

}

/**

* HEX颜色 转 RGB颜色

*

* @param hex

* @return

*/

public static RGB toRGB(String hex){

RGB rgb = new RGB();

if(!Pattern.matches("^#[0-9a-f[A-F]]{6}", hex)){

return rgb;

}

String redStr = hex.substring(1,3);

String greenStr = hex.substring(3,5);

String blueStr = hex.substring(5);

rgb.red = Integer.valueOf(redStr,16).intValue();

rgb.green = Integer.valueOf(greenStr,16).intValue();

rgb.blue = Integer.valueOf(blueStr,16).intValue();

return rgb;

}

/**

* @param args

*/

public static void main(String[] args) {

System.out.println(toHEX(222,221,222));

System.out.println(toRGB("#DEDDDE"));

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值