How to change the brightness of an Image

前端 未结 4 513
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 01:42

My Question: I want to be able to change the brightness of a resource image and have three instances of it as ImageIcons. One at 50% brightness (so darker), ano

4条回答
  •  旧巷少年郎
    2021-02-06 02:10

    Basic logic is take RGB value of each pixel ,add some factor to it,set it again to resulltant matrix(Buffered Image)

        import java.io.*;
        import java.awt.Color;
        import javax.imageio.ImageIO;
        import java.io.*;
        import java.awt.image.BufferedImage;
    
    
    
            class psp{
    
        public static void main(String a[]){
        try{
    
        File input=new File("input.jpg");
        File output=new File("output1.jpg");
                BufferedImage picture1 = ImageIO.read(input);   // original
        BufferedImage picture2= new BufferedImage(picture1.getWidth(), picture1.getHeight(),BufferedImage.TYPE_INT_RGB);      
                int width  = picture1.getWidth();
                int height = picture1.getHeight();
    
        int factor=50;//chose it according to your need(keep it less than 100)
        for (int y = 0; y < height ; y++) {//loops for image matrix
        for (int x = 0; x < width ; x++) {
    
        Color c=new Color(picture1.getRGB(x,y));
    
        //adding factor to rgb values
    int r=c.getRed()+factor;
        int b=c.getBlue()+factor;
        int g=c.getGreen()+factor;
        if (r >= 256) {
         r = 255;
        } else if (r < 0) {
        r = 0;
        }
    
        if (g >= 256) {
        g = 255;
        } else if (g < 0) {
        g = 0;
        }
    
         if (b >= 256) {
        b = 255;
        } else if (b < 0) {
        b = 0;
         }
        picture2.setRGB(x, y,new Color(r,g,b).getRGB());
    
    
        }
        }
         ImageIO.write(picture2,"jpg",output);       
        }catch(Exception e){
        System.out.println(e);
        }
         }}
    

提交回复
热议问题