使用java从图像中获取像素数据 [英] Getting pixel data from an image using java

查看:172
本文介绍了使用java从图像中获取像素数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 64 x 48 位图中获取像素rgb值。我得到了一些值,但远不及我期待的 3072(= 64 x 48)值。我也得到:

I'm trying to get the pixel rgb values from a 64 x 48 bit image. I get some values but nowhere near the 3072 (= 64 x 48) values that I'm expecting. I also get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:301)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:871)
at imagetesting.Main.getPixelData(Main.java:45)
at imagetesting.Main.main(Main.java:27)

我找不到越界错误...

I can't find the out of bounds error...

以下是代码:

package imagetesting;

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



public class Main {

public static final String IMG = "matty.jpg";

public static void main(String[] args) {

    BufferedImage img;

    try {
        img = ImageIO.read(new File(IMG));

        int[][] pixelData = new int[img.getHeight() * img.getWidth()][3];
        int[] rgb;

        int counter = 0;
        for(int i = 0; i < img.getHeight(); i++){
            for(int j = 0; j < img.getWidth(); j++){
                rgb = getPixelData(img, i, j);

                for(int k = 0; k < rgb.length; k++){
                    pixelData[counter][k] = rgb[k];
                }

                counter++;
            }
        }


    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static int[] getPixelData(BufferedImage img, int x, int y) {
int argb = img.getRGB(x, y);

int rgb[] = new int[] {
    (argb >> 16) & 0xff, //red
    (argb >>  8) & 0xff, //green
    (argb      ) & 0xff  //blue
};

System.out.println("rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]);
return rgb;
}

}


推荐答案

这:

for(int i = 0; i < img.getHeight(); i++){
    for(int j = 0; j < img.getWidth(); j++){
        rgb = getPixelData(img, i, j);

与此不匹配:

private static int[] getPixelData(BufferedImage img, int x, int y) {

你有 i 计算行数和 j 列,即包含 y 值, j 包含 x 值。那是倒退。

You have i counting the rows and j the columns, i.e. i contains y values and j contains x values. That's backwards.

这篇关于使用java从图像中获取像素数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