I have an integer array of RGB pixels that looks something like:
pixels[0] = <rgb-value of pixel(0,0)>
pixels[1] = <rgb-value of pixel(1,0)>
pixels[2] = <rgb-value of pixel(2,0)>
pixels[3] = <rgb-value of pixel(0,1)>
...etc...
And I'm trying to create a BufferedImage from it. I tried the following:
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
img.getRaster().setPixels(0, 0, width, height, pixels);
But the resulting image has problems with the color bands. The image is unclear and there are diagonal and horizontal lines through it.
What is the proper way to initialize the image with the rgb values?
EDIT:
Here is what my image looks like
thanks, Jeff
Try setDataElements
instead of setPixels
.
Another option is for the image to share the array instead of copying from it (see this answer for an example.)
Not sure how to do it with a single array value. I believe you need three array values to specify the color when you use TYPE_INT_RGB:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class ImageFromArray2 extends JFrame
{
int width = 50;
int height = 50;
int imageSize = width * height;
public ImageFromArray2()
{
JPanel panel = new JPanel();
getContentPane().add( panel );
int[] pixels = new int[imageSize * 3];
// Create Red Image
for (int i = 0; i < imageSize * 3; i += 3)
{
pixels[i] = 255;
pixels[i+1] = 0;
pixels[i+2] = 0;
}
panel.add( createImageLabel(pixels) );
// Create Green Image
for (int i = 0; i < imageSize * 3; i += 3)
{
pixels[i] = 0;
pixels[i+1] = 255;
pixels[i+2] = 0;
}
panel.add( createImageLabel(pixels) );
// Create Blue Image
for (int i = 0; i < imageSize * 3; i += 3)
{
pixels[i] = 0;
pixels[i+1] = 0;
pixels[i+2] = 255;
}
panel.add( createImageLabel(pixels) );
// Create Cyan Image
for (int i = 0; i < imageSize * 3; i += 3)
{
pixels[i] = 0;
pixels[i+1] = 255;
pixels[i+2] = 255;
}
panel.add( createImageLabel(pixels) );
}
private JLabel createImageLabel(int[] pixels)
{
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = image.getRaster();
raster.setPixels(0, 0, width, height, pixels);
JLabel label = new JLabel( new ImageIcon(image) );
return label;
}
public static void main(String args[])
{
JFrame frame = new ImageFromArray2();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With