8

我想从文件中加载一个大的位图图像,运行一个操作单个像素的函数,然后重新保存位图。

文件格式可以是 PNG 或 BMP,操作函数很简单,例如:

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

诀窍是能够加载位图并能够逐行读取每个像素

Java 中是否有可以处理此 I/O 的标准库机制?

(位图需要几百万像素,我需要能够处理几百万像素)

4

1 回答 1

11

感谢 MadProgrammer 我有一个答案:

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);
    }
}
于 2013-05-10T06:21:11.690 回答