I imported an image into Eclipse, in the same package as this class:
public class mainWindow extends JFrame {
public mainWindow() {
Image bg = // \mainPackage\ShittyPlane.png;
Graphics2D g2d;
this.setSize(500,500);
this.setResizable(false);
this.setTitle("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
g2d.drawImage(bg, 0, 0, null);
}
}
How do I define the image path?
If the image is part of you source and is packed into jar later for distribution i would sucgest you get a stream to the image using getResourceAsStream.
ClassLoader cl = getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("mainPackage/ShittyPlane.png");
BufferedImage image = ImageIO.read(is);
this aproache will also work in if you run the program from your IDE
If you plan to locate the image using a a File chooser then go with #Pescis's answer.
What you need to do to load an image from a specific file is:
BufferedImage img = null;
try {
img = ImageIO.read(new File("src/mainPackage/ShittyPlane.png")); //I'm guessing this is the path to your image..
} catch (IOException e) {
}
For more info you can read the javadoc on working with images.
Related
I'm trying to export a JAR file from my project and I need some of my BufferedImages to get loaded in it.
Structure is this:
-src
-img
-models
-views
...
and knowing that all my image files are stored into the img package. I'm trying to do this in a JPanel from other project:
public class BelowPanel extends JPanel {
private BufferedImage img;
public BelowPanel() {
initImage();
setOpaque(false);
}
private void initImage() {
try {
img = ImageIO.read(getClass().getResourceAsStream(("/img/titan.png")));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(img, 0, 0,this.getWidth(),this.getHeight(), this);
}
}
When I run this it shows the image, but once I generate the JAR file in my desktop, it doesn't even run.
My images of Image type, doesn't have any problem, but BufferedImages doesn't load.
So... Do you know a way to load my "titanImage", so I can generate a running JAR file which can work correctly?
I use eclipse on linux Ubuntu and I have this code for loading image and setting it as background in one of my JPanels:
public class MenuState extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private GameStateManager gsm;
private int width;
private int height;
public MenuState(GameStateManager gsm)
{
this.gsm = gsm;
width = gsm.getWidth();
height = gsm.getHeight();
SizeManager sm = new SizeManager();
this.setLayout(new BorderLayout());
sm.set_size(this, width, height);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
BufferedImage background_image;
try {
background_image = ImageIO.read(new File("src/res/img/menu_background.png"));
g.drawImage(background_image, 0, 0, width, height, null);
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
}
and it works only in eclipse. When I export it to jar file or runnable jar file program does not show images. I also tried to use
this.getClass().getResource()
and similar codes but it does not work in eclipse. But I am maybe doing something wrong.
I also have this code in another class to play audio:
public class AudioManager {
private Clip clip;
public void play(String audio_name, boolean repeat)
{
try {
File audioFile = new File(audio_name);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(audioStream);
if(repeat)
{
clip.loop(clip.LOOP_CONTINUOUSLY);
}
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop()
{
clip.stop();
}
and it plays audio in eclipse but not after I export project.
I suppose File works only for files on disk and not for files in jar file but it is only way I made it works in eclipse.
So, what should I do?
And additional problem:
Sound played in eclipse is lagging, I improved it increasing available memory for eclipse but little lags occur when loading program and changing JPanels in JFrame by clicking on JButtons.
Thanks for any advice.
What String do you put into the getResource method ?
When you use getResource or getResourceAsStream, you must specify the package path. If your file is in the package "com.test.example", then you must put getResource("/com/test/example/my_file.png").
So, with your background image, you must load your image with :
background_image = ImageIO.read(this.getClass().getResource("/res/img/menu_background.png"));
You should do the same way with your audio file.
I also recommend you to load your image outside of the paintComponent method. Otherwise, each time your panel is repainted, the image is reloaded.
Apparently, this is my code I have been using to get image from my disks to my program.
public void getVehicleImage(){
FileDialog fd = new FileDialog(this);
fd.setFile("*.jpg; *.jpg; *.png; *.gif");
fd.show();
vehicle_path = fd.getDirectory()+fd.getFile();
vehicleFileName.setText(vehicle_path = fd.getFile());
vehicleImagePath.setText(vehicle_path = fd.getDirectory()+fd.getFile());
image.setIcon(new ImageIcon(vehicle_path));
}
How do I fit the image to the size of my jLabel? I have tried using the
getScaledInstance()
but still no good. And also I want to ask if I am using the right code on how to get Image from my disk? I kinda feel it is wrong.
I faced similar problem and did below workaround:
Step1: Read the picture as a BufferedImage from your file system.
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Step2: Create a new BufferedImage that is the size of the JLabel
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
Step3: Create new ImageIcon from the resized BufferedImage (Step 2)
ImageIcon imageIcon = new ImageIcon(img);
In your case, create a helper method and call it while creating ImageIcon as below:
public void getVehicleImage(){
...................
image.setIcon(new ImageIcon(getScaledImage(vehicle_path)));//call helper here
}
This can be helper function:
public BufferedImage getScaledImage(String imagePath){
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
return img;
}
I've got a simple swing application with a JFrame that holds various components. On the JFrame I have a custom toolbar class that extends JPanel. On the JPanel I plan on adding buttons with image icons. My directory structure is as follows:
Project/src/gui (Package holds source files for application)
Project/src/images (Package holds a jar file jlfgr-1_0.jar with button icons and /or individual images files)
The issue is that I want to avoid copying the individual image files to the images package. I'd rather somewhow just load the images directly from the jar file. I've got private method that returns the appropriate icon. This method works, for example if I drag an image file to the images package and call:
button.setIcon(createIcon("/images/Save16.gif"));
private ImageIcon createIcon(String path) {
URL url = getClass().getResource(path);
ImageIcon icon = new ImageIcon(url);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
return icon;
I know this is basic, but how can I get my images directly from the jar file in my current setup?
Thanks.
You can read the image from the stream, thanks to javax.imageio.ImageIO:
private ImageIcon createIcon(String path) {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
ImageIcon icon = new ImageIcon(image);
return icon;
}
This is another way. The images are at location src/images
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(this.getClass().getResource("images/Picture2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
try {
myPicture = ImageIO.read(this.getClass().getResource("images/broken_image.jpg"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
panel.add(picLabel);
I have a form in which i want to capture the image of the person and display that image in the form.
How can i connect to the webcam through java and display that image in the form?
You could use JavaCV to capture the image.
This code should get you started (taken from here):
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.VideoInputFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class GrabberShow implements Runnable {
//final int INTERVAL=1000;///you may use interval
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public GrabberShow() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
#Override
public void run() {
FrameGrabber grabber = new VideoInputFrameGrabber(0);
int i=0;
try {
grabber.start();
IplImage img;
while (true) {
img = grabber.grab();
if (img != null) {
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++)+"-capture.jpg", img);
// show image on window
canvas.showImage(img);
}
//Thread.sleep(INTERVAL);
}
} catch (Exception e) {
}
}
}
Another alternative would be to use the Java Media Framework (JMF). You can find an example here.
You can use Webcam Capture project to do that. It's working on Windows XP, Vista, 7, Linux, Mac OS, Raspberry Pi and more. There is a ready-to-use Swing component extending JPanel which can be used to display image from your webcam. Please found this example for more details of how this can be done - it presents some advanced capabilities of this component, but basic usage would be the following:
JFrame window = new JFrame("Test webcam panel");
window.add(new WebcamPanel(Webcam.getDefault()));
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
After you run this code you should see JFrame with image from your webcam inside.
Webcam.setAutoOpenMode(true);
BufferedImage image = Webcam.getDefault().getImage();
ImageIO.write(image, "PNG", new File("F:/test.png"));
can download the latest version from https://github.com/sarxos/webcam-capture
and add other library file that in the zip file