Draw an image from an array!!!!!!!!!!!!!!!!!!!!!!

Hi all , I have written a code to draw an image from an array using the following function called createimage( ) but I dont see an image in my image panel. Please let me know what is the reason for not getting that image.

// ARRAY OF SIZE 10*10

int w=10,h=10;

int[] line={100, 120, 10, 40, 50, 60, 70, 80, 70, 80,

90, 10, 10, 100, 90, 60, 70, 10, 100, 90,

30, 40, 50,60, 70, 20, 40, 50, 0,0,

70, 80, 90,90, 90, 90, 80, 70, 20, 30,

30, 40, 50,60, 50, 60, 70, 10, 120, 120,

123, 80, 70,60, 20, 10, 20, 30, 40,90,

10 , 60, 70,80, 40, 50, 30, 20, 50, 60,

70, 80, 100, 120, 120,100,110,110,120,110,

105,103, 104, 50, 10, 30, 70, 02, 70, 80,

40, 30, 02, 90, 70, 60, 50, 50, 60, 40,

};

Toolkit tk = Toolkit.getDefaultToolkit();

Image imageline = tk

.createImage(new MemoryImageSource(w, h, line, 0, w));

// DISPLAY THE IMAGE IMAGE LINE

final JFrame f = new JFrame("BlackAndWhite");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container cp = f.getContentPane();

cp.setLayout(new GridLayout(1,2));

cp.add(new JLabel(new ImageIcon(imageline)));

f.pack();

SwingUtilities.invokeLater(new Runnable(){

public void run() {

f.setSize(150,150);

f.setLocationRelativeTo(null);

f.setVisible(true);

}

});

[1394 byte] By [ephemerala] at [2007-10-3 3:13:40]
# 1

Hi,

I don't know where exactly your problem is, but try my code (not exactly mine, I borrowed some pieces from MemoryImageSource class from documentation)

It works quite well so try to do it in the same way

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.image.MemoryImageSource;

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.SwingUtilities;

public class ImageTest {

public ImageTest() {

int w = 100;

int h = 100;

int pix[] = new int[w * h];

int index = 0;

for (int y = 0; y < h; y++) {

int red = (y * 255) / (h - 1);

for (int x = 0; x < w; x++) {

int blue = (x * 255) / (w - 1);

pix[index++] = (255 << 24) | (red << 16) | blue;

}

}

final JFrame f = new JFrame("BlackAndWhite");

Image img = f.createImage(new MemoryImageSource(w, h, pix, 0, w));

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container cp = f.getContentPane();

cp.setLayout(new BorderLayout());

f.add(new JLabel(new ImageIcon(img)));

f.pack();

SwingUtilities.invokeLater(new Runnable(){

public void run() {

f.setSize(150,150);

f.setLocationRelativeTo(null);

f.setVisible(true);

}

});

}

public static void main(String[] args) {

new ImageTest();

}

}

Hope this helps

L.P.

lukika at 2007-7-14 21:04:42 > top of Java-index,Security,Cryptography...