Java Image Sending Network - java

I am trying to send Image over the Network following Server code.
import java.net.*;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server {
static private BufferedImage bi;
static Socket socket;
static ServerSocket serverSocket;
DataInputStream dis=null;
public static void connect() throws IOException
{
serverSocket = new ServerSocket(9632);
System.out.println("i am server & listening...");
socket = serverSocket.accept();
System.out.println("Connected");
}
public static void main (String [] args ) throws IOException {
connect();
receiveimage();
showimage();
}
public static void receiveimage()
{
byte[] data;
while (true){
try{
System.out.println("Reading Image");
InputStream in=socket.getInputStream();
data=new byte[socket.getReceiveBufferSize()];
in.read(data, 0, socket.getReceiveBufferSize());
Image image = getPhoto(data);
bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
}
catch(Exception ex)
{
System.out.println("error: " + ex.toString());
}
}
}
public static void showimage() throws IOException
{
File file = new File("saved.png");
Image image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static Image getPhoto(byte[] bytePhoto) throws IOException {
return ImageIO.read(new ByteArrayInputStream(bytePhoto)); //bytePhoto is the byte array
}
}
and following Client code
import java.net.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class client{
public static byte[] bytePhoto;
public static Socket sock;
public static void connect() throws IOException
{
Socket sock = new Socket("172.16.0.143",9632);
System.out.println("Connected");
}
public static void main (String [] args ) throws IOException, ClassNotFoundException {
connect();
sendphoto();
}
public static void sendphoto() throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream("c:\\ziki.png"));
Image image = ImageIO.read(is);
byte[] data=setPhoto(image);
// OutputStream output = sock.getOutputStream();
//output.write(data);
}
public static byte[] setPhoto(Image img) throws IOException {
ImageIcon icon = new ImageIcon(img);
BufferedImage bImg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bImg.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
ByteArrayOutputStream writer = new ByteArrayOutputStream();
ImageIO.write(bImg, "jpg", writer);
return bytePhoto = writer.toByteArray(); //bytePhoto is a byte array
}
}
It is giving me Java Null pointer exception on Client side.

When I run this, I'm getting a NullPointerException on the server side. ImageIO.read in getPhoto is returning null, because I don't have an ImageReader registered that's capable of reading the stream.
Any ImageInputStreamSpis in your classpath are automatically registered, so I guess I don't have one. I don't know what's installed on your machine, but it's likely a similar problem.

Related

JAVA TCP Server Error

