Java - getImage and drawImage do not work for local files - java

I am working by way through a tutorial: http://www.kilobolt.com/day-4-enter-the-robot.html
and have been having a problem getting a simple image to display in the applet. I am using IntelliJ 13 Community Edition. The main for loading the images is here:
It does the image setup in the init method:
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "data/character.png").toString());
}
where character is a sprite I obtained from the tutorial website. I saved it in a folder called data. The file structure can be seen here:
When I run this I just see a black background and character.png is not displayed. However if I change the getImage line to:
character = getImage(base, new URL("http://www.kilobolt.com/uploads/1/2/5/7/12571940/character.png").toString());
and point at the URL directly it works. I suspect this must be a path issue but I have not been able to get it working.

I am working on the same program and had the same problem. When run, the document base is actually in KiloboltGame/bin so you need to add your data/character.png here.

Related

Cannot display image with correct path using ImageIcon

I've been having an issue with displaying images in Java with the ImageIcon class. The code is very simple, but it simply displays a window like
.
import javax.swing.*;
public class TestButtonIcons {
public static void main(String[] args) {
ImageIcon usFlag = new ImageIcon("images/usFlag.png");
JFrame frame = new JFrame();
JButton jbt = new JButton(usFlag);
frame.add(jbt);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My image is located under the src folder, and my IDE can also detect it, since it shows
.
Also, if I change the path mentioned above into the full path, like
"/Users/Mac/Documents/Java TB/ImageIcons/src/images/usFlag.png"
The program works normally.
Any help will be appreciated.
Thanks!
ImageIcon(String) assumes that the image is located on the disk somewhere. When you place the image inside the src directory, most IDE's will bundle the image into the resulting Jar (AKA embedded resource), which means that they are no longer a "file" on the disk, but a byte stream in a zip file, so you need to access them differently.
Start by using ImageIO.read, unlike ImageIcon, it will throw an IOException when the image can't be loaded.
You need to use Class#getResource or Class#getResourceAsStream depending on how need to reference it, for example...
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getResource("/images/usFlag.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
Take a look at Reading/Loading an Image for more details
Make sure you use "./path" or else it might think it's an absolute path. "." is the current directory, which indicates a relative path instead of an absolute one.
Problem is in the location of the image. Place your image in source folder. Try like
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("images/usFlag.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
I assume that the image is in src/images.
The path you give to the constructor of ImageIcon is relative to the location of your class.
So if your class is org.example.TestButtonIcons it will look for org/example/images/usFlag.png
Hope this helps.

My method from another class is not being called?

Alright I am super confused right now, I am using a piece of code in my program that is 95% similar to another piece I've used in an another program, the only difference is that it worked in the previous program...
it is basically a Image loading class/method and I'm trying to call it in my main class but its not working and the "cannot find symbol - class Image" error occurs.
Where I'm calling the method from my GameImage class:
//STORE IMAGES
private static Image background;
GameImage class:
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
Where I load the image in main class:
//load the images
background = GameImage.loadImage("Images//background.jpg");
So yeah I dont know why that error keeps popping up because ive used that exact same code structure and GameImage class in another program... hmm
Any help would be great thanks :)
You lack the Image import statement.
Import the Image class and you should be fine.

Processing: Sketch gets stuck when using Capture class

I'm using Processing 2.0.3 on Windows 8. I tried to use the following code but I've no idea why my sketch couldn't run when I'm using the processing.video.* library:
import processing.video.*;
Capture cam;
void setup() {
size(200, 200);
cam = new Capture(this);
cam.start();
}
void draw() {
if (cam.available()) {
// Reads the new frame
cam.read();
}
image(cam, 0, 0);
}
I notice that the sketch will get stuck and will not open the sketch applet window at all if I call anything related to the Capture class. Calling println(Capture.list()); for example will cause the sketch to stuck at where ever that line was called.
What do I have to do to resolve this problem?

Java ImageIcon.GetImage hanging

I am having trouble with ImageIcon().GetImage()
The strange thing is, is that it sometimes works and shows me the window with the maps on it, and other times it doesn't. It also works on other computers flawlessly but not on mine!
I have tried everything, reinstalling Java, reinstalling IntelliJ, also disabling my firewall, but to no avail. I have also written a similar program in C# which works perfectly, which leads me to believe it isn't a permissions error. I have also tested it on a basic Windows XP system with an on board graphics card which also works perfectly.
Here is my code:
public class main {
public static void main(String[] args) {
System.out.println("Running main..");
try
{
URL url = new URL("http://maps.googleapis.com/maps/api/staticmap?center=-33.80382155278416,18.567184266922002&zoom=17&size=1024x1024&maptype=hybrid&sensor=false&format=png&key=AIzaSyCVnp9iTXRSS3ZE5FjzF7uNZavazWhLko4");
Image img=new ImageIcon(url).getImage();
System.out.println("INFO :"+img);
new ImageFrame(img);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class ImageFrame extends JFrame{
public ImageFrame(Image img){
setPreferredSize(new Dimension(540, 480));
setaImg(img);
ImagePanel somePanel = new ImagePanel(540, 480);
add(somePanel);
setVisible(true);
}
private Image aImg;
public Image getaImg() {
return aImg;
}
public void setaImg(Image aImg) {
this.aImg = aImg;
}
public class ImagePanel extends JPanel{
public ImagePanel(int width, int height){
setPreferredSize(new Dimension(width, height));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
}
}
}
}
I have ran it through the step through debugger and it stops at this line:
Image img=new ImageIcon(url).getImage();
But with no error, it just hangs forever.
I am totally confused as to why it isn't working on my system, and only my system. Any help would be GREATLY appreciated.
Works fine for me
Google's not blocking you are they? From memory you have something like 10,000 queries a day or something.
Try downloading the URL manually using the InputStream (URL.openStream()) and see if you're getting some kind of response other than an image binary.
UPDATED
After investigation, found to be a problem with Java 7 and IPv6 as documented here Downloading files using Java randomly freezes
Always start and update the GUI on the EDT. See Concurrency in Swing for more details.
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
That comment is very good advice, since a 4 char edit should fix the problem.
g.drawImage(getaImg(), 0, 0, this); // Observer is good for asynchronous image load

How to get screenshot of any Linux/Windows application running outside of the JVM

Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?
Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.
Here is the answer for Windows (not sure if alt+printScr works on linux :P)
I guess one way to achieve this
1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)
2. read the clipboard!
Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.
Code to Fire commands to get active window on clipboard
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class ActiveWindowScreenShot
{
/**
* Main method
*
* #param args (not used)
*/
public static void main(String[] args)
{
Robot robot;
try {
robot = new Robot();
} catch (AWTException e) {
throw new IllegalArgumentException("No robot");
}
// Press Alt + PrintScreen
// (Windows shortcut to take a screen shot of the active window)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
System.out.println("Image copied.");
}
}
Code to read image on clipboard
// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!
You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.

Categories

Resources