Reading an image in Netbeans - java

I have an image file in my project. The hierarchy looks like this:
I'm trying to read Manling.png into Manling.java using this code:
public BufferedImage sprite;
public Manling()
{
try
{
File file = new File("resources/Manling.png");
sprite = ImageIO.read(file);
} catch (IOException e) {}
System.out.println(sprite.toString()); //This line is to test if it works
}
I always get a NullPointerException on the println statement, so I assume the path is wrong. I've tried moving the image to different places in the project and I've tried changing the file path (e.g. 'mine/resources/Manling.png' and '/resources/Manling.png'). Any ideas?
If you want a full compilable example, try this one:
package minesscce;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.URL;
public class Mine extends JFrame
{
private BufferedImage sprite;
public static void main(String args[])
{
Mine mine = new Mine();
}
public Mine()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(800, 600);
setExtendedState(Frame.MAXIMIZED_BOTH);
setBackground(Color.WHITE);
try
{
File file = new File("resources/Manling.png");
sprite = ImageIO.read(file);
} catch (IOException e) {}
System.out.println(sprite.toString());
}
public void paint(Graphics g)
{
g.translate(getInsets().left, getInsets().top);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprite, 0, 0, this);
Toolkit.getDefaultToolkit().sync();
g2d.dispose();
}
}
Just set up the project like this, using any image you want:

