Display and writing of image in java - java

I am unable to display the image as there's problem in the main method and i am not sure whether did i write the image correctly. Sorry, I am really new to Java.
public class Display extends JPanel
{
String path = "C:/Users/asus/workspace/Code/src/7horses.jpg";
File file = new File(path);
static BufferedImage img;
img = ImageIO.read(new File(file));
public static BufferedImage CopyImage (File file)
{
BufferedImage cImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = cImg.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
File saveImage = new File("C:/Users/asus/workspace/Code/src", saveAs);
ImageIO.write(cImg, "png", saveImage);
return cImg;
}
public static void main(String[] args)
{
JFrame f = new JFrame("Show Image");
LoadImage panel = new BufferedImage CopyImage(file);//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
After duplicate the image, i am not sure how to display the duplicate copy. Below was the code which i initially use for loading and displaying.
public class LoadImage extends JPanel
{
BufferedImage img;
String path = "C:/Users/asus/workspace/MP/src/7horses.jpg";
File file = new File(path);
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, null);
}
public LoadImage()
{
try
{
img = ImageIO.read(file);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
JFrame f = new JFrame("Show Image");
LoadImage panel = new LoadImage();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}

There's a few things wrong with this code..
path and file cannot be accessed by main() because they are not static and main is. Meaning when main() is ran, neither of path or file exist.
LoadImage panel = new BufferedImage CopyImage(file) is not valid Java - I'm not sure what you were trying to do but I guess you want to remove the new BufferedImage part
img = ImageIO.read(new File(file)); - you can't run this statement outside a method or static block as it requires handling of an IOException
ImageIO.read(new File(file)); - file is already of type File and you are passing it to a type File, not necessary. ImageIO.read(file); would do
saveAs hasn't been defined anywhere.
ImageIO.write(cImg, "png", saveImage); can throw an IOException so you need to add a try-catch around it like in the LoadImage() constructor or append throws IOException to your method signature like so public static BufferedImage CopyImage (File file) throws IOException
You are referencing LoadImage which looks like it's trying to do exactly what Display does in a slightly different way. I'm not sure what to advise here because I don't understand the intention but I think perhaps replace LoadImage in the Display code with Display

Maybe:
Use ImageIO to retrieve a BufferedImage from your file.
Using an ImagePanel that can use a Buffered Image to display on
your JFrame
It would be something more like that:
public class Display extends JPanel {
private static final long serialVersionUID = 1L;
private static final String path = "C:/Users/asus/workspace/Code/src/7horses.jpg";
private static final File file = new File(path);
public static void main(String[] args) throws IOException {
JFrame f = new JFrame("Show Image");
BufferedImage image = ImageIO.read(file);
ImagePanel panel = new ImagePanel(image);//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setLocation(200, 200);
f.setVisible(true);
}
public static class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
}

What is a LoadImage? Unless it's both a BufferedImage AND a Container your code won't even compile.
And as a class can't be both a Container and a BufferedImage at the same time (given that both are classes, not interfaces, and multiple inheritance at class level doesn't exist in Java) your code can't work.
You're going to have to figure out how to correctly initialise your LoadImage instance, and only the documentation (and possibly source) of that class is going to help you.

Related

How to load an image into a JPanel using Java

I would like to use an image as the background of a JPanel.
It needs to be loaded from a relative file path.
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
this.add(background);
} catch(IOException e) {
System.out.println(e.toString());
}
}
My current code is not working. Any help would be appreciated.
So can't comment(need 50 rep) but your file path is completely wrong
you need it to be something like this
new File("C:/Users/"Insert Username"/Desktop/workspace/Java/BSC_Project/Application/src/resources/background.jpg")
except I'm not on your computer so you need to figure out your own file path, This would be assuming your workspace folder is on your Desktop which it almost certainly isn't, do you understand?
Well if you want your code to have a panel this is what you would do...
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JPanel panel = new JPanel();
JLabel background = new JLabel(new ImageIcon(backgroundImage));
panel.add(background);
this.add(panel);
} catch(IOException e) {
System.out.println(e.toString());
}
}
but in your case it looks to me like you want a frame background as image... to which you can set the image background to which for that one you can try this code
JFrame f = new JFrame ("SettingBackGround");
try{
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Med.jpg")))));
}catch (IOException e){
System.out.println("Image Doesnt Exist");
}
f.setVisible(true);
f.setResizable(false);
f.pack();
}
}
I hope this helps though.
public WelcomeView() {
initComponents();
try {
image = ImageIO.read(new File("C:\\Users\\Developer\\workspace\\Java\\BSC_Project\\Application\\src\\application\\resources\\background.png"));
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
private BufferedImage image;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 2, 0, null); // see javadoc for more info on the parameters
}

Image in not repainting from List<path>

i am trying to load image from specified path, and list of files are stored inside List<>.
at first time when i initialize image it display but when i am trying to display next image from List instance which contain list of files, it doesn't repaint the image.
what's wrong going is i am initializing image in constructor first time that overwrite
the new image, now where to initialize image first time outside constructor i don't know.
my code :
public void nextImage(int cnt)
{
System.out.println(cnt);
if (cnt < imageFiles.size())
{
System.out.println(imageFiles.size());
try
{
bg = ImageIO.read(new File((imageFiles.get(cnt)).toString()));
scaled = getScaledInstanceToFit(bg, new Dimension(600, 600));
setBackground(Color.BLACK);
}
catch(Exception e)
{
e.printStackTrace();
}
}
MouseHandler handler = new MouseHandler();
addMouseListener(handler);
addMouseMotionListener(handler);
System.out.println(cnt);
System.out.println(imageFiles.get(cnt).toString());
}
menu item click code :
JMenuItem mntmRestoreImage = new JMenuItem("Next Image");
final ImagePane st = new ImagePane();
mntmRestoreImage.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
st.nextImage(k);
k++;
}
});
mnEdit.add(mntmRestoreImage);
class code & constructor :
private BufferedImage bg;
private BufferedImage scaled;
java.util.List<Path> imageFiles= getFilesFromDirectory(FileSystems.getDefault().getPath("D:\\New folder"));
public ImagePane()
{
try
{
bg = ImageIO.read(getClass().getResource("/images/src11.jpg"));
scaled = getScaledInstanceToFit(bg, new Dimension(600, 600));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
counter also increments, now the code inside ImagePane() constructor
overwrites the image of nextImage() function, so idea what happen out
in this code ??
any suggestion ?
I think I have the perfect solution for you! I wrote a little program for you so it is easier to understand.
First I have a method for you to check if the file is a picture:
public Stack<File> getFilesInFolder(String startPath) {
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles()) {
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0) {
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes) {
if (extension.equals(filetype)) {
picturestack.add(file);
}
}
}
}
return picturestack;
}
Very easy! Take the folder and iterate his files. Take the extension of the file and check if it is a valid file type. Define the file types in a array at the begining of your code.
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
At the end I push every file into a stack. Remember to fill the stack into a variable, do not read the files more than once because than you get the same problem as before:
Stack<File> pictures = getFilesInFolder("C:\\Users\\Admin\\Desktop");
After that use a Action for your JMenuItem! In my example I do not have much, you have to put your methods in!
Action nextpictureaction = new AbstractAction("Next Picture") {
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e) {
if (!pictures.isEmpty()) {
System.out.println(pictures.pop().getName());
}
}
};
Add the Action at your JMenu and set the properties of your Frame.
/*
* Add Components to Frame
*/
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
/*
* Frame Properties
*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
At the end execute your program with the invokeLater method!
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PictureEditor();
}
});
}
Summary
Basically you need a somthing to iterate through because values like integer are not saved the way you like. In my example I used a Stack and save at the beginning all pictures in it. Important is that, if you used or finished with the picture, you have to remove it (use stack.pop() for a Stack). I do not found a method where you check if the file is a picture (if it is the ImageIO catch it is bad). I wrote a method for that if you want you could use it.
This is not an answer, but I cannot paste that much code into a comment.
I would change your code to something along the lines of this piece of code. This seperates the image loading from the gui updating logic (like adding mousehandlers and the like, I pasted only image loading code).
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import javax.imageio.ImageIO;
public class ImageLoader
{
public static class ImageContainer
{
BufferedImage bg = null;
BufferedImage scaled;
}
Iterator<File> imageFiles = Arrays.asList(
new File("D:\\New folder").listFiles()).iterator();
public ImageContainer nextImage(Dimension dimensionToFit) throws Exception
{
ImageContainer c = new ImageContainer();
if (imageFiles.hasNext())
{
File file = imageFiles.next();
//you might not need this, if only images are in this directory
if(file.isDirectory())
return null;
c.bg = ImageIO.read(file);
c.scaled = getScaledInstanceToFit(c.bg, dimensionToFit);
return c;
}
else
return null;
}
private BufferedImage getScaledInstanceToFit(BufferedImage bg,
Dimension dimensionToFit)
{
//do the risizing
}
}
This is not yet optimized though.

Painting an Image object on a BufferedImage for later use

I need some help with painting an Image object upon/inside/on a BufferedImage and then painting that BufferedImage on a JPanel.
I've prepared a small program to illustrate my problem. Just a frame with a panel accompanied by an ImageLoader.
The image is placed in the same folder as the code. The sten Image is painted successfully when just painted, but not when I try painting it with the BufferedImage, which you'll notice if you try to run the program. just create the Test object and the constructor does the rest.
Thanks in advance!
My code:
public class Test extends JFrame{
static class ImageLoader {
public static Image loadImage(String name){
Image img = null;
img = Toolkit.getDefaultToolkit().getImage(ImageLoader.class.getResource(name));
return img;
}
}
class Panel extends JPanel{
Image sten;
BufferedImage bf = new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);
public Panel(Image sten){
super();
this.sten = sten;
initBF();
}
private void initBF(){
Graphics2D g = (Graphics2D) bf.createGraphics();
g.drawImage(sten, 0,0,this);
}
public void paintComponent (Graphics g)
{
g.drawImage(bf, 100,100,null);
g.drawImage(sten, 0,0,null);
repaint();
}
}
public Test(){
setSize(new Dimension(500, 500));
setEnabled(true);
this.setBounds(50, 150, 500, 500);
setVisible(true);
Image sten = ImageLoader.loadImage("sten.png");;
Panel panel = new Panel(sten);
panel.setBackground(Color.GREEN);
panel.setSize(500, 500);
this.add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.paintComponent(this.getGraphics());
}
}
The problem is that Toolkit.getDefaultToolkit().getImage loads images asychronously so will not be loaded when paintComponent is invoked. Use a MediaTracker to block until the image has been loaded:
public Image loadImage(String name) {
Image img = null;
MediaTracker tracker = new MediaTracker(myPanel); // pass the panel from ctor
img = Toolkit.getDefaultToolkit().getImage(ImageLoader.class.getResource(name));
tracker.addImage(img, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
return img;
}
or far simpler:
img = ImageIO.read(ImageLoader.class.getResource(name)));
This will eliminate the need to use MediaTracker.
Some notes:
Don't call paintComponent directly, request repaints by invoking repaint.
Don't use getGraphics for custom painting - this uses a transient Graphics reference.
When using a custom Graphics reference, make sure to call Graphics#dispose when finished using the reference.
In addition of Reimeus' aswer, notice that Toolkit.getDefaultToolkit().getImage() is non-blocking, it loads images asynchronously, so at the point when you call g.drawImage(sten, 0,0,this); sten will probably not still actually be loaded (see the doc of the method). See also this (false) bug report.

Display image on applet

I am using Jtree for listing various images of a directory, I want to display image on applet when the user click on the image name displayed in the Tree, the code i'm using is as below, ta is an object of the applet because i'm using it in another class.
private void displayImage(URL furl, String fname) {
ta.Picture = ta.getImage(furl, fname);
prepareImage(ta.Picture, this);
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
System.out.println("slecte asldf " + node.isLeaf());
if (node.isLeaf())
{
currentFile = node.file;
System.out.println("File name " + currentFile.getName());
try
{
URL furl = new URL("file:/F:/photos");
displayImage(furl, currentFile.getName());
}
catch (MalformedURLException mle)
{
System.out.println("Exception::::::" + mle);
}
}
else
currentFile = null;
}
But its not working.
As you are showing files from the local filesystem, working with URLs is not required. Use
displayImage(currentFile);
and rewrite that method as following:
private void displayImage(File file) {
BufferedImage image = ImageIO.read(file);
ta.image = image;
ta.repaint();
}
where the paint method of the (I an assuming) component ta must be like
BufferedImage image;
public void paint(Graphics g) {
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
}
Because of security reasons, the applet will only be able to access the file system if signed or running without security manager (most often on the same computer).
But its not working.
This is in no way helpful, do you get exceptions? What happens? Please post an SSCCE for better help sooner
I want to display image on applet when the user click on the image
name displayed in the Tree, the code i'm using is as below, ta is an
object of the applet because i'm using it in another class.
IMO you are going about it wrong using the JPanel object and Component#getGraphics.
Dont use Component#getGraphics() as its not good practice and not persistent thus on next call to repaint() the screen will be cleared.
Dont use Applet with Swing components rather use JApplet.
Add a custom JPanel with getters and setters for BufferedImage variable to the container and than override paintComponnet and draw the BufferedImage there.
Now to change the BufferedImage simply call the setter i.e setBackgroundImage(BufferedImage img) and than call repaint() on JPanel to show the changes. Like so:
public class MyPanel extends JPanel {
private BufferedImage bg;
public MyPanel(BufferedImage bi) {
bg=bi;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2d.drawImage(bg,0,0,this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
public BufferedImage setBackgroundImage(BufferedImage bi) {
bg=bi;
}
}
Now we use it like so:
MyPanel mp=new MyPanel(...);//create the panel with an image
...
add(mp);//add to container
...
mp.setBackgroundImage(..);//change the image being displayed
mp.repaint();//so the new image may be painted

Adding image to JPanel through ImageIO.read?

I'm trying to add a JPanel with a picture in it. I'm using ImageIO.read to get the path but i get an IOException saying : can't read input file
The picture is called TCHLogo. It's a PNG inside a 'res' folder inside my project.
If there is any better way of displaying this image please also mention it!
Here is the code for my JPanel:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
//THIS LINE BELLOW WAS ADDED
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
} catch (IOException ex) {
// handle exception...
System.out.println(ex);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //THIS LINE WAS ADDED
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
Here is how i add the JPanel in my Applet:
ImagePanel appletRunningPanel;
appletRunningPanel = new ImagePanel();
appletRunningPanel.setSize(300, 300);
appletRunningPanel.validate();
add(appletRunningPanel);
EDIT
I created a folder inside the bin which the application starts to look in currently..
the folder is called res and the picture is inside..
Now i get the following IOException when i run the line:
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
Here is the error log:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1338)
at surprice.applet.ImagePanel.<init>(ImagePanel.java:17)
at surprice.applet.MainClass.init(MainClass.java:41)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
Likely your image's file path isn't correct relative to the user directory. To find out where Java is starting to look, where the user directory is, place something like this line of code somewhere in your program:
System.out.println(System.getProperty("user.dir"));
Perhaps you'd be better off getting the image as an InputStream obtained from a resource and not as a file. e.g.,
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
This will look for the image at the path given relative to the location of the class files, and in fact this is what you must do if your image is located in your jar file.
Edit 2
As an aside, often you need to first call the super's paintComponent method before doing any of your own drawing so as to allow necessary house-keeping can be done, such as getting rid of "dirty" image bits. e.g., change this:
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
to this:
public void paintComponent(Graphics g) {
super.paintComponent(g); // **** added****
g.drawImage(image, 0, 0, null);
}
I've written this ImagePanel class that i use for this scope :
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 7952119619331504986L;
private BufferedImage image;
public ImagePanel() { }
public ImagePanel(String resName) throws IOException {
loadFromResource(resName);
}
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* Load the Image from a File
* #param path image name and path
* #throws IOException
*/
public void loadFromFile(String path) throws IOException {
image = ImageIO.read(new java.io.File(path));
}
/**
* Load Image from resource item
* #param resName name of the resource (e.g. : image.png)
* #throws IOException
*/
public void loadFromResource(String resName) throws IOException {
URL url = this.getClass().getResource(resName);
BufferedImage img = ImageIO.read(url);
image = img;
}
}
Then i use the ImagePanel in this way :
//Inizialization of the ImagePanel
ImagePanel panelImage = new ImagePanel();
//Try loading image into the image panel
try {
panelImage.loadFromResource("/Resources/someimage.png");
} catch (java.io.IOException e) {
//Handling Exception
}

Categories

Resources