I've started Java a week ago, and now I would like to insert an image into my window.
Whatever I try I keep having this in Eclipse:
javax.imageio.IIOException: Can't read input file!
package graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import src.Common;
public class Window extends JFrame
{
public class Panel extends JPanel
{
public void paintComponent(Graphics g)
{
Image img;
try
{
img = ImageIO.read(new File("/logo.jpg"));
g.drawImage(img, 0, 0, this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public Window(String title, int width, int height)
{
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Panel());
this.setVisible(true);
}
}
I think the code is pretty self-explaining.
I tried to solve the problem with this, this, and that .
What I'm trying to do is a desktop program, and my sources are stored like that :
training/src/graphics/Window
training/src/src/main
I did put the image I want to read in every folder, and still getting the issue :/
What did I do wrong?
EDIT Finally solved, here the answer
nIcE cOw gave me the link that helped.
So I did put my images into a folder, and change the way to access to them, as described in the link.
getClass().getResource("/images/yourImageName.extension");
Have you tried using new File("logo.jpg"); (without the leading /)?
And are you sure, the logo.jpg is copied to your output? (Some IDEs don't copy every file from your source-directories to your output (or target) directories.)
/src
|-> Window.java
|-> Logo.jpg
becomes
/out
|-> Window.class
(Note that the IDE/compiler does not copy the image to your output-directory and so the compiled code cannot find the image - allthough you did specify the correct path)
Try do debug which file resource you actually try to access. First step would be to get your new File("/logo.jpg").get [Canonical]Path() and print it to System.out (or alternatively watch in the the debugger). I guess the problem is the / before logo.jpg, which points to your root directory (e.g. c:) and your file isn't there, but I don't know your file setup in detail.
The problem is that you're looking at nothing before the image, so it's looking into a folder that isn't there to find it.
You have to create a folder to store the images in your project, and then call to it, your folder name in front of the image name. e.g.
ImageIO.read(new File("Folder/Image.png"));
Otherwise you can find the image by going through the entire directory, which isn't a good way as it takes longer, and when you move your project it won't be a working link as the directory will be different. For example:
ImageIO.read(new File("D:/eclipse/Workspace/Project/Folder/Image.png"));
Creating a folder in your project so its on the same level as the source folder in the directory and call to it for the image, like so:
Folder structure;
settings
src
Image Folder
bin
copypasting from a working project:
private JPanel getPanel() {
JPanel panel = new JPanel();
JLabel labelLcl = new JLabel("Ye ana!");
try {
File f = new File("./src/res/0.jpg");
//l.a(f.getCanonicalPath());
BufferedImage imgLcl = ImageIO.read(f);
ImageIcon iconLcl = new ImageIcon(imgLcl);
labelLcl.setIcon(iconLcl );
panel.add(labelLcl);
} catch (IOException e) {
e.printStackTrace();
}
return panel;
}
otherwise you can have folder/file read permission problem
Related
I am working on a Java Project. I have my images in my "resources" package and all my UI classes in my "UIPackage". I am using a JFrame form to design my window and put an image into a JLabel through the properties tab in the window editor. However, this does not scale the image so to get around this, I wrote code to grab an image from the resources package, scale it, and then display it in the JLabel. However, my attempts to grab an image file return null. The especially frustrating part is if I copy (not editing the generated code) what the form does when I add an image to the JLabel through the properties tab, it still doesn't work. What am I doing wrong here?
Project Navigator
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.image.BufferedImage;
/**
*
* #author Admin
*/
public class LandingPage extends javax.swing.JFrame {
/**
* Creates new form LandingPage
*/
public LandingPage() {
initComponents();
//this works
sideArtLabel.setIcon(new ImageIcon(new ImageIcon("C:\\Users\\Admin\\Documents\\NetBeansProjects\\HowtoFeedYourDragon\\src\\main\\java\\resources\\2561-bearded-dragon-lawler.jpg").getImage().getScaledInstance(sideArtLabel.getWidth(), sideArtLabel.getHeight(),Image.SCALE_SMOOTH)));
//path is null
System.out.println("jpg 1 " + getClass().getResource("/resources/2561-bearded-dragon-lawler.jpg"));
//sideArtLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/2561-bearded-dragon-lawler.jpg")));
//but this doesn't. path is null
try
{
System.out.println("jpg 2 " + getClass().getResource("/resources/01.jpg"));
BufferedImage sideArtImg = ImageIO.read(getClass().getResource("/resources/01.jpg"));
ImageIcon sideArtIcon = new ImageIcon(sideArtImg);
sideArtLabel.setIcon(sideArtIcon);
}
catch(IOException e)
{
e.printStackTrace();
}
}
I want to include a font as a resource file in my deployed application.
To use it in swing, I know that I can import a font like this:
InputStream is_regular = Resources.class.getResourceAsStream("Lato-Regular.ttf");
Font regular_font = Font.createFont(Font.TRUETYPE_FONT, is_regular);
But how can I register also the bold variant, which is stored in a file called "Lato-Bold.ttf"?
I also know that I can access the variant weights via the attributes field. But how do I register these?
The Lato Font comes in 18 different variants such as light, semibold, hairline, etc.
You write a FontManager. The solution to almost any Java problem is either a manager or a factory. Sometimes you need a manager-factory.
One way would be like this.
package com.ggl.testing;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resources;
public class FontManager {
public static Font getNormalFont() {
return getFont("Lato-Regular.ttf");
}
public static Font getBoldFont() {
return getFont("Lato-Bold.ttf");
}
private static Font getFont(String fontFileName) {
InputStream is = Resources.class.getResourceAsStream(fontFileName);
try {
return Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
You write a getter method for the 18 variations of your font.
The return null at the end of the getFont method can be changed to return a standard font.
If you want to deploy the fonts with your application, you need to copy the font files into a resource folder in your application. You add the application resource folder to your Java build path (classpath). This line in the code would change to
InputStream is = getClass().getResourceAsStream("/" + fontFileName);
There is a web site developed entirely in PHP with GD library that mainly deals with printing text over a random image.
The text has to be printed in any of about 100 prescribed TTF fonts (residing in a directory near the .php files) in a dozen of prescribed colors and there is a requirement to specify location of the text according to any of several prescribed algorithms.
This is solved by using imagettfbox() which returns geometry of the text, which is then mapped onto the image using imagettftext().
What can I use in Java to achieve the same functionality with servlets/beans?
I can put the TTF fonts anywhere I have to. Registering them in Windows is undesirable, but if that's the only option we'd go for it (currently they are not).
#LexLythius:
From your link and some other resources I pieced together a working solution to drawing text over graphics:
// file is pointed at the image
BufferedImage loadedImage = ImageIO.read(file);
// file is pointed at the TTF font
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
Font drawFont = font.deriveFont(20); // use actual size in real life
Graphics graphics = loadedImage.getGraphics();
FontMetrics metrics = graphics.getFontMetrics(drawFont);
Dimension size = new Dimension(metrics.getHeight(), metrics.stringWidth("Hello, world!"));
graphics.setFont(drawFont);
graphics.setColor(new Color(128, 128, 128); // use actual RGB values in real life
graphics.drawString("Hello, world!", 10,10); // use Dimension to calculate position in real life
What is remaining is displaying that image in a servlet and deciding what functionality goes where - to a servlet or bean.
You can get an OutputStream from the servlet response, and pass that OutputStream to ImageIO.write. Example based on the code from here (not my code):
http://www.avajava.com/tutorials/lessons/how-do-i-return-an-image-from-a-servlet-using-imageio.html
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg"); // change this if you are returning PNG
File f = new File( /* path to your file */ );
BufferedImage bi = ImageIO.read(f);
// INSERT YOUR IMAGE MANIPULATION HERE
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out); // or "png" if you prefer
out.close(); // may not be necessary; containers should do this for you
}
Depending on how much memory you have, pre-loading the fonts and keeping a pool of them may save a bit of time.
I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.
I'm trying to create a splash screen using LWUIT. I want a form to load and display text and an imagefor 5 seconds then continue to the next form. I have a code but fails to show the image. The class and the image are stored together int he same package. Instead, it shows an error.
java.io.IOException
What could be the problem? This is the code
package tungPackage;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import javax.microedition.midlet.MIDlet;
public class photoMidlet extends MIDlet {
public void startApp() {
Display.init(this);
try {
Form splashscreen = new Form();
// Label splashText = new Label("Baldy");
Image image = Image.createImage("/splash.png");
Label pictureLabel = new Label(image);
splashscreen.addComponent(pictureLabel);
splashscreen.show();
} catch (Exception ex) {
Form x = new Form("ERROR");
String y = ex.toString();
Label g = new Label(y);
x.addComponent(g);
x.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Open your JAR file using a ZIP utility (e.g. 7-zip) and look in the root of the file. If splash.png isn't in the root of the jar that's your problem!
Place splash.png so it is in the root of the jar.