Server : package Server;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen(){
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true){
if((image = ImageIO.read(min)) != null){
while(min.read() != 'y');
System.out.println("received");
mout.write('y');
mout.flush();
Main.drawImage(image);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client :package Client;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] buffer = new byte[10];
while(true){
ImageIO.write(webcam.getImage(), "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This Program works well about 10sec. But after that It doesn't work. Socket is Connected but It doesn't send anything. I guess it doesn't match sync, so I match sync, but it's not work too. I don't have an idea. why It doesn't work. please help. I can't find problem
Your client needs to send the size of transfered image to server prior to sending the image itself, because your server needs to know how long the image is, in order to read it from socket and start receiving the char data coming right after the image.
And since "ImageIO" has no means of specifying the number of bytes supposed to be read from the input stream, you should use InputStream instead.
See the modified code below (I put comments whenever added a new line, everything else is identical with yours):
Server:
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; //<--- added
import java.io.DataInputStream; //<--- added
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
private DataInputStream din; //<--- added DataInputStream
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
din = new DataInputStream(min); //<--- initialized DataInputStream
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen()
{
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true)
{
int arrlen = din.readInt(); //<--- receive image size in order to prepare a buffer for it
byte[] b = new byte[arrlen]; //<--- prepare a buffer
din.readFully(b); //<--- receive image data
while(min.read() != 'y');
mout.write('y');
mout.flush();
InputStream bais = new ByteArrayInputStream(b); //<--- get ByteArrayInputStream from buffer
BufferedImage image = ImageIO.read(bais); //<--- prepare BufferedImage from ByteArrayInputStream
bais.close(); //<--- close ByteArrayInputStream
Main.drawImage(image);
}//end while true
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client:
import java.awt.image.BufferedImage; //<--- added
import java.io.ByteArrayOutputStream; //<--- added
import java.io.DataOutputStream; //<--- added
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
DataOutputStream dos = new DataOutputStream(out); //<--- added DataOutputStream
BufferedImage image = null; //<--- added BufferedImage to keep image from webcam
while(true){
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //<--- create ByteArrayOutputStream
image = webcam.getImage(); //<--- get BufferedImage from webcam
ImageIO.write(image, "png", baos); //<--- write image into ByteArrayOutputStream
dos.writeInt(baos.size()); //<--- send image size
dos.flush(); //<--- flush DataOutputStream
baos.close(); //<--- close ByteArrayOutputStream
ImageIO.write(image, "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Can't set ImageView photo from datainputstream JavaFx socket application

I am trying to output an image to an ImageView in javafx, i am recieving the image via socket connection and saving it to my hard-drive then i create an Image object with the path of the newly created image, the problem is that the image view is not updated.
public void save(String path, DataInputStream dis) throws IOException {
FileOutputStream fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
//Image imBuff = ImageIO.read(socket.getInputStream());
int filesize = dis.readInt(); // Send file size in separate msg
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("img"+frame_number+".jpg");
File f = new File("img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
}catch(Exception e){
System.out.println("didn't find");
}
System.out.println("stream size:"+image_Stream.size());
ps.println("ok");
frame_number++;
}
Things i have tried:
1- i tried to used the path i saved the photo in to create an Image then used the setImage() function on my ImageView (iv), i got Invalid Url even though i loaded an image image from the same directory before.
2- we tried using (file:///) to get an absolute path but it didn't work, also invalid url
3- i tried loading the image as a file first then using the toURI() function to get the proper path to it then create an image accordingly, i don't get an error but it also doesn't update the UI
P.S
this function is called in a sub Thread that updates an ImageView in the main javafx thread, i tried it with images not loaded through the socket connection and it worked, but when i try to display the images i receive the face this problem.
EDIT: I managed to load the image properly, now i can't update the ImageView using iv.setImage()
EDIT:
CameraOBJ class
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.util.Duration;
public class CameraOBJ implements Runnable{
String name;
int delay;
Socket socket;
String ip;
int port;
PrintStream ps;
Scanner sc;
static int frame_number;
StackPane sp;
Label delay_lbl;
ImageView iv;
public CameraOBJ (String name, String ip, int port){
this.ip = ip;
this.port = port;
this.name = name;
sp = new StackPane();
}
public void run() {
setStackPane();
connect();
while(true){
update();
}
// Timeline timeline = new Timeline();
// Duration duration = Duration.seconds(1/Settings.FPS);
// KeyFrame f1 = new KeyFrame(duration,e->{
// update();
// });
// timeline.getKeyFrames().add(f1);
// timeline.setCycleCount(Timeline.INDEFINITE);
// timeline.play();
}
private void update() {
// Platform.runLater(new Runnable() {
// public void run() {
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
if(dis!=null){
save("images",dis);
//setStackPane();
}
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
// }
// });
}
public void setStackPane(){
Platform.runLater(new Runnable() {
public void run() {
sp.setMinSize(500, 384);
sp.setMaxSize(500, 384);
sp.setStyle("-fx-background-color: #FFFFFF;");
Image image = new Image("Camera_Frame.jpg");
iv = new ImageView(image);
iv.setFitWidth(470);
iv.setPreserveRatio(true);
Label name_lbl = new Label(name);
delay_lbl = new Label(delay+"");
sp.setAlignment(iv,Pos.CENTER);
sp.setAlignment(name_lbl,Pos.TOP_LEFT);
sp.setAlignment(delay_lbl,Pos.BOTTOM_RIGHT);
sp.getChildren().addAll(iv,name_lbl,delay_lbl);
}
});
}
public void connect(){
try{
socket = new Socket(ip, port);
System.out.println(socket.isConnected());
ps = new PrintStream(socket.getOutputStream());
sc = new Scanner(socket.getInputStream());
}
catch (Exception c){
c.getMessage();
}
}
public void save(String path, DataInputStream dis) throws IOException {
Platform.runLater(new Runnable() {
public void run() {
FileOutputStream fos;
try {
fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
int filesize;
try {
filesize = dis.readInt();
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("file:img"+frame_number+".jpg");
File f = new File("C:\\Users\\ahmed\\workspace\\College\\RTS_Client\\src\\img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
delay_lbl.setText("frame_number: "+frame_number);
}catch(Exception e){
System.out.println("didn't find");
}
frame_number++;
}
});
}
}
Main class:
import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import com.sun.prism.paint.Color;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class main extends Application{
static Stage window;
static String default_ip = "192.168.43.200";
static int default_port = 1234;
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
window = stage;
window.setResizable(false);
window.setTitle("Control Room");
StackPane sp = new StackPane();
sp.setMinSize(500, 500);
Scene sc = new Scene(sp);
window.setScene(sc);
window.show();
CameraOBJ camera = new CameraOBJ("Camera 1", default_ip, default_port);
Thread t = new Thread(camera);
camera.run();
sc = new Scene(camera.sp);
window.setScene(sc);
}
}
Server class:
import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Camera implements Runnable {
long timeStamp;
int delayShift;
int FPS;
boolean idle;
//Control Rooms object here
int portNumber;
Socket csocket;
Camera() {
}
Camera(Socket csocket) {
this.csocket = csocket;
}
void startConnection() throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Camera(sock)).start();
}
}
public void run() {//Start Stream
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
Scanner inpstream = new Scanner(csocket.getInputStream());
// Receiving an integer that is sent from the client side.
int ID = inpstream.nextInt();
// Generating a reply based on the ID sent from the client.
String response = "";
if (ID == 1100) {
response = "Your name is Mahmoud. \n" + "You are 22 years old.";
} else {
response = "No data found matching the ID you entered.";
}
// Sending the reply through the OutputStream to the client.
pstream.println(response);
pstream.close();
terminateConnection();
} catch (InputMismatchException e) {
System.out.println(e.toString() + "\nNo data is received.");
} catch (IOException e) {
System.out.println(e.toString());
} catch (Exception c) {
System.out.println(c.toString());
}
}
void terminateConnection() throws IOException {
csocket.close();
}
public static void main(String[] args) throws Exception {
Camera cam = new Camera();
cam.startConnection();
}
}

Check if the port you want to connect to is in use

So I have a server-client program which makes a screen capture and shows it on your screen.
I want to verify in the main part if the port I want to connect to is in use or not and to print some relevant messages..
Server:
package test;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server extends Thread
{
private ServerSocket serverSocket;
Socket server;
public Server(int port) throws IOException, SQLException, ClassNotFoundException, Exception
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setVisible(true);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
// private static boolean isLocalPortInUse(int port) {
// try {
// // ServerSocket try to open a LOCAL port
// new ServerSocket(port).close();
// // local port can be opened, it's available
// return false;
// } catch(IOException e) {
// // local port cannot be opened, it's in use
// return true;
// }
// }
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception
{
int port = 9000;
Thread t = new Server(port);
t.start();
}
}
Client:
package test;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import javax.imageio.ImageIO;
public class Client
{
static BufferedImage img;
byte[] bytes;
public static void main(String [] args)
{
String serverName = "localhost";
int port = 10001;
try
{
Socket client = new Socket(serverName, port);
Robot bot;
bot = new Robot();//clasa Robot ajuta la creare capturii de ecran
img = bot.createScreenCapture(new Rectangle(0, 0, 500, 500));//scalarea imaginii; schimba dimensiunea screen shotului
ImageIO.write(img,"JPG",client.getOutputStream());
System.out.println("The image is on the screen!Yey!");
client.close();
} catch(IOException | AWTException e) {
e.printStackTrace();
}
}
}
If the client and server are on the same box, then you can use the strategy of binding to the existing port and checking for a specific exception.
public static void main(String...args) throws IOException {
int port = 31999; // for demonstration purposes only.
boolean serverRunning = isServerRunning(port);
System.out.printf("Server running: %s\n", serverRunning);
new ServerSocket(port); // start the server
serverRunning = isServerRunning(port);
System.out.printf("Server running: %s\n", serverRunning);
}
private static boolean isServerRunning(int port) throws IOException {
try(ServerSocket clientApp = new ServerSocket(port)) {
return false;
} catch (java.net.BindException e) {
return true;
}
}
If the server is on another box, which is most likely the case, then you can follow a similar strategy, instead looking for ConnectException
public static void main(String...args) throws IOException {
int port = 31999; // for demonstration purposes only.
boolean serverRunning = isServerRunning("localhost", port);
System.out.printf("Server running: %s\n", serverRunning);
new ServerSocket(port); // start the server
serverRunning = isServerRunning("localhost", port);
System.out.printf("Server running: %s\n", serverRunning);
}
private static boolean isServerRunning(String address, int port) throws IOException {
try(Socket clientApp = new Socket(address, port)) {
return true;
} catch (java.net.ConnectException e) {
return false;
}
}

dialog box is not showing system's items when i use applet in place of frame?

My code is:
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.*;
import java.io.*;
import java.util.zip.GZIPOutputStream;
import java.util.*;
import java.awt.Checkbox;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.CheckboxGroup;
import java.applet.*;
import javax.swing.JFileChooser;
/*
<applet code="compress1" width=200 height=200>
</applet>
*/
interface CompressionStrategy
{
public void compressFiles(FileOutputStream files,String str);
}
class ZipCompressionStrategy implements CompressionStrategy{
public void compressFiles(FileOutputStream files, String str)
{
byte[] buffer = new byte[1024];
try{
//using ZIP approach
ZipOutputStream zos = new ZipOutputStream(files);
ZipEntry ze= new ZipEntry(str);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(str);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done with Zip");
}
catch(IOException ex){
ex.printStackTrace();}
}
}
class GZipCompressionStrategy implements CompressionStrategy
{
public void compressFiles(FileOutputStream files, String str)
{
//using RAR approach
//FileOutputStream fos = null;
GZIPOutputStream gos = null;
FileInputStream fis = null;
try {
// fos = new FileOutputStream("e://myGzip.gzip");
gos = new GZIPOutputStream(files);
fis = new FileInputStream(str);
byte[] tmp = new byte[4*1024];
int size = 0;
while ((size = fis.read(tmp)) != -1) {
gos.write(tmp, 0, size); }
gos.finish();
System.out.println("Done with GZip...");
}
catch (IOException e) {}
finally{
try{
if(fis != null) fis.close();
if(gos != null) gos.close();
} catch(Exception ex){}
}
}
}
class CompressionContext
{
private CompressionStrategy strategy;
//this can be set at runtime by the application preferences
public void setCompressionStrategy(CompressionStrategy strategy)
{
this.strategy = strategy;
}
//use the strategy
public void createArchive(FileOutputStream files, String str)
{
strategy.compressFiles(files,str);
}
}
public class compress1 extends Applet implements ActionListener
{
int n;
Button b1;
Checkbox jcb1,jcb2;
CheckboxGroup cbg;
int r;
JFileChooser fs=new JFileChooser();
File file1;
static String filenm;
//TextField tf;
public void init()
{
//setTitle("compress");
Panel p1;
//setLayout(new FlowLayout());
p1=new Panel();
b1=new Button("compress");
cbg=new CheckboxGroup();
jcb1=new Checkbox("zip1",cbg,true);
jcb2=new Checkbox("gzip1",cbg,false);
//b1.setPreferredSize(new Dimension(100,100));
b1.addActionListener(this);
//tf=new TextField("",6);
p1.add(b1);
//p1.add(tf);
p1.add(jcb1);
p1.add(jcb2);
add(p1,BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==b1)
{
r=fs.showOpenDialog(null);
if(r==JFileChooser.APPROVE_OPTION)
{
file1=fs.getSelectedFile();
filenm=file1.getAbsolutePath();
}
if(jcb1.getLabel()=="zip1"){
n=1;
}
else if(jcb2.getLabel()=="gzip1"){
n=2;
}
else{}
compress1.x(n);
}
}
static void x(int n)
{
CompressionContext ctx = new CompressionContext();
switch(n)
{
//ctx.setCompressionStrategy(new ZipCompressionStrategy());
case 1:
ctx.setCompressionStrategy(new ZipCompressionStrategy());
//get a list of files
try{
FileOutputStream fos = new FileOutputStream("f:\\MyFile1.zip");
//String st="f:\\MyFile1.zip";
ctx.createArchive(fos,filenm);
}
catch(IOException ex){
ex.printStackTrace();}
break;
case 2:
ctx.setCompressionStrategy(new GZipCompressionStrategy());
//get a list of files
try{
FileOutputStream fos = new FileOutputStream("f:\\MyFile1.gzip");
//String st="f:\\MyFile.zip";
ctx.createArchive(fos,filenm);
}
catch(IOException ex){
ex.printStackTrace();}
break;
case 3:
System.exit(0);
}
}
}
this is code for compress to files. When i was using frame it's properly work but in place of frame when now i'm using applet then dialog box is not showing any path element, i don't know what's happen.

Is there a way to take a screenshot using Java and save it to some sort of image?

Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
Believe it or not, you can actually use java.awt.Robot to "create an image containing pixels read from the screen." You can then write that image to a file on disk.
I just tried it, and the whole thing ends up like:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
NOTE: This will only capture the primary monitor. See GraphicsConfiguration for multi-monitor support.
I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:
public static final void makeScreenshot(JFrame argFrame) {
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try {
// Create temp file
File temp = File.createTempFile("screenshot", ".png");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "png", temp);
// Delete temp file when program exits
temp.deleteOnExit();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
If you'd like to capture all monitors, you can use the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class HelloWorldFrame extends JFrame implements ActionListener {
JButton b;
public HelloWorldFrame() {
this.setVisible(true);
this.setLayout(null);
b = new JButton("Click Here");
b.setBounds(380, 290, 120, 60);
b.setBackground(Color.red);
b.setVisible(true);
b.addActionListener(this);
add(b);
setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b)
{
this.dispose();
try {
Thread.sleep(1000);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
Rectangle rec = new Rectangle(0, 0, d.width, d.height);
Robot ro = new Robot();
BufferedImage img = ro.createScreenCapture(rec);
File f = new File("myimage.jpg");//set appropriate path
ImageIO.write(img, "jpg", f);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
HelloWorldFrame obj = new HelloWorldFrame();
}
}
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
}
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );
bufferedImage will contain a full screenshot, this was tested with three monitors
You can use java.awt.Robot to achieve this task.
below is the code of server, which saves the captured screenshot as image in your Directory.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.
package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
#Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
Toolkit returns pixels based on PPI, as a result, a screenshot is not created for the entire screen when using PPI> 100% in Windows.
I propose to do this:
DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();
Rectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());
BufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);

Categories