Cant Load Image on Java (BlueJ) - java

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 :)

Related

"Bad src image pointers" error after calling setFrameNumber() on FFmpegFrameGrabber in JavaCV

I am in the process of creating a small video editor and currently trying to get video files to display in the preview window. To do that, I want to get a frame of a video at a specific position using JavaCVs FFmpegFrameGrabber.
I have figured out a way of doing this, by setting the frameNumber variable of the grabber to the needed frame. However, this results in only the first frame of the file being displayed and some information about the file being printed out repeatedly (tell me if you need to see it, it's just kind of long and messy) alongside the error:
[swscaler # 000001927a7d3000] bad src image pointers
This is my frame grabbing class:
public class Video {
private FFmpegFrameGrabber grabber;
private final static Java2DFrameConverter converter = new Java2DFrameConverter();
public Video(File file) {
this.grabber = new FFmpegFrameGrabber(file);
try {
this.grabber.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public BufferedImage grabFrame(int framePos) throws Exception {
BufferedImage frame;
grabber.grabImage(); // Without this done before, the image is just black
grabber.setFrameNumber(framePos);
frame = converter.convert(grabber.grabImage());
return frame;
}
}
I am very thankful for your answers!

Class path resource for JLabel ImageIcon

I want to add a image in JLabel that can display after building the project too in eclipse.
I have this code..
jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));
Goodness, why are you trying to read an image file in one line?
First, make sure that your resources folder is defined for your project and is on the build path.
Here's an example from one of my Java projects.
Next, code a method to read image files from the resources folder.
private Image getImage(String filename) {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/" + filename));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Read the image file once, saving the result in a class variable ImageIcon.
imageIcon = new ImageIcon(getImage("image.png"));
Finally, reference the ImageIcon in your Swing code.
jLabel1.setIcon(imageIcon);

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.

How to load Images from a package in 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" );

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