Try
ImageIO.read(Mine.class.getResource("../minesscce.resources/Manling.png"));
Here's an example:
Hierarchy
Result
And here's the code...
public final class ImageResourceDemo {
private static BufferedImage bi;
public static void main(String[] args){
try {
loadImage();
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadImage() throws IOException{
bi = ImageIO.read(
ImageResourceDemo.class.getResource("../resource/avatar6.jpeg"));
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.WHITE);
frame.add(new JLabel(new ImageIcon(bi)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

If I am not wrong, root directory of your application is the project directory or the source directory. (Not sure exactly which one is)
If it is project directory then resources/Manling.png is MineSSCCE/resources/Manling.png. Nothing is there!
If it is the source directory, resources/Manling.png is MineSSCCE/Source/resources/Manling.png. Nothing is there either!
The actual location is MineSSCCE/Source/minesscce/resources/Manling.png
That is why it was not working.

Related

Graphics draw image rendering weird squares

So im making my own game in Java, yeah a weird thing. The problem is that ive made a method to return a BufferedImage with an image loaded in it:
public static BufferedImage getImage(String img) {
try {
image = ImageIO.read(Game.class.getResourceAsStream("./img/" + img));
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
return image;
}
This method is returning the image for my icon with no problems.
frame.setIconImage(Game.getImage("icon.png"));
The problems is when i draw the image on the canvas:
g.drawImage(Game.getImage("aa.png"), 0, 0,Game.WIDTH, Game.HEIGHT,null);
That displays this:
And the actual image is:
Can someone help me out?
I should say it works on Windows but not on GNU/Linux
Taking your image, and placing in a subdirectory/package below this class (in the img package) worked just fine for me
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MenuPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class Game {
public static BufferedImage getImage(String named) throws IOException {
return ImageIO.read(Game.class.getResource("img/" + named));
}
}
public class MenuPane extends JPanel {
private BufferedImage background;
public MenuPane() {
try {
background = Game.getImage("aa.jpg");
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(200, 200) : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
}
}
}
What did I notice? aa is a jpg when I download, but is named as a png in your code, might not be an issue, but is a different.
Without a Runnable example it's near impossible to know what else to suggest
I finally found that it was a hardware issue. I returned home and tested it on a VM + on the same HDD. It works just fine, sorry for taking your time to answer.

Java-Image not drawing to screen

I am trying to draw an image to the screen using Java. The problem is that it does not appear and no errors occur.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class GameClass extends JPanel implements ActionListener, KeyListener{
private BufferedImage image;
public GameClass(){
Timer time = new Timer(15, this);
time.start();
this.addKeyListener(this);
this.setFocusable(true);
}
public void openImage(){
try {
image = ImageIO.read(this.getClass().getResource("spaceship.png"));
} catch (IOException e) {
System.out.println("An error occurred!");
}
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, Main.WW, Main.WH);
g.drawImage(image,Main.WW/2,Main.WH/2,null);
}
public void actionPerformed(ActionEvent e){
repaint();
}
public void keyPressed(KeyEvent e){
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
You need to call you openImage() method in your constructor.
I renamed this to loadImages() so that this method can handle loading multiple images. I also created a static image loading function.
Note: If you have not already, create a resources/ folder in your projects' src/ folder. This folder will contain your application's assets i.e. text, image, and other data files.
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*
public class GameClass extends JPanel
implements ActionListener, KeyListener {
private static final long serialVersionUID = -2508183917768834794L;
private Image image;
// Added this, because you did not include it.
private class Main {
static final int WW = 256;
static final int WH = 256;
}
public GameClass() {
Timer time = new Timer(15, this);
time.start();
this.addKeyListener(this);
this.setFocusable(true);
this.loadImages();
}
// Load all required images into instance variables.
public void loadImages() {
image = loadImage("spaceship.png");
}
// Draw the image to the panel.
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, Main.WW, Main.WH);
// Dimensions of spaceship
int imgW = image.getWidth(null);
int imgH = image.getHeight(null);
// Dimensions of panel
int pnlW = this.getWidth();
int pnlH = this.getHeight();
// Draw the spaceship in the center of the window.
g.drawImage(image, pnlW/2 - imgW/2, pnlH/2 - imgH/2, null);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
// Static image loader method which utilizes the `ClassLoader`.
public static Image loadImage(String filename) {
try {
return ImageIO.read(GameClass.class.getClassLoader().getResource("resources/" + filename));
} catch (IOException e) {
System.out.println("Error loading image: " + filename);
}
return null;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
Container panel = new GameClass();
frame.setSize(Main.WW, Main.WH);
frame.setTitle("Spaceship Game");
frame.setContentPane(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

java add image to canvas

I'm trying to add a image to a java canvas.
I'm using the "ImageIO.read" to get the image source. The problem i'm facing is that i don't know how to display it on the canvas after reading the image location. Also later i will need to load a different image(e.g. after a button pressed) how can i do this. The update (canvas.update) method needs a "Graphics" parameter instead of an image.
Below you'll find my code simplified (i left out all code that's not relevant to the canvas issue.)
public class MainWindow {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Canvas csStatusImage = new Canvas();
csStatusImage.setBounds(393, 36, 200, 200);
frame.getContentPane().add(csStatusImage);
Image iMg;
try {
iMg = ImageIO.read(new File("Images/Error_status_1.png"));
csStatusImage.imageUpdate(iMg, 10, 2, 2, 9, 10);
csStatusImage.checkImage(iMg, (ImageObserver) this);
csStatusImage.createImage((ImageProducer) iMg);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
First of all, you going to need some way to paint the image. To achieve this, you can override the paint method of the java.awt.Canvas class
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
Frame frame = new Frame("Testing");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.add(new ImageCanvas());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class ImageCanvas extends Canvas {
private BufferedImage img;
public ImageCanvas() {
try {
img = ImageIO.read(new File("Images/Error_status_1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g.drawImage(img, x, y, this);
}
}
}
}
I have to tell you, AWT is out-of-date by some 15+ years, replaced by Swing. You may find it hard to get additional support with this API. If you can, you'd better of using Swing or JavaFX

IIOException when reading image [duplicate]

This question already has an answer here:
Java ImageIO: can't read input file
(1 answer)
Closed 8 years ago.
SOLVED! crew4ok helped and others too,Thanks!Error in the following section of code. I am trying to load a png image into a BufferedImage type but can't do so, and I'm working in ubuntu.I have a root directory called TicTacToe and under it i have src and res folder.In src i have my java files and in res i have a png image.When i am trying to access png file from res folder it gives error.
link for my directory structure:http://tinypic.com/view.php?pic=210aamd&s=5#.Up38mLUW3h8
package com.blogspot.edwn112;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Game extends JFrame implements MouseListener {
private JPanel panel = new JPanel();
private JPanel gameArea = new JPanel();
private JButton button = new JButton("Play Again");
private JLabel label;
private BufferedImage resizedImage;
public Game() {
addMouseListener(this);
panel.add(button);
BufferedImage image = null;
try {
image = ImageIO.read(new File("/TicTacToe/res/tictactoe.png"));
} catch (IOException e) {
e.printStackTrace();
}
resizedImage = resize(image, 100, 100);
gameArea.add(label);
add(gameArea, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public static BufferedImage resize(BufferedImage image, int width,
int height) {
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public void paint(Graphics g) {
g.drawImage(resizedImage, 0, 0, getWidth(), getHeight(), null);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Error in native look");
}
JFrame frame = new Game();
frame.setTitle("Tic Tac Toe");
frame.setSize(400, 300);
// frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Error:
Archive for required library:'res/tictactoe.png' in project'TicTacToe' cannot be read or is not a valid ZIP file
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
If the project root folder is TicTacToe, you want to just use "res/tictactoe.png" as the file path.
TicTacToe (project root dir)
res
tictacttoe.png
src
When you use this "TicTacToe/res/tictactoe.png" You saying that the file structure is like this
ProjectRoot
TicTacToe
res
tictactoe.png
Have you tried new File(getClass().getResource("// path to tictactoe"); ?
Does you app have enough permissions to read the file?
I found theese lines in ImageIO.read() sources:
if (!input.canRead()) {
throw new IIOException("Can't read input file!");
}
And input.canRead() in turn gives us:
public boolean canRead() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
return fs.checkAccess(this, FileSystem.ACCESS_READ);
}

I'm attempting to import a picture into my projecy but does not work

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class spriteStore {
public static BufferedImage playerStanding;
public void getImage()
{
try
{
playerStanding = ImageIO.read(new File("Cobalt\\pictures\\playerStanding1.png"));
}
catch(Exception e){System.out.println("Picture not found");}
}
}
I am trying to read an image to save as a BufferedImage object, but when i run the main code,
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Cobalt {
public Boolean movingLeft, movingRight, firstJump, secondJump;
public int jump = 0;
public Dimension screenSize;
public JFrame frame;
public JPanel panel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run(){
new Cobalt();
}
});
}
public Cobalt()
{
frame = new JFrame("COBALT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(true);
frame.setSize(500,500); //width and height
panel = new MyPanel();
frame.getContentPane().add(panel);
}
class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
Graphics g2D = (Graphics2D) g;
super.paint(g);
g2D.drawImage(spriteStore.playerStanding, 100, 100, null);
}
}
}
and the image will not show up. I'm using eclipse, and am relatively a noob, so please inform me of my error.
There is no need to do custom painting to show an image.
You can use a JLabel. Read the section from the Swing tutorial on How to Use Icons.
I assume that you have in your project a structure like this:
Cobalt
|
\---src
| Cobalt.java
|
\---pictures
playerStanding1.png
Try the following:
public static void main(String[] args) throws Exception {
URL url = ClassLoader.getSystemClassLoader().
getResource("pictures/playerStanding1.png");
BufferedImage playerStanding = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(playerStanding));
JOptionPane.showMessageDialog(null, label);
}
Try this to create the jlabel
ImageIcon icon = createImageIcon("images/middle.gif",
"a pretty but meaningless splat");
JLabel thumb = new JLabel();
thumb.setIcon(icon);
And load the image like this
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
//System.err.println("Couldn't find file: " + path);
return null;
}
}
And if you want it from a url
URL PicURL = new URL("http://...");
ImageIcon imgThisImg = new ImageIcon(PicURL));
jLabel2.setIcon(imgThisImg);

Categories