关于云图库项目中颜色搜索的小问题

关于云图库项目中颜色搜索的小问题

云图库项目第八期的颜色搜索中鱼皮留了一个小问题,利用数据万象获取图片主色调的时候,返回的数据中会发现有的图片十六进制数值不是标准6位,而是会省略掉若干0。

我去看官网的写返回信息是0xRRGGBB,RGB每个颜色数值占两位,我就猜测会不会是同一颜色出现两个0则会省略为1个0,比如RR的值是00但只会返回0。

我想不出来实现方法,就让DeepSeek帮忙生成,实现如果出现R、G或B中1个0的情况写为两个0。不过看来确实挺难的,DeepSeek愣是思考了500多秒生成一长串的思考过程才得出来。以下是代码:

java
复制代码
public static String getStandardColor(String color) { // 去掉开头0x String hex = color.startsWith("0x") ? color.substring(2) : color; // 获取其余长度 int length = hex.length(); String[] parts = new String[3]; // 分别存储R, G, B部分 int currentIndex = 0; for (int i = 0; i < 3; i++) { if (currentIndex >= length) { parts[i] = ""; continue; } int remaining = length - currentIndex; if (i < 2) { // 处理R和G部分,尽量取两位 if (remaining >= 2) { parts[i] = hex.substring(currentIndex, currentIndex + 2); currentIndex += 2; } else { parts[i] = hex.substring(currentIndex, currentIndex + 1); currentIndex += 1; } } else { // 处理B部分,取剩余所有字符 parts[i] = hex.substring(currentIndex); currentIndex = length; } } StringBuilder result = new StringBuilder(); for (String part : parts) { if (part.isEmpty()) { result.append("00"); } else if (part.length() == 1) { result.append(part.charAt(0)).append('0'); } else { result.append(part); } } String standardHex = result.toString().substring(0, 6); // 确保总长度是6位 return "0x" + standardHex; } public static void main(String[] args) { // 测试用例 System.out.println(getStandardColor("0xc000")); // 预期输出0xc00000 System.out.println(getStandardColor("0xff")); // 预期输出0xff0000 System.out.println(getStandardColor("0x00")); // 预期输出0x000000 System.out.println(getStandardColor("0xf0f")); // 预期输出0xf00ff0 System.out.println(getStandardColor("0x0")); // 预期输出0x000000 System.out.println(getStandardColor("0xc00")); // 预期输出0xc00000 }

以上代码经过测试没有什么问题,上面是转换0,目前我就发现只有0有问题。

我不知道是否相同的任何其余数值也会被吃掉,当我上传了一张#FFFFFF的图片时返回的Hex竟然是0xe0e0e0,这就很匪夷所思。

0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
子琦真帅
下载 APP