📜  增加或减少图像亮度的Java程序

📅  最后修改于: 2022-05-13 01:55:11.178000             🧑  作者: Mango

增加或减少图像亮度的Java程序

在了解如何在任何图像中调整亮度之前,我们必须先了解图像是如何表示的。图像以像素的 2D 形式表示,像素是图像的最小元素。任意点的像素值对应于撞击该点的光子的光强度。每个像素存储 N 位无符号整数值,其中 N 是图像的深度(8 位图像、16 位图像、24 位图像)。对于 8 位图像,像素的值可以在 0 到 255 之间变化,其中 0 对应于黑色,255 对应于白色。每个像素颜色由 RGB 值的组合组成。亮度只不过是图像对光的感知程度。

脚步:

我们需要依次执行以下 3 个步骤,如下所示:

  1. 使用 ImageIO 类读取图像
  2. 获取图像的宽度和高度并遍历每个像素
  3. 获取每个像素的RGB值以增加亮度

执行:

考虑一个样本任意输入图像,我们将使用它来增加或减少其对比度以说明变化。

照片.jpg

例子

Java
// Java Program to Increase or Decrease Brightness of an
// Image
 
import java.io.*;
 
class GFG {
 
    // Method 1
    // Helper method to method 2
    public static int Truncate(int value)
    {
 
        if (value < 0) {
            value = 0;
        }
        else if (value > 255) {
            value = 255;
        }
        return value;
    }
 
    // Method 2
    // To adjust the brightness of image
    public static void AdjustBrightness(String inpPath,
                                        String outPath)
        throws IOException
    {
 
        // Taking image path and reading pixels
        File f = new File(inpPath);
        BufferedImage image = ImageIO.read(f);
 
        // Declaring an array for spectrum of colors
        int rgb[];
 
        // Setting custom brightness
        int brightnessValue = 25;
 
        // Outer loop for width of image
        for (int i = 0; i < image.getWidth(); i++) {
 
            // Inner loop for height of image
            for (int j = 0; j < image.getHeight(); j++) {
 
                rgb = image.getRaster().getPixel(
                    i, j, new int[3]);
 
                // Using(calling) method 1
                int red
                    = Truncate(rgb[0] + brightnessValue);
                int green
                    = Truncate(rgb[1] + brightnessValue);
                int blue
                    = Truncate(rgb[2] + brightnessValue);
 
                int arr[] = { red, green, blue };
 
                // Using setPixel() method
                image.getRaster().setPixel(i, j, arr);
            }
        }
 
        // Throwing changes over the image as read above
        ImageIO.write(image, "jpg", new File(outPath));
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Passing images present on directory on local
        // machine
        String inputPath = "E:\\photo.jpg";
        String outputPath = "E:\\outphoto.jpg";
 
        // Calling method 2 inside main() to
        // adjust the brightness of image
        AdjustBrightness(inputPath, outputPath);
    }
}


输出:明亮的图像

outphoto.jpg