Skip to main content
gamedev.net
🔒 Locked

[java] Loading an image

Started by cMADsc 1 reply 300+ views
Original Post
cMADsc
cMADsc
Greetings all, I am new to java coming from a C/C++ background. I was wondering if it was possible to load an image, instead of using an URL I put the pathname to the image? Due to the fact that my pc has no isp and I was thinking if I put the path it should still work. No compile errors but when the program is executed I get some errors like "cannot find resource". Sorry I didnot post the whole error, using 2 pcs here! I am using JCreator Pro 2.5 and XP. Any help is appreciated, thanks in advance! ========================================= import java.awt.Graphics; import java.awt.Image; public void Player extends public java.applet.Applet { Image myImage; void init() { myImage =getImage(getcodeBase(),"C:/MyProgramms/player.gif"); } void public paint(Graphics g) { g.drawImage(myImage, 0, 0, this); } ======================== //code in applet ================== //applet code="player.class" codebase="C:/MyProgramms/player.gif" height=200 weight=100> ----------------------------- "There are ones that say they can and there are those who actually do." "...u can not learn programming in a class, you have to learn it on your own." [edited by - cMADsc on January 9, 2003 3:50:33 PM]
-----------------------------"There are ones that say they can and there are those who actually do.""...u can not learn programming in a class, you have to learn it on your own."
GKW
GKW
You will want to use something like this:

String starfield = "com/foo/StarField.jpg";

URL urlbackground = this.getClass().getClassLoader().getResource(starfield);

Image stars = getToolkit().getImage( urlbackground );


This works exactly the same whether your resources are in directories on a disk or in a jar. Just make sure the image is in the right place on your drive/jar.

"... we should have such an empire for liberty as she has never surveyed since the creation ..."
Thomas Jefferson
"... we should have such an empire for liberty as she has never surveyed since the creation ..."Thomas Jefferson
Petr Stedry
Petr Stedry
You can always use ImageIO (since 1.4 I think) to read/write images. The read method takes a File/URL/InputStream/ImageInputStream as a parameter. So it's up to you what suits you best.

have fun ...

Petr Stedry

P.S.: You can also use the URL as described in the previous answer to obtain the file URL. Using relative paths is mostly the better way to locate resources, that are bundled with your application.

EDIT: added the Post Scriptum part ...

[edited by - Petr Stedry on January 10, 2003 5:01:50 AM]
Petr Stedry

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.