BufferedImage unexpectedly changes color

I have the following code that creates a grayscale BufferedImage and then sets the random colors of each pixel.

import java.awt.image.BufferedImage;

public class Main {

    public static void main(String[] args) {
        BufferedImage right = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
        int correct = 0, error = 0;
        for (int i = 0; i < right.getWidth(); i++) {
            for (int j = 0; j < right.getHeight(); j++) {
                int average = (int) (Math.random() * 255);
                int color = (0xff << 24) | (average << 16) | (average << 8) | average;
                right.setRGB(i, j, color);
                if(color != right.getRGB(i, j)) {
                    error++;
                } else {
                    correct++;
                }
            }
        }
        System.out.println(correct + ", " + error);
    }
}

In about 25-30% of the pixels, a strange behavior occurs when I set the color, and on the right after it has a different meaning than was previously set. Am I setting colors incorrectly?

+4
source share
3 answers

Here is your solution: disable getRGB and use Raster (faster and easier than getRGB) or even better than DataBuffer (faster, but you have to handle the encoding):

import java.awt.image.BufferedImage;

public class Main
{

public static void main(String[] args)
    {
    BufferedImage right = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
    int correct = 0, error = 0;
    for (int x=0 ; x < right.getWidth(); x++)
        for (int j = 0; j < right.getHeight(); j++)
            {
            int average = (int) (Math.random() * 255) ;
            right.getRaster().setSample(x, y, 0, average) ;
            if ( average != right.getRaster().getSample(x, y, 0) ) error++ ;
            else correct++;
            }
    System.out.println(correct + ", " + error);
    }
}

getRGB , (8 ), RGB getRGB. .

+1

, ( BufferedImage). BufferedImage.TYPE_INT_ARGB, 100% .

BufferedImage.getRGB(int,int), , RGB,

RGB (TYPE_INT_ARGB) sRGB . , ColorModel.

, , , - .

+1

Wild hunch:

Delete (0xff <24) | which is an alpha channel, like an opaque / opaque color. If yes / no is transparent and the average value <or> = 128 applies transparency, 25% may be an incorrect display of colors (a very wild assumption).

0
source

All Articles