How can I load a bitmap image and manipulate individual pixels?

28,051

Thanks to MadProgrammer I have an answer:

package image_test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Image_test {

    public static void main(String[] args) {
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("test.bmp"));
        } catch (IOException e) {
            
        }
        int height = img.getHeight();
        int width = img.getWidth();
        
        int amountPixel = 0;
        int amountBlackPixel = 0;
        
        int rgb;
        int red;
        int green;
        int blue;
        
        double percentPixel = 0;

        System.out.println(height  + "  " +  width + " " + img.getRGB(30, 30));
        
        for (int h = 0; h<height; h++)
        {
            for (int w = 0; w<width; w++)
            {
                amountPixel++;
                
                rgb = img.getRGB(w, h);
                red = (rgb >> 16 ) & 0x000000FF;
                green = (rgb >> 8 ) & 0x000000FF;
                blue = (rgb) & 0x000000FF;
                
                if (red == 0 && green == 0 && blue == 0)
                {
                    amountBlackPixel ++;
                }
            }
        }
        percentPixel = (double)amountBlackPixel / (double)amountPixel;
        
        System.out.println("amount pixel: "+amountPixel);
        System.out.println("amount black pixel: "+amountBlackPixel);
        System.out.println("amount pixel black percent: "+percentPixel);
    }
}
Share:
28,051
Joseph
Author by

Joseph

Works in IT

Updated on July 09, 2022

Comments

  • Joseph
    Joseph almost 2 years

    I want to load a single large bitmap image from a file, run a function that manipulates individual pixels and then re save the bitmap.

    File formats can be either PNG or BMP, and the manipulating function is something simple such as:

    if r=200,g=200,b=200 then +20 on all values, else -100 on all values
    

    The trick is being able to load a bitmap and being able to read each pixel line by line

    Is there standard library machinery in Java that can handle this I/O?

    (The bitmap will need to be several megapixels, I need to be able to handle millions of pixels)

  • Toby Wilson
    Toby Wilson over 3 years
    Many years later, but this method misses the first row and column of pixels. The for loop initialisers for w & h should be = 0, not = 1.