Java: Loading BufferedImage from res Folder - java

Im trying to load an image from my res folder which is already part of the Java BuildPath. Sadly it seems I am no able to find the image neither with relative nor with an absolute path to the file.
Im always getting this error message:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at schneider.twodgame.BufferedImageLoader.loadImage(BufferedImageLoader.java:14)
at schneider.twodgame.Game.init(Game.java:64)
at schneider.twodgame.Game.run(Game.java:99)
at java.lang.Thread.run(Unknown Source)
And here is a part of the code:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException {
System.out.println(getClass());
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
This is the method I am trying to load the image with. The method is part of my Main Class:
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/res/sprite_sheet.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Have a look here.
spriteSheet = loader.loadImage("/sprite_sheet.png");
Should work.

It is currently looking in your .class file folder or .jar file at the location of your class files in:
[root folder of class files]/res/sprite_sheet.png
Maybe it should be looking in:
[root folder of class files]/schneider/twodgame/res/sprite_sheet.png
In that case you should remove the leading slash (/).

Related

accessing image resource in java ( jboss server)

I'm trying access image in java code.
For jboss server getting file not found exception.
Image logo = new getImage("/images/test_image.bmp");
public getImage(String fileName) throws Exception
{
try{
image=Image.getInstance(ImageIO.read(getClass().getResourceAsStream(fileName)),null);
}catch (Exception e ){
e.printStackTrace();
}
}
exception -
java.io.FileNotFoundException: /images/test_image.bmp
test_image.bmp is stored in src->images folder.
Is there any solution?
Yes you can achieve this by using ServletContext as follows
ServletContext servletContext = new ServletContext();
String relativePath = "/images/test_image.bmp";
String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
Image img = Image.getInstance(absoluteDiskPath);
use img object where you want.

Path can not be found, creates argument exception

I know what the problem is I just do not know how to fix it. So I have an image that I am trying to render in my program. I use ImageIO to load the image. But it seems to have a problem wit the path I am giving it. I am using NetBeans as my IDE and I dont know if I am saving the image file correctly.
First method:
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/sprite_sheet.png");
}catch(IOException e){
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1,1,32,32);
}
the loader BufferedImageLoader class:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
I have the image saved under a 'res' folder under 'src' folder.
Error:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
Thank you.
Why do you need to use getClass().getResource() ?
Most simple usage of ImageIO.read is as follows.
image = ImageIO.read(new File(path));
You may need to add folders to path also.
spriteSheet = loader.loadImage("/src/res/sprite_sheet.png");
Try using an absolute path for your file or if you need a relative check this post (eg assuming you have a res folder under default package did you try "/res/yourfile"

Extracting Text From JPG

I've tried this code and added the needed jar files but still I'm getting an error message like Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302'.
Is there a complete tutorial how to extract text and what things should be done to address the error? Any help is appreciated...
import net.sourceforge.tess4j.*;
import java.io.File;
public class ExtractTxtFromImg {
public static void main(String[] args) {
File imgFile = new File("C:\\Documents and Settings\\rueca\\Desktop\\sampleImg.jpg");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try {
String result = instance.doOCR(imgFile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
In addition to adding the jars, you also need to add the natives. You can do so with Djava.library.path="C:\[absolute path to dir containing *.dll files and such]"
Note that you need to provide the directory, not the file itself.

Can't load a BufferedImage

I have a form with that code:
public Form()
{
initComponents();
try
{
File file= new File("avatar.jpg");
BufferedImage image= ImageIO.read(file);
}
catch (IOException ex)
{
System.out.println("Failed to load image");
}
}
The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:
What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?
Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().
It would be something like:
public class Test {
private static final String absName = "/yourpackage/yourimage.jpg";
public static void main(String[] args) {
Class c=null;
try {
c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
} catch (Exception ex) {
// This should not happen.
}
InputStream s = c.getResourceAsStream(absName);
// do something with it.
}
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResourceAsStream(name); // A system class.
}
return cl.getResourceAsStream(name);
}
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResource(name); // A system class.
}
return cl.getResource(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
}
Reference:
Accessing Resources
It looks like you have a namespace of poker.*
It all depends on where the jvm is initialized from.
Where is your main? Is it in /Users/ramy/NetBeansProjects/Poker/src?
Also, I suggest you use getResource() for all of your file loading needs, especially inside jars.
this.getClass().getResource("/resource/buttons1.png")
or
this.getClass().getResourceAsStream("/resource/TX_Jello2.ttf")
You can find out where your programs default path is by doing the following:
System.getProperty("user.dir");
Without seeing the error I would say the most likely cause is it can't find the file. So I suggest you replace "avatar.jpg" in the File constructor with the absolute file path to it. e.g.
File file = new File("INSERT_PATH_TO_FILE/avatar.jpg");
You cannot assume the image will be "there" because the relative path between your .java and the image seems ok.
Accessing a resource depends of your "kind" of project (Web, standalone....). In your case, you can try to get the image from your classpath
final File inputFile = new ClassPathResource("....").getFile();
final BufferedImage inputImg = ImageIO.read(inputFile);

why do i get this error when i play .wav sound file using eclipse IDE?

whenever i try to play a .wav or .mp3 sound file USING ECLIPSE IDE i get
this error, check the code(it's very simple why would i get errors?) :
import sun.audio.*;
import java.io.*;
public class Sound {
String Filename = "someSound.wav";
InputStream in;
AudioStream as;
public Sound() {
try {
in = new FileInputStream(Filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
as = new AudioStream(in);
} catch (IOException e) {
e.printStackTrace();
}
AudioPlayer.player.start(as);
AudioPlayer.player.stop(as);
}
static public void main(String[] args) {
Sound s = new Sound();
}}
and this is the exception :
java.io.FileNotFoundException: someSound.wav (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at Sound.<init>(Sound.java:14)
at Sound.main(Sound.java:10)
Exception in thread "main" java.lang.NullPointerException
at sun.audio.AudioStream.<init>(AudioStream.java:65)
at Sound.<init>(Sound.java:19)
at Sound.main(Sound.java:10)
so what's the problem?
edit 1 :
i also tried to change the path to
C:\Users\Rev3rse\workspace\Project1\src\someSound.wav
and i got a diffrent excpetion check it :
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at Sound.<init>(Sound.java:16)
at Sound.main(Sound.java:26)
FileInputStream expects the file path to be partitioned with double slashes.So instead of giving the source path as C:\Users\Rev3rse\workspace\Project1\src\someSound.wav use double slashes for the partition.
HOPE IT WORKS !!!
I would recommend creating the InputStream from a resource instead so you are not tied down to a path. Something like:
in = this.getClass().getResourceAsStream("someSound.wav");
That eliminates the path and creates one less headache for you the developer to worry about.

Categories

Resources