Buffered image pixel manipulation

后端 未结 2 2039
野趣味
野趣味 2021-01-22 21:05

I have this code:

public Image toNegative()
{
    int imageWidth =  originalImage.getWidth();
    int imageHeight = originalImage.getHeight();
    int [] rgb = n         


        
相关标签:
2条回答
  • 2021-01-22 21:20

    Your code will throw a NullPointerException because you are never assigning a non-null reference to the rgb variable. Hence, references to it (e.g. rgb[index]) will generate the exception. If you wish to pass in a null array to getRGB you need to ensure you assign the result array returned by the method; e.g.

    int[] rgb = originalImage.getRGB(0, 0, imageWidth, imageHeight, rgb, 0,imageWidth);
    

    If you were to uncomment the code commented out there is a bug in that you are allocating the array as imageWidth * imageWidth instead of imageWidth * imageHeight, which is why you're seeing an ArrayIndexOutOfBoundsException.

    0 讨论(0)
  • 2021-01-22 21:31

    There are two problems:

    1. The width of the array is not the width of the image but the "scan size" (some image sizes get padded with extra pixels)

    2. If you call getRGB() with a null array, the method will create an array but it won't change the rgb reference - Java doesn't support "out parameters".

    To make this work, use

    rgb = originalImage.getRGB(0, 0, imageWidth, imageHeight, null, 0,imageWidth);
    
    0 讨论(0)
提交回复
热议问题