Adding image to JPanel through ImageIO.read? - java

I'm trying to add a JPanel with a picture in it. I'm using ImageIO.read to get the path but i get an IOException saying : can't read input file
The picture is called TCHLogo. It's a PNG inside a 'res' folder inside my project.
If there is any better way of displaying this image please also mention it!
Here is the code for my JPanel:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
//THIS LINE BELLOW WAS ADDED
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
} catch (IOException ex) {
// handle exception...
System.out.println(ex);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //THIS LINE WAS ADDED
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
Here is how i add the JPanel in my Applet:
ImagePanel appletRunningPanel;
appletRunningPanel = new ImagePanel();
appletRunningPanel.setSize(300, 300);
appletRunningPanel.validate();
add(appletRunningPanel);
EDIT
I created a folder inside the bin which the application starts to look in currently..
the folder is called res and the picture is inside..
Now i get the following IOException when i run the line:
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
Here is the error log:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1338)
at surprice.applet.ImagePanel.<init>(ImagePanel.java:17)
at surprice.applet.MainClass.init(MainClass.java:41)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)

Likely your image's file path isn't correct relative to the user directory. To find out where Java is starting to look, where the user directory is, place something like this line of code somewhere in your program:
System.out.println(System.getProperty("user.dir"));
Perhaps you'd be better off getting the image as an InputStream obtained from a resource and not as a file. e.g.,
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
This will look for the image at the path given relative to the location of the class files, and in fact this is what you must do if your image is located in your jar file.
Edit 2
As an aside, often you need to first call the super's paintComponent method before doing any of your own drawing so as to allow necessary house-keeping can be done, such as getting rid of "dirty" image bits. e.g., change this:
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
to this:
public void paintComponent(Graphics g) {
super.paintComponent(g); // **** added****
g.drawImage(image, 0, 0, null);
}

I've written this ImagePanel class that i use for this scope :
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 7952119619331504986L;
private BufferedImage image;
public ImagePanel() { }
public ImagePanel(String resName) throws IOException {
loadFromResource(resName);
}
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* Load the Image from a File
* #param path image name and path
* #throws IOException
*/
public void loadFromFile(String path) throws IOException {
image = ImageIO.read(new java.io.File(path));
}
/**
* Load Image from resource item
* #param resName name of the resource (e.g. : image.png)
* #throws IOException
*/
public void loadFromResource(String resName) throws IOException {
URL url = this.getClass().getResource(resName);
BufferedImage img = ImageIO.read(url);
image = img;
}
}
Then i use the ImagePanel in this way :
//Inizialization of the ImagePanel
ImagePanel panelImage = new ImagePanel();
//Try loading image into the image panel
try {
panelImage.loadFromResource("/Resources/someimage.png");
} catch (java.io.IOException e) {
//Handling Exception
}

Related

Using jWindow as splash screen which shows good but image doesn't paint ... just blank jWindow opened...any thoughts?

jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
public class CreateSplashScreen extends JWindow {
JWindow jw = new JWindow();
Image scImage = Toolkit.getDefaultToolkit().getImage("testImage.png");
ImageIcon imageIcon = new ImageIcon(scImage);
public CreateSplashScreen() {
try {
jw.setSize(700, 500);
jw.setLocationRelativeTo(null);
jw.setVisible(true);
} catch (Exception e) {
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(scImage, 0, 0, jw);
}
public void CloseSplashScreen() {
jw.setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(CreateSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
sp.CloseSplashScreen();
}
}
jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
Why are you creating an internal JWindow when your class CreateSplashScreen already extends JWindow?
There is no need of it. You are messing with your program.
How?
You are actually viewing the inner JWindow by jw.setVisible(true); but you are painting the image in the CreateSplashScreen's `JWindow.
Try this code :
public class CreateSplashScreen extends JWindow
{
ImageIcon i = new ImageIcon(getClass().getResource("/createsplashscreen/testImage.png"));
public CreateSplashScreen() {
setSize(700, 500);
setLocationRelativeTo(null);
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(i.getImage(), 0, 0, null);
}
public void CloseSplashScreen() {
setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
sp.CloseSplashScreen();
}
}
Note: I do not know about your method to fetch image resource from the source folder.
Edit: Assuming that the name of the package containing your class CreateSplashScreen is createsplashscreen, make sure that the image testImage.png is present in the createsplashscreen package of your project.
#Peter
For error code, I deleted one line that I added in mamifest.mf file and build a program...
This time, didn't give me an error, weird...
I was following error code when I got it and it led me to something like "CLASSPATH" section of application generated code... sorry I can't remember exactly
Really appreciate Peter for your help.
Wish you luck...

Display and writing of image in java

I am unable to display the image as there's problem in the main method and i am not sure whether did i write the image correctly. Sorry, I am really new to Java.
public class Display extends JPanel
{
String path = "C:/Users/asus/workspace/Code/src/7horses.jpg";
File file = new File(path);
static BufferedImage img;
img = ImageIO.read(new File(file));
public static BufferedImage CopyImage (File file)
{
BufferedImage cImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = cImg.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
File saveImage = new File("C:/Users/asus/workspace/Code/src", saveAs);
ImageIO.write(cImg, "png", saveImage);
return cImg;
}
public static void main(String[] args)
{
JFrame f = new JFrame("Show Image");
LoadImage panel = new BufferedImage CopyImage(file);//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
After duplicate the image, i am not sure how to display the duplicate copy. Below was the code which i initially use for loading and displaying.
public class LoadImage extends JPanel
{
BufferedImage img;
String path = "C:/Users/asus/workspace/MP/src/7horses.jpg";
File file = new File(path);
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, null);
}
public LoadImage()
{
try
{
img = ImageIO.read(file);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
JFrame f = new JFrame("Show Image");
LoadImage panel = new LoadImage();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
There's a few things wrong with this code..
path and file cannot be accessed by main() because they are not static and main is. Meaning when main() is ran, neither of path or file exist.
LoadImage panel = new BufferedImage CopyImage(file) is not valid Java - I'm not sure what you were trying to do but I guess you want to remove the new BufferedImage part
img = ImageIO.read(new File(file)); - you can't run this statement outside a method or static block as it requires handling of an IOException
ImageIO.read(new File(file)); - file is already of type File and you are passing it to a type File, not necessary. ImageIO.read(file); would do
saveAs hasn't been defined anywhere.
ImageIO.write(cImg, "png", saveImage); can throw an IOException so you need to add a try-catch around it like in the LoadImage() constructor or append throws IOException to your method signature like so public static BufferedImage CopyImage (File file) throws IOException
You are referencing LoadImage which looks like it's trying to do exactly what Display does in a slightly different way. I'm not sure what to advise here because I don't understand the intention but I think perhaps replace LoadImage in the Display code with Display
Maybe:
Use ImageIO to retrieve a BufferedImage from your file.
Using an ImagePanel that can use a Buffered Image to display on
your JFrame
It would be something more like that:
public class Display extends JPanel {
private static final long serialVersionUID = 1L;
private static final String path = "C:/Users/asus/workspace/Code/src/7horses.jpg";
private static final File file = new File(path);
public static void main(String[] args) throws IOException {
JFrame f = new JFrame("Show Image");
BufferedImage image = ImageIO.read(file);
ImagePanel panel = new ImagePanel(image);//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200, 200);
f.setVisible(true);
}
public static class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
}
What is a LoadImage? Unless it's both a BufferedImage AND a Container your code won't even compile.
And as a class can't be both a Container and a BufferedImage at the same time (given that both are classes, not interfaces, and multiple inheritance at class level doesn't exist in Java) your code can't work.
You're going to have to figure out how to correctly initialise your LoadImage instance, and only the documentation (and possibly source) of that class is going to help you.

Display image on applet

I am using Jtree for listing various images of a directory, I want to display image on applet when the user click on the image name displayed in the Tree, the code i'm using is as below, ta is an object of the applet because i'm using it in another class.
private void displayImage(URL furl, String fname) {
ta.Picture = ta.getImage(furl, fname);
prepareImage(ta.Picture, this);
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
System.out.println("slecte asldf " + node.isLeaf());
if (node.isLeaf())
{
currentFile = node.file;
System.out.println("File name " + currentFile.getName());
try
{
URL furl = new URL("file:/F:/photos");
displayImage(furl, currentFile.getName());
}
catch (MalformedURLException mle)
{
System.out.println("Exception::::::" + mle);
}
}
else
currentFile = null;
}
But its not working.
As you are showing files from the local filesystem, working with URLs is not required. Use
displayImage(currentFile);
and rewrite that method as following:
private void displayImage(File file) {
BufferedImage image = ImageIO.read(file);
ta.image = image;
ta.repaint();
}
where the paint method of the (I an assuming) component ta must be like
BufferedImage image;
public void paint(Graphics g) {
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
}
Because of security reasons, the applet will only be able to access the file system if signed or running without security manager (most often on the same computer).
But its not working.
This is in no way helpful, do you get exceptions? What happens? Please post an SSCCE for better help sooner
I want to display image on applet when the user click on the image
name displayed in the Tree, the code i'm using is as below, ta is an
object of the applet because i'm using it in another class.
IMO you are going about it wrong using the JPanel object and Component#getGraphics.
Dont use Component#getGraphics() as its not good practice and not persistent thus on next call to repaint() the screen will be cleared.
Dont use Applet with Swing components rather use JApplet.
Add a custom JPanel with getters and setters for BufferedImage variable to the container and than override paintComponnet and draw the BufferedImage there.
Now to change the BufferedImage simply call the setter i.e setBackgroundImage(BufferedImage img) and than call repaint() on JPanel to show the changes. Like so:
public class MyPanel extends JPanel {
private BufferedImage bg;
public MyPanel(BufferedImage bi) {
bg=bi;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2d.drawImage(bg,0,0,this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
public BufferedImage setBackgroundImage(BufferedImage bi) {
bg=bi;
}
}
Now we use it like so:
MyPanel mp=new MyPanel(...);//create the panel with an image
...
add(mp);//add to container
...
mp.setBackgroundImage(..);//change the image being displayed
mp.repaint();//so the new image may be painted

How can I display an image in the Applet?

I have an image and I want to display it in the applet, The problem is the image wont display. Is there something wrong with my code?
Thanks...
Here's my code :
import java.applet.Applet;
import java.awt.*;
public class LastAirBender extends Applet
{
Image aang;
public void init()
{
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
public void paint(Graphics g)
{
g.drawImage(aang, 100, 100, this);
}
}
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
I suspect you are doing something wrong, and that should be just plain:
aang = getImage(getDocumentBase(), "images.jpg");
What is the content of HTML/applet element? What is the name of the image? Is the image in the same directory as the HTML?
Update 1
The 2nd (changed) line of code will try to load the images.jpg file in the same directory as the HTML.
Of course, you might need to add a MediaTracker to track the loading of the image, since the Applet.getImage() method returns immediately (now), but loads asynchronously (later).
Update 2
Try this exact experiment:
Save this source as ${path.to.current.code.and.image}/FirstAirBender.java .
/*
<applet class='FirstAirBender' width=400 height=400>
</applet>
*/
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class FirstAirBender extends JApplet {
Image aang;
public void init() {
try {
URL pic = new URL(getDocumentBase(), "images.jpg");
aang = ImageIO.read(pic);
} catch(Exception e) {
// tell us if anything goes wrong!
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
if (aang!=null) {
g.drawImage(aang, 100, 100, this);
}
}
}
Then go to the prompt and compile the code then call applet viewer using the source name as argument.
C:\Path>javac FirstAirBender.java
C:\Path>appletviewer FirstAirBender.java
C:\Path>
You should see your image in the applet, painted at 100x100 from the top-left.
1) we living .. in 21century, then please JApplet instead of Applet
import java.awt.*;
import javax.swing.JApplet;
public class LastAirBender extends JApplet {
private static final long serialVersionUID = 1L;
private Image aang;
#Override
public void init() {
aang = getImage(getDocumentBase(), getParameter("images.jpg"));
}
#Override
public void paint(Graphics g) {
g.drawImage(aang, 100, 100, this);
}
}
2) for Icon/ImageIcon would be better to look for JLabel
3) please what's getImage(getDocumentBase(), getParameter("images.jpg"));
there I'll be awaiting something like as
URL imageURL = this.getClass().getResource("images.jpg");
Image image = Toolkit.getDefaultToolkit().createImage(imageURL);
Image scaled = image.getScaledInstance(100, 150, Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(scaled));
Well , above answers are correct. This is the code I used to display image. Hope it helps:
/*
<applet code = "DisplayImage.class" width = 500 height = 300>
</applet>
*/
import java.applet.Applet;
import java.awt.*;
public class DisplayImage extends Applet
{
Image img1;
public void init(){
img1 = getImage(getCodeBase(),"Nature.jpg" );
}
public void paint(Graphics g){
g.drawImage(img1, 0,0,500,300,this);
}
}
In above code, we create an image class object and get image from location specified by codebase. Then plot the image using drawImage method. Those who are interested in knowing value of getCodeBase() and getDocumentBase() methods can add following code in paint method. They are actually location of src folder in your project folder:-
String msg;
URL url=getDocumentBase();
msg="Document Base "+url.toString();
g.drawString(msg,10,20);
url=getCodeBase();
msg="Code Base "+url.toString();
g.drawString(msg,10,40);
One more point to note:- Make sure images and classes don't have same name in src folder. This was preventing my image to be displayed.

How do I make an Image show up in a Java Swing Applet

How do I make an Image show up in a Java Swing Applet?
The simplest way is to add it as an Icon to a JLabel that you put on your GUI.
http://download.oracle.com/javase/6/docs/api/javax/swing/JLabel.html#JLabel(javax.swing.Icon)
Here's an outline of what you need
class myApplet extends JApplet {
private BufferedImage image;
myApplet() {
try {
image = ImageIO.read(new File("insert image path here"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}

Categories

Resources