Java实现图片亮度自动调节(RGB格式)

最关键的获取亮度公式:
float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;

private BufferedImage adjustBrightness(BufferedImage imgsrc) {
        int width = imgsrc.getWidth();
        int height = imgsrc.getHeight();
        int totalPixels = width * height;
        int[] intValues = new int[totalPixels];
        imgsrc.getRGB(0, 0, width, height, intValues, 0, width);
        int pixelLuminanceLowerThanBound = 0;
        int pixelLuminanceHigherThanBound = 0;
        float luminanceSum = 0.f;
        for (int i = 0, j = intValues.length; i < j; i++) {
            int val = intValues[i];
            int red = (val >> 16) & 0xFF;
            int green = ((val >> 8) & 0xFF);
            int blue = val & 0xFF;
            float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;
            if (luminance < lowerBound) {
                pixelLuminanceLowerThanBound++;
            }
            if (luminance > upperBound) {
                pixelLuminanceHigherThanBound++;
            }
            luminanceSum += luminance;
        }
        float threshold = (totalPixels * pixelAdjustmentRatio);
        if (!(pixelLuminanceLowerThanBound > threshold) && !(pixelLuminanceHigherThanBound > threshold)) {
            return imgsrc;
        }

        float luminanceMean = luminanceSum / (totalPixels);
        float brightnessDiff = (float) (universalBrightness) / 100 - luminanceMean;
        float expandFactor = (float) (Math.pow(1. + brightnessDiff, 2.5));
        RescaleOp rescaleOp = new RescaleOp(expandFactor, 35, null);
        rescaleOp.filter(imgsrc, imgsrc);
//        imgsrc.setRGB(0, 0, width, height, intValues, 0, width);
        return imgsrc;
    }

你可能感兴趣的:(Java实现图片亮度自动调节(RGB格式))