坐标超出范围:bufferedimage [英] coordinates out of bound:bufferedimage

查看:239
本文介绍了坐标超出范围:bufferedimage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个程序来分离图像的红色蓝色和绿色部分,但是下面的代码给出了错误:

I made a program to separate red blue and green components of a image but the code below gives an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:318)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:888)
at rgb.Rgb.main(Rgb.java:46):

这是源代码:

public static void main(String[] args) {
    String type = "jpg";
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("d:\\a.jpg"));
        System.out.println(img.getWidth() + "     " + img.getHeight());

    } catch (IOException ex) {
        Logger.getLogger(Rgb.class.getName()).log(Level.SEVERE, null, ex);

    }

    BufferedImage rp, gp, bp;

    rp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    bp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    gp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);

    for (int i = 1; i <= img.getHeight(); i++) {
        for (int j = 1; j <= img.getWidth(); j++) {

            int pixel = img.getRGB(i, j);
            int alpha = pixel & 0xff000000;
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = (pixel) & 0xff;
            rp.setRGB(i, j, alpha | (red << 16));
            gp.setRGB(i, j, alpha | (green << 8));
            bp.setRGB(i, j, alpha | blue);

        }

    }

    try {
        ImageIO.write(rp, type, new File("d:\\red.jpg"));
        ImageIO.write(gp, type, new File("d:\\green.jpg"));
        ImageIO.write(bp, type, new File("d:\\blue.jpg"));
    } catch (IOException ex) {
        Logger.getLogger(Rgb.class.getName()).log(Level.SEVERE, null, ex);
    }


推荐答案

方法为 getRGB(x,y)表示您的外循环应该是宽度,内循环应该是高度。更改为

The method is getRGB(x,y) meaning your outer-loop should be for width and inner-loop for height. Change to

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

原因

您正在尝试获取不存在的坐标。这是因为

REASON
You are trying to get a co-ordinate that does not exist. This is because


  1. 您的循环应从0开始,并以getWidth()-1 / getHeight()-1作为最后一个co-纵坐标为(WIDTH-1,HEIGHT-1)

  2. 您的外循环获取y值,而内部循环获取x值,因此您尝试获取(y,x)值,而它应该是(x,y)值。如果是方形图片,这不会造成任何问题,但是如果是矩形图片,则将导致异常(如您所见)。

因此,按照我在代码中的建议进行更改,它应该可以工作。

So make the change as I suggested in code and it should work.

这篇关于坐标超出范围:bufferedimage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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