Create BufferredImage with colors based on integer array in Java
Description
The following code shows how to create BufferredImage with colors based on integer array.
Example
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/*from www . ja v a 2 s . c o m*/
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
int width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int i = 0;
for (int y = 0; y < height; y++) {
int red = (y * 255) / (height - 1);
for (int x = 0; x < width; x++) {
int green = (x * 255) / (width - 1);
int blue = 128;
data[i++] = (red << 16) | (green << 8) | blue;
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
g.drawImage(image, 0, 0, this);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.