获取图片的每一个像素点的字节数据,根据灰度值的加权公式计算出单个像素的灰度值,将整体灰度值相加除总像素。
/**
* 识别图片的色调
*/
public class ImageToneDetect {
/**
* 计算一个图片的RGB深浅度,返回一个值在0-100之间,值越大,图片颜色越深,值越小,图片颜色越淡,例如偏白色
* @param bytes
* @return
*/
public static Integer getRgbToneValue(byte[] bytes) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(bais);
int width = image.getWidth();
int height = image.getHeight();
long totalLuminance = 0;
int pixelCount = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = image.getRGB(x, y);
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int b = rgb & 0xff;
// 使用RGB到灰度的转换公式
int luminance = (int) (0.299 * r + 0.587 * g + 0.114 * b);
totalLuminance += luminance;
pixelCount++;
}
}
double averageLuminance = (double) totalLuminance / pixelCount;
// 归一化到0-100之间,假设一个阈值将亮度值映射到该范围
double toneValue = (averageLuminance / 255.0) * 100;
// 反转值,使亮度越高值越小,亮度越低值越大(偏白色值越小)
return 100 - (int)Math.round(toneValue);
}
}