简体   繁体   中英

java - how to make an image using setRGB?

i have 2D array to keep color component value :

p[pixel_value][red]
p[pixel_value][green]
p[pixel_value][blue]

i just dont know how to use them to make an image.

i read about setRGB , what i understand is i should mix all of them to become a RGBArray. then how to make it?

is it any better way to make an image without setRGB ? i need some explanation.

The method setRGB() can be used to set the color of a pixel of an already existing image. You can open an already existing image and set all the pixels of it, using the values stored in your 2D array. You can do it like this:

BufferedImage img = ImageIO.read(new File("image which you want to change the pixels"));
for(int width=0; width < img.getWidth(); width++)
{
    for(int height=0; height < img.getHeight(); height++)
    {
          Color temp = new Color(p[pixel_value][red], p[pixel_value][green], p[pixel_value][blue]);
          img.setRGB(width, height, temp.getRGB());
    }
}
ImageIO.write(img, "jpg", new File("where you want to store this new image"));

Like this, you can iterate over all the pixels and set their color accordingly.

NOTE: By doing this, you will lose your original image. This is just a way which I know.

What you need is a BufferedImage . Create a BufferedImage of type TYPE_3BYTE_BGR , if RGB is what you want, with a specified width and height.

QuickFact:
The BufferedImage subclass describes an Image with an accessible buffer of image data.

Then, call the getRaster() method to get a WritableRaster

QuickFact:
This class extends Raster to provide pixel writing capabilities.

Then, use the setPixel(int x, int y, double[] dArray) method to set the pixels.

Update:

If all you want is to read an image, use the ImageIO.read(File f) method. It will allow you to read an image file in just one method call.

Somewhat SSCCE:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}

You want to manually set RGB values?

You need to know that since an int is 32bit it contains all 4 rgb values (1 for the transparency).

xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
^Alpha     ^red    ^green    ^blue

You can accomplish using 4 int values by the use of binary arithmetic:

int rgb = (red << 16) && () (green << 8) & (blue);
bufferedImage.setRGB(x, y, rgb);

IN the above you can add Alpha as well if needed. You just "push" the binary codes into the right places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM