Loading a BufferedImage in a .jar - java

I'm currently trying working on an own game and created a Animation class, my problem is that i want the programm to be able to still find all the images when i create a jar out of it so I tried to load an Image via
BufferedImage img = ImageIO.read(getClass().getClassLoader().getResourceAsStream("player.png"));
but when I start the code I get a NullPointerException, i checked the location twice but the image exists and there should be no problems, can anyone help me out a bit?

try this
public BufferedImage loadImage(String fileName){
BufferedImage buff = null;
try {
buff = ImageIO.read(getClass().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return null;
}
return buff;
}

Related

Dynamically get image paths in eclipse

this is my code below
public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png");
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png");
private BufferedImage loadBufferedImage(String string)
{
try
{
BufferedImage bi = ImageIO.read(this.getClass().getResource(string));
return bi;
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
I just wanted to know if there's a way to dynamically get the images from my image directory in eclipse instead of having to access them one by one

How to convert FITS to JPG in Java?

I need to convert a fits file to jpg in java. I've tried with imageJ but I need a simple library without GUI. I'm developing a web page in java and I need to convert the file in background (headlessly).
Alex solved it by doing this:
public void fitsToJpg(String source, String destination, String image){
try {
ImagePlus imageP = openImage(source+image);
final File out = new File(destination+"preview.jpg");
BufferedImage imagen = imageP.getBufferedImage();
ImageIO.write(imagen, "jpg", out);
} catch (IOException ex) {
Logger.getLogger(Fits.class.getName()).log(Level.SEVERE, null, ex);
}
}

How to properly extract simple try/catch blocks that load resources in java?

Currently there is a method that loads an image from an URL and then processes it like follows:
BufferedImage tempImage;
try {
tempImage = ImageIO.read(url);
}
catch (IOException e) {
return;
}
final BufferedImage image = tempImage;
To clean the code up a bit, I would like to extract the try/catch block while preserving the functionality of exiting the method if the loading of the image fails. I have tried extracting the block as follows:
final BufferedImage image = loadImageFromURL();
if (image == null)
return;
//--------------------------------------
private BufferedImage loadImageFromURL() {
BufferedImage tempImage = null;
try {
tempImage = ImageIO.read(url);
}
catch (IOException e) {
LogUtils.severe(e);
}
return tempImage;
}
The problem is that if the loading of the image fails, the method returns null, which does not make the code any cleaner, as I have to perform an additional null check. I have read through Clean Code: A Handbook of Agile Software Craftsmanship but all the examples seem to rethrow the exception in some form: is that the only/correct way to go?
We don't know the complete situation you are in, but I would just add a throw clause to the method signature and do not use any try catch.
private BufferedImage loadImageFromURL() throws IOException
{
return ImageIO.read(url);
}
Which basically resolves back to the original method, without extracting the try-catch. If the loading fails, the method will stop, but not really return. The exception will go all the way back to some piece of code that handles it properly.

Writing imageicon in the output stream

I am not able to write an imageicon in the outputstream .Here is my code.Please anyone help me.
public ScreenSpyer(Socket socket, Robot robot, Rectangle rect) {
this.socket = socket;
this.robot = robot;
this.rectangle = rect;
start();
}
public void run(){
oos = null;
try{
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(rectangle);
// oos.flush();
// oos.reset();
}catch(IOException ex){
ex.printStackTrace();
}
while(continueLoop){
//Capture screen
image = robot.createScreenCapture(rectangle);
imageIcon = new ImageIcon(image);
//Send captured screen to the server
try {
System.out.println("before sending image");
System.out.println("intermidiate");
// oos.reset();
oos.writeObject(imageIcon);
System.out.println("New screenshot sent");
//oos.reset();
//oos.flush();
oos.reset();
} catch (IOException ex) {
ex.printStackTrace();
}
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
You say "it gets stuck"; how do you know? This is obviously a thread, terminated by other code. I assume the trace output "New screenshot sent" does not get executed; that could be because it is stuck, or writeObject() could be throwing an exception you are not catching.
Catch throwable after IOException to see if there's another exception.
Right after your image is generated, replace it with a known image and see if it gets written; that will help figure out if there's a problem with this particular writeObject() call or something wrong elsewhere in the program.
Try using a small rectangle from the screen, instead of all of it. Perhaps getScreenSize() returns something unusable, like something one pixel size larger than the screen. If a small rectangle works, try reducing the rectangle by a few pixels in both dimensions.
It looks like you are actually trying to save the screenshot images to an OutputStream or maybe to disk.
In this case, you don't have to use an ImageIcon. You can save the image that is returned from the createScreenCapture call. You can use ImageIO for saving images:
ImageIO.write(BufferedImage image, String formatName, File output);
or
ImageIO.write(BufferedImage image, String formatName, ImageOutputStream output);
or
ImageIO.write(BufferedImage image, String formatName, OutputStream output);
The formatName can be either jpg, png or gif.

Java - How to access an image packed in an applet jar

I have created an applet jar. That jar contains an images in the following folder
com\common\images\red.bmp
Now, I want to display this image on the Swing Applet.
private static final ImageIcon redIndicator = new ImageIcon("com\\common\\images\\red.bmp");
After that, I have attached the redIndicator to a JPanel but I am not able to see this image.
Any suggestions?
==================================EDITED=========================================
private static final ImageIcon marker = loadImage("com/common/images/scale.jpg");
#SuppressWarnings("unused")
private static ImageIcon loadImage(String imagePath) {
BufferedInputStream imgStream = new BufferedInputStream(TpcHandler.class.getResourceAsStream(imagePath));
int count = 0;
if (imgStream != null) {
byte buf[] = new byte[2400];
try {
count = imgStream.read(buf);
} catch (java.io.IOException ioe) {
return null;
} finally {
if (imgStream != null)
try {
imgStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (count <= 0) {
LOGGER.warning("Empty image file: " + imagePath);
return null;
}
return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
} else {
LOGGER.warning("Couldn't find image file: " + imagePath);
return null;
}
}
I am getting the following exception
java.io.IOException: Stream closed
at line count = imgStream.read(buf);
This should do the trick (if called from a class loaded from that same jar):
new ImageIcon(getClass().getResource("/com/common/images/red.bmp"))
Use YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"), read the stream to a byte[] and construct the ImageIcon based on that. (and don't use bmps - prefer png or jpeg)
Applets and Images that is a frequently asked questions so, as for Java applets and images, I recommend you read one of my previous answers hope it helps a bit :)
Good luck

Categories