Search code examples
javaawtgraphics2d

Image is drawing sideways to screen (Java BufferedImage, WritableRaster)


My code is drawing the image incorrectly. Every time I try to guess what's wrong and fix it, I get arrayOutOfBounds exceptions. All the array business is mixing me up. I just really need some help. Thanks!

(By the way, I do need to extract the pixel values and store them so I can do blur, sharpening, and other types of methods on the data by hand. I'm learning how image processing works.)

This code gives this result (the image is sideways when it should be right-side up):

enter image description here

This is the original image:

enter image description here

Image.java:

package mycode;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class Image {

    public int height;
    public int width;
    public int image[][];

    public Image(BufferedImage openImage)
    {
        height = openImage.getHeight();
        width = openImage.getWidth();

        image = new int[openImage.getWidth()][openImage.getHeight()];
        for(int x = 0; x < openImage.getWidth(); x++)
        {
            for(int y = 0; y < openImage.getHeight(); y++)
            {
                image[x][y] = 0xff & openImage.getRGB(x, y);
                Debug.print(""+Integer.toHexString(image[x][y]));
            }
        }

    }
}

refreshView(): (model.image is an instance of the Image class above.)

@Override
public void refreshView(Graphics2D g2d)
{   
    //Draw the background image.
    if(ControllerState.inImageMode && model.image != null)
    {
        Debug.print("Drawing background image");
        BufferedImage bufferedImage = new BufferedImage(model.image.width, model.image.height, 
                BufferedImage.TYPE_BYTE_GRAY);
        WritableRaster wr = bufferedImage.getRaster();

        for(int x = 0; x < model.image.width; x++)
        {
            for(int y = 0; y < model.image.height; y++)
            {
                wr.setPixels(0, x, model.image.width, 1, model.image.image[x]);
            }
        }
        g2d.drawImage(bufferedImage, null, 0, 0);   
    }
}

Solution

  • It seems like you have a classic x-y row-column mixup problem. I think inside of your for loop you want:

    wr.setPixels(x, 0, 1, model.image.height, model.image.image[x]);