Re: loading an image
On 7-8-2006 9:52, vk wrote:
hi i have done this coding in order to do image loading and then get
its height and width but it is showin an error that unable to load
image
could you plz check it and let me know where i m going wrong..
Works for me. I've added a few lines to your code: it opens a window (a
JFrame) with the image loaded from the give URL. I've modified the URL
to the Java logo on Sun's site. Can you see the Java image when you run
the code?
Google sometimes blocks request from unknown/unsupported browsers (which
this Java application in fact is). However, when I replace the URL with
the one from Google, I can see this image too.
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class Viewer extends JPanel {
private Image image;
public Viewer(URL url) {
image = Toolkit.getDefaultToolkit().getImage(url);
System.out.println("hi");
MediaTracker mt = new MediaTracker(this);
mt.addImage(image, 0);
try {
mt.waitForID(0);
} catch (InterruptedException e) {
System.err.println("Unexpected interrupt in waitForID!");
return;
}
if (mt.isErrorID(0)) {
System.err.println("Couldn't load image file " + url);
return;
}
int width = image.getWidth(this);
int height = image.getHeight(this);
if (width == -1 || height == -1) {
System.err.println("Image dimensions unknown");
}
System.out.println("Image width : " + width);
System.out.println("Image height: " + height);
}
public static void main(String[] args) throws Exception {
// String url =
//"http://mt3.google.com/mt?n=404&;v=ap.14&x=1314&y=3177&zoom=4";
String url =
"http://java.sun.com/j2se/1.5.0/docs/images/javalogo52x88.gif";
Viewer viewer = new Viewer(new URL(url));
ImageIcon imageIcon = new ImageIcon(viewer.image);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(imageIcon);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
JFrame app = new JFrame();
app.getContentPane().setLayout(new BorderLayout());
app.getContentPane().add(imageLabel, BorderLayout.CENTER);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(400, 400);
app.setVisible(true);
}
}
--
Regards,
Roland