Java 如何加载位图图像并操作单个像素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16475482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:04:14  来源:igfitidea点击:

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

javaimageimage-processingbitmappixel

提问by Joseph

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:

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

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?

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

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

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

采纳答案by Joseph

Thanks to MadProgrammer I have an answer:

感谢 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 = 1; h<height; h++)
        {
            for (int w = 1; 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);
    }
}