Can't open an image file when using an ImageIO class - java

I've written a program that has to open an image I've placed on the desktop. The problem is that the program runs but nothing happens in the console nor does it open the image. Do I've to implement a GUI to fix the problem or...?
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Image {
public JavaImage() {
try {
BufferedImage image = ImageIO.read(new File("C:/Users/Username/Desktop/index.jpg"));
}
catch (IOException e) {
System.out.println("There isn't a picture in the folder");
}
}
public static void main(String[] args) {
new Image();
}
}

Related

Playing sound in Java using java.applet class

I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}

Complete JFXPanel to image

I want to take a snapshot of a website without any video, so it's just plain text with some css and pictures.
I am using a WebView (which is the scene of the JFXPanel) to load the website and then save it via
WritableImage image = scene.snapshot(new WritableImage(1920, 1080));
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bufferedImage, "png", file);
(where "scene" is the scene of the JFXPanel)
but the saved image just displays a part of the website, instead of the complete content (see picture).
How do I ensure/enforce that the dimensions of the image matches the dimensions of the JFXPanel content and everthing is visible?
Complete Code:
package renderer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.WritableImage;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class HtmlRenderer extends Application {
private JFXPanel jfxPanel;
private WebView webView;
public void start(Stage stage) {
jfxPanel = new JFXPanel();
webView = new WebView();
webView.getEngine().getLoadWorker().stateProperty().addListener(
new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SUCCEEDED) {
HtmlRenderer.this.toImage(jfxPanel.getScene());
try {
Platform.exit();
HtmlRenderer.this.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
jfxPanel.setScene(new Scene(webView));
this.updateView("http://www.stackoverflow.com/");
}
private void toImage(Scene scene) {
WritableImage image = scene.snapshot(new WritableImage(1920, 1080));
// TODO: save in matching dir using proper filename
File file = new File("D:/workspace/SiteChecker/test.png");
try {
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bufferedImage, "png", file);
} catch (IOException e) {
// TODO: exception handling
}
}
public void updateView(String url) {
webView.getEngine().load(url);
}
private void reloadView() {
webView.getEngine().reload();
}
}
So I found a solution, but it's far from perfect and not really perfomant.
However, nothing else works for me.
The trick is to load the website once, determine width and height of the site. The second time I set the preferred size of the Webview to the determined values and load the website again with the new size. I think it's because the first time only the visible part is rendered.
The width and height can be determined with javascript, e.g.:
private int getPageWidth(WebView webView) {
String script = "Math.max(" +
"document.body.scrollWidth, document.body.offsetWidth," +
"document.documentElement.clientWidth, document.documentElement.scrollWidth," +
"document.documentElement.offsetWidth );";
WebEngine engine = webView.getEngine();
int maxWidth = (int) engine.executeScript(script);
return maxWidth;
}
For some reason some websites have a funny end/bottom i.e. there is a lot of empty space.

send screenshots over network

I am trying to send continuous screenshots to another PC on same network.
I googled it also but i didn't find things relevant to me.
Below is my code of sender and receiver. Problem is only first image is being received and then struck.
If i turn on JFrame then not a single image is updating in JPanel. Please help me :-(
imagesender.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
class imagesender
{
imagesender()throws Exception
{
Socket soc=new Socket("127.0.0.1",5555);
OutputStream os=soc.getOutputStream();
while(true)
{
try
{
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rec=new Rectangle(dim);
Robot bot=new Robot();
BufferedImage image=bot.createScreenCapture(rec);
ImageIO.write(image,"jpeg",os);
System.out.println("Image Sent");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagesender();
}
}
imagereciever.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
class imagereciever extends JPanel
{
static BufferedImage image;
imagereciever()throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket soc=ss.accept();
JFrame frame=new JFrame();
frame.setSize(500,500);
frame.setContentPane(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
InputStream is=soc.getInputStream();
while(true)
{
try
{
image=ImageIO.read(is);
//this.repaint();
ImageIO.write(image,"jpeg",new File("C:\\Users\\Arpit Jindal\\Desktop\\screenshot.jpeg"));
System.out.println("Image Recieved");
}
catch(Exception e)
{e.printStackTrace()}
}
}
public static void main(String aerg[])throws Exception
{
new imagereciever();
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image,0,0,null);
}
}
imagereciever.java recieves one image and then gives this error infinite times and imagesender.java keeps on sending images:-
java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
at imagereciever.<init>(imagereciever.java:26)
at imagereciever.main(imagereciever.java:37)
Your GUI completely ignores Swing threading rules, so I'm not surprised that it might be getting stuck. Suggestions:
Use a SwingWorker to do long-running background tasks such as reading in images. In your case, perhaps a SwingWorker<Void, BufferedImage> is what you want so that you can pass the BufferedImage to the GUI via the publish/process method pair. The Concurrency in Swing tutorial will tell you the details on how to use this tool.
Don't draw with the paint method.
Instead draw in the paintComponent method of a JPanel that is displayed in JFrame. Be sure to call the super's paintComponent method within your override.
Stop to consider -- do you really need images transmitted in this way as you're passing in a lot of information, perhaps more than is needed? Better would be to pass a data model over the socket and then recreate a view with the data, if possible.
Never blatantly ignore exceptions as your code is doing. At least catch the exception's stacktrace.
The example #MadProgrammer gave to me solved my problem. This is my new Code:-
imagesender.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
class imagesender
{
imagesender()throws Exception
{
Socket soc=new Socket("127.0.0.1",5555);
OutputStream os=soc.getOutputStream();
while(true)
{
try
{
BufferedImage image=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image,"png",baos);
baos.close();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(baos.size()+"");
os.write(baos.toByteArray());
//System.out.println("Image Sent");
}
catch(Exception e)
{
System.exit(1);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagesender();
}
}
imagereciever.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
class imagereciever extends JPanel
{
static BufferedImage image;
static Socket soc;
static InputStream is;
imagereciever()throws Exception
{
ServerSocket ss=new ServerSocket(5555);
soc=ss.accept();
is=soc.getInputStream();
JFrame frame=new JFrame();
frame.setSize(500,500);
frame.setContentPane(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
while(true)
{
try
{
ObjectInputStream ois=new ObjectInputStream(is);
int size=Integer.parseInt(ois.readObject().toString());
ByteArrayOutputStream baos=new ByteArrayOutputStream(size);
int sizeread=0,bytesin=0;
byte[] buffer=new byte[1024];
while(sizeread<size)
{
bytesin=is.read(buffer);
sizeread+=bytesin;
baos.write(buffer,0,bytesin);
}
baos.close();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
image=ImageIO.read(bais);
this.repaint();
}
catch(Exception e)
{
System.exit(1);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagereciever();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image,0,0,null);
}
}

How to display the information in a browser via Java Applet?

I want to display information about the musical composition in the browser via Java applet. I use the library beaglebuddy_mp3.jar for id3 tags. A folder with files looks like this:
applet
- index.html
- FirstApplet.class
- beaglebuddy_mp3.jar
In index.html I connect an applet:
<applet code="FirstApplet.class" archive="beaglebuddy_mp3.jar" width="500" height="500"></applet>
FirstApplet.class contains the following code:
import java.applet.Applet;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import com.beaglebuddy.mp3.MP3;
public class FirstApplet extends Applet{
public void paint(Graphics g){
try {
MP3 mp3 = new MP3("D:\\Music\\abc.mp3");
g.drawString(mp3.getBand() +" "+mp3.getTitle(), 20, 20);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After starting the index.html file dialog box appears with a warning stating that I run the application at your own risk. Then I click "Run", instantly appears and disappears gray square. On that nothing is displayed.
Try the following:
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import java.io.File;
import java.io.IOException;
import com.beaglebuddy.mp3.MP3;
public class FirstApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
MP3 mp3 = new MP3("D:\\Music\\abc.mp3");
JLabel label = new JLabel(mp3.getBand() +" "+mp3.getTitle());
add(label);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
And secondly you have to sign your applet code with an official certificate to be able to run it in your web browser.

Java does not load embedded Images

package common;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ResourcesToAccess {
public static Icon sharedAbstractDownIcon;
public static Icon sharedAbstractPlayIcon;
public static Icon sharedAbstractPauseIcon;
public static Icon sharedAbstractBlackCursor;
public static Icon sharedAbstractWhiteCursor;
public ResourcesToAccess(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/src/images/blackCursor.png");
try{
BufferedImage bi = ImageIO.read(is);
sharedAbstractBlackCursor = (Icon) new ImageIcon(bi);
new JFrame().add(new JLabel(sharedAbstractBlackCursor)).setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new ResourcesToAccess();
}
}
I am using this code to see whether the PNG images can be properly loaded to create JLabels, Icons, etc but I get the error that:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at common.ResourcesToAccess.<init>(ResourcesToAccess.java:21)
at common.ResourcesToAccess.main(ResourcesToAccess.java:29)
Why do I see that error message?
try with
this.getClass().getClassLoader().getResourceAsStream("images/blackCursor.png")
it is looking in your classpath so no more src directory there

Categories