How to load Images from a package in java - java

I usually use this to load from the same package
Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();
How can I load an image from a package specified for images?

You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
Use
ImageIcon icon=new ImageIcon(<any one from above>);
You can use BufferedImage also in place of ImageIcon directly.
For more information read it here How to retrieve image from project folder?

Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();
Suggests that "image.png" resides within the same package as the class represented by this
You can use absolute paths to reference resources that reside within different packages
String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
The important concept here is to understand that the path is suffixed to class path
Personally, you should be using ImageIO over ImageIcon, apart from supporting more formats, it throws an IOException when something goes wrong and is guaranteed to return a fully loaded image (when successful).
See How to read images for more details

You don't need to use(like "this") locally: this.getClass().getResource( img );
Just use class loader globally : ClassLoader.getSystemResource( path );
I'm gonna show you my library function below
public final class PackageResourceLoader {
// load image icon
public static final ImageIcon loadImageIcon( final String path ) {
final URL res = ClassLoader.getSystemResource( path );
return new ImageIcon( res );
}
// load buffered image
public static final BufferedImage loadBufferedImage( final String path ) {
final URL res = ClassLoader.getSystemResource( path );
try { return ImageIO.read( res ); }
catch( final Exception ex ) { return null; }
}
}
if your img.png is in package pack use PackageResourceLoader.loadImageIcon( "pack/img.png" );

Related

ImageIO.read unable to find .png-file

sorry if this has been asked quite a few times, I'm new here.
I've used three different approaches to get a file to be loaded and nothing worked:
Using Toolkit:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("apple.png"));
Using a File:
BufferedImage img = null;
try {
img = ImageIO.read(new File("apple.png"));
} catch(IOException e) {
e.printStackTrace();
}
Using a FileInputStream:
Path path=Paths.get(".").toAbsolutePath().normalize();
String dir=path.toFile().getAbsolutePath()+"\\resources\\apple.png";
BufferedImage image = null;
try {
image = ImageIO.read(new FileInputStream(dir));
} catch(IOException e) {
e.printStackTrace();
}
path and dir are working fine getting me an absolute path but I alway end up with image = null.
/edit:
#DuncG: I don't get an exception so there's no stacktrace to post, sorry. new File("apple.png").exists() evaluates to false.
#Harald_K: It is a normal .png image-file I have on my local system. It is located in src/main/resources/apple.png.
The issue is that your program is NOT able to find the required file and then further read it as an Image. This is a common recurring problem statement in any modern-day app where a required resource is NOT found, halting subsequent operations.
I would suggest writing a common piece of code to always locate such files/resources in your project dir just by giving the filename and returning the path.
#Slf4j
public class PathFinder {
private static Path filepath;
public static Path getFilePathForFile(String filename) {
log.info("Looking for filepath for given filename: ".concat(filename));
try {
filepath = Files.walk(Paths.get("."))
.collect(Collectors.toList()).stream()
.filter(file -> !Files.isDirectory(file) &&
file.getFileName().toString().startsWith(filename))
.findFirst().get();
} catch (IOException exception) {
log.error(exception.getMessage());
} return filepath;
}
}
Now you can easily use the above Pathfinder utility class to look for any given file and further operate on it as shown below:
BufferedImage img = ImageIO.read(PathFinder.getFilePathForFile("apple.png")
.toFile());

i am not able to get the images read in java for exporting it as JAR

This code throws a NullPointerException and I have no idea why.
try {
imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
backgroundImage = imageIcon.getImage();
signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
JOptionPane.showMessageDialog(null, "");
}
res/ is a source folder in the project root which contains all images used in this piece of code but I'm not able to get it to work. I've tried using getClass().getResource() (which works from inside Eclipse but not from a .jar file) and getClass().getResourceAsStream() (which throws an exception telling that the input stream is null) but to no avail.
P.S.: MyButton is a user-defined class which extends JButton and has a constructor MyButton(String, final BufferedImage, final BufferedImage).
After all I succeeded by just making images folder under my source(i.e. under res) folder. And using method
ImageIO.read(getClass().getResource("/images/SignIn.png"));

Scale image with Vaadin and Java

I have following code to upload an image and show it on the webpage
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
The problem is, it shows the full resolution and I want to scale (so it remains proportional) it down to 180px width. The picture also needs to be saved as the original filename_resized.jpg but I can't seem to get it to scale. Several guides on the web talk about resizing (but then the picture gets distorted) or it gives some issues with Vaadin.
Update:
Added the scarl jar (from this answer)) because it would be easy-peasy then by using following code:
BufferedImage scaledImage = Scalr.resize(image, 200);
but that gives following error:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
and I cannot cast because Cannot cast from Embedded to BufferedImage error
Update: with following code I can cast to the right type
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
but now I can't show the image..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
because of error The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)
You cannot use Vaadin objects directly with a third-party tool such as Scalr without adapting one to the other. "Embedded" is a Vaadin class whereas SclaR expects a "BufferedImage".
So, you first need to extract the File object from the Embedded object:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
Then, load it into the BufferedImage using ImageIO, such as explained in the link you pointed at ( What is the best way to scale images in Java? )
BufferedImage img = ImageIO.read(...); // load image
Then, you have the BufferedImage object you were looking for.

Cant Load Image on Java (BlueJ)

Im Trying to load my images on to Java but when running the code nothing appears inside my JFrame.
The way im doing it is calling my Image function from my main:
import java.awt.*; // Graphics stuff from the AWT library, here: Image
import java.io.File; // File I/O functionality (for loading an image)
import javax.swing.ImageIcon; // All images are used as "icons"
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
}
And then calling it here:
GI_Background = GameImage.loadImage("Images//background.jpg");
GI_DuskyDolphin = GameImage.loadImage("Images//DuskyDolphin.jpg");
If this is not enough information I'll gladly supply the rest of the code :)
Thanks
If the image is part of the application, do not use a File but use the java resource mechanism.
URL imageUrl = getClass().getResource("/Images/background.jpg");
return new ImageIcon(imageURL).getImage();
The resource URL will return null when not found.
If the application is packed in a .jar, you can open that with 7zip/WinZip or so, and check the path. It must be case-sensitive, and using / (not backslash).
I'm not quite sure what you try to achieve...
to load an image with a method, this will be enough:
private Image loadImage(String fileName){
return (new ImageIcon(fileName)).getImage();
}
Afterwards, i would create a JLabel with the Image as background;
ImageIcon image = getImage( filename );
JLabel imageLabel = new JLabel( image );
imageLabel.setSize( image.getIconHeight, image.getIconWidth );
JFrame frame = new JFrame();
frame.add( imageLabel );
Try this and feel free to aks again if i does not work for you, or thats not want you want :)

Loading Image in Java Applet

When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed

Categories