Variable Not Changing in If Statement with Sarxos Motion Detection - java

I'm trying to have my program print a few "funny" images whenever it detects motion. Everything works by itself but when I put the if(detection == true) statement into the program, the variable doesn't update. How could I get it to update inside of the motionDetected function?
I've tried using boolean and int for the variable but I think it could be with the way I've structured it.
package printstuff;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.function.Function;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
/**
* Detect motion.
*
* #author Bartosz Firyn (SarXos)
*/
public class DetectMotion implements WebcamMotionListener {
public static boolean detection = false;
public DetectMotion() {
//creates a webcam motion detector
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms
detector.addMotionListener(this);
detector.start();
}
#Override
public void motionDetected(WebcamMotionEvent wme) {
//detects motion and should change the detection variable
System.out.println("Detected motion");
detection = true;
}
public static void main(String[] args) throws IOException, Exception {
new DetectMotion();
System.in.read(); // keep program open
final String[] catImages = new String[4];
//all the images
catImages[0] = "https://i.ytimg.com/vi/3v79CLLhoyE/maxresdefault.jpg";
catImages[1] = "https://i.imgur.com/RFS6RUv.jpg";
catImages[2] = "https://kiwifarms.net/attachments/dozgry5w4ae3cut-jpg.618924/";
catImages[3] = "https://www.foodiecrush.com/wp-content/uploads/2017/10/Instant-Pot-Macaroni-and-Cheese-foodiecrush.com-019.jpg";
//statement does not work..
if(detection == true)
{
for(int i=0; i<4; i++)
{
//saves the picture inside of the array to image.jpg
String imageUrl = catImages[i];
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
//sends print job to printer
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("image.jpg");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
java.util.concurrent.TimeUnit.SECONDS.sleep(15);
}
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
//converts url into image
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}

Related

Java task not updating jlabel

Question I have is I am trying to update my gui with a timer(this works and changes the image for mypic but, it will not update mytext label for some weird reason any help would be very much appreciated!
*I should add that mytext isn't showing up at all on my gui since introducing the timer...but mypic does????
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by xxxxxxzz on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = null;
JLabel mypic = null;
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
//Tried setting it like this and still doesn't work
// myText = new JLabel("HOT");
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
UPDATE with suggestions still isn't working..
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by jsnow on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = new JLabel();
JLabel mypic = new JLabel();
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
Here's a working solution which you can tailor to your use. The cause seemed to be the way you had tried to display the Components rather than the code in your action listener.
Your approach was just replacing myText with myPic when you initially set up the JFrame. Instead you need to use a layout manager. The example I've given is with overlaying using JLayeredPane. You may wish to use a layout manager instead if this is not the desired outcome, see the Oracle Tutorial on using layout managers.
Widget class
package widget;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Widget extends JFrame {
private static final int UPDATE_TICK = 5_000;
private static final int WIDGET_WIDTH = 150;
private static final int WIDGET_HEIGHT = 150;
private JLabel myText = new JLabel();
private JLabel myPic = new JLabel();
private Weather weather = new Weather();
private Timer simpleTimer;
public void createAndShow() {
setUndecorated(true);
setSize(WIDGET_WIDTH, WIDGET_HEIGHT);
Shape shape = new Ellipse2D.Float(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
// AWTUtilities.setWindowShape(this, shape);
setShape(shape); // do this instead
myText.setHorizontalAlignment(JLabel.CENTER);
myPic.setHorizontalAlignment(JLabel.CENTER);
JLayeredPane layered = new JLayeredPane();
myText.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
myPic.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
layered.add(myPic, 1, 0);
layered.add(myText, 2, 0);
add(layered);
simpleTimer = new Timer(UPDATE_TICK, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
update();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
simpleTimer.start();
}
private void update() {
myText.setText(weather.getTemp());
myPic.setIcon(new ImageIcon(weather.getImage(WIDGET_WIDTH, WIDGET_HEIGHT)));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Widget w = new Widget();
w.createAndShow();;
}
});
}
}
Weather class for demonstration purposes
package widget;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Weather {
private static final Random rand = new Random();
private static final Color[] randColors = {Color.YELLOW,
Color.GREEN,
Color.WHITE};
public String getTemp() {
return Integer.toString(rand.nextInt(100));
}
public BufferedImage getImage(int width, int height) {
int colorIndex = rand.nextInt(randColors.length);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.setRGB(x, y, randColors[colorIndex].getRGB());
}
}
return img;
}
}

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();
}
}

Buffered image is null

I am trying to send frames to java app from python app. Firstly I create a blank image on python side with numpy array and then wanna send it to java app and display it on the java side. But the bufferedimage on java side is null here is python code;
import socket
import sys
import cv2
import numpy as np
import base64
import json
from lib2to3.pytree import Leaf
from lib2to3.fixer_util import String
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "localhost"
PORT = 5555
try:
socket.connect((HOST, PORT))
except:
print "We cannot find the server !!!!"
print "Terminating the program . . ."
#exit(0)
img = np.zeros((300, 300, 3), np.uint8)
obj = NumpyEncoder()
outjson = {}
outjson['img'] = base64.b64encode(img)
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)
socket.sendall(json_data
socket.close()
and here is java side;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Base64;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.javafx.iio.ImageFormatDescription;
import com.sun.prism.Image;
import java.awt.Color;
import java.awt.Dimension;
public class ServerFrame extends JFrame {
private JPanel contentPane;
public static BufferedImage bufferedImage;
/**
* Launch the application.
* #throws IOException
* #throws JSONException
*/
public static void main(String[] args) throws IOException, JSONException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerFrame frame = new ServerFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(5555);
} catch(IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
System.out.println("Server Socket Has Been Started . . .");
try {
clientSocket = serverSocket.accept();
System.out.println("User Connected :" + clientSocket.getLocalAddress().toString());
} catch(IOException e) {
System.out.println(e.getMessage());
}
StringBuilder sb = new StringBuilder();
InputStream in = clientSocket.getInputStream();
if(in == null) System.exit(1);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
//System.out.println(sb.toString());
JSONObject json = new JSONObject(sb.toString());
String leaf_name = json.getString("leaf");
String mat_string = json.getString("img");
byte[] raw_data = Base64.getDecoder().decode(mat_string);
bufferedImage = ImageIO.read(new ByteArrayInputStream(raw_data));
if(bufferedImage == null) System.out.println("warning");
System.out.println(raw_data.length);
FileOutputStream fos = new FileOutputStream("image.jpg");
try {
fos.write(raw_data);
}
finally {
fos.close();
}
/*JPanel panel = new JPanel();
panel.setBackground(Color.RED);
Dimension dim = new Dimension(50,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
label.setSize(label.getPreferredSize());
panel.add(label);
panel.setVisible(true);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bufferedImage)));*/
br.close();
clientSocket.close();
}
/**
* Create the frame.
*/
public ServerFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
Can you see the problem, Why is it null ?
change to :
outjson['img'] = base64.b64encode(img.tobytes())

compress pdf with large images via java

Looking for a way to compress images in a pdf and to output a pdf for archiving. I cannot compress the images before creation as it would compromise the quality of the print.
The size of each pdf is around 8MB with the bulk of this being made up of 2 images. Images are in png format and are brought into pdf during generation(3rd party generator used)
Is there a way to compress these in java without using a 3rd party tool. I have tried with pdfbox, itext and a 3rd party exe(neevia), the 3rd party tool the only one that has given me any results so far(Down to around half a MB) but I do not want to relinquish control to an exe.
Sample code is below.
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDStream;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
public class compressPDF {
public static void main (String[] args) throws IOException, DocumentException, COSVisitorException {
/*
* Using PDF Box
*/
PDDocument doc; // = new PDDocument();
doc = PDDocument.load("C:/_dev_env_/TEMP/compressPDF/TRPT_135002_1470_20131212_121423.PDF");
PDStream stream= new PDStream(doc);
stream.addCompression();
doc.save("C:/_dev_env_/TEMP/compressPDF/compressed_pdfBox.pdf");
doc.close();
/*
* Using itext
*/
PdfReader reader = new PdfReader("C:/_dev_env_/TEMP/compressPDF/TRPT_135002_1470_20131212_121423.PDF");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/_dev_env_/TEMP/compressPDF/compressed_Itext.pdf"), PdfWriter.VERSION_1_5);
stamper.setFullCompression();
stamper.getWriter().setCompressionLevel(50);
int total = reader.getNumberOfPages() + 1;
for (int i = 1; i < total; i++) {
reader.setPageContent(i, reader.getPageContent(i));
}
stamper.close();
reader.close();
/*
* Using 3rd party - Neevia
*/
try {
Process process = new ProcessBuilder("C:/Program Files (x86)/neeviaPDF.com/PDFcompress/cmdLine/CLcompr.exe","C:/_dev_env_/TEMP/compressPDF/TRPT_135002_1470_20131212_121423.PDF", "C:/_dev_env_/TEMP/compressPDF/compressed_Neevia.pdf").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("Created!!");
}
}
}
I used code below for a proof of concept... Works a treat :) Thanks to Bruno for setting me on the right path :)
package compressPDF;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.PdfImageObject;
public class ResizeImage {
/** The resulting PDF file. */
//public static String RESULT = "results/part4/chapter16/resized_image.pdf";
/** The multiplication factor for the image. */
public static float FACTOR = 0.5f;
/**
* Manipulates a PDF file src with the file dest as result
* #param src the original PDF
* #param dest the resulting PDF
* #throws IOException
* #throws DocumentException
*/
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfName key = new PdfName("ITXT_SpecialId");
PdfName value = new PdfName("123456789");
// Read the file
PdfReader reader = new PdfReader(src);
int n = reader.getXrefSize();
PdfObject object;
PRStream stream;
// Look for image and manipulate image stream
for (int i = 0; i < n; i++) {
object = reader.getPdfObject(i);
if (object == null || !object.isStream())
continue;
stream = (PRStream)object;
// if (value.equals(stream.get(key))) {
PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
System.out.println(stream.type());
if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
PdfImageObject image = new PdfImageObject(stream);
BufferedImage bi = image.getBufferedImage();
if (bi == null) continue;
int width = (int)(bi.getWidth() * FACTOR);
int height = (int)(bi.getHeight() * FACTOR);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
ImageIO.write(img, "JPG", imgBytes);
stream.clear();
stream.setData(imgBytes.toByteArray(), false, PRStream.BEST_COMPRESSION);
stream.put(PdfName.TYPE, PdfName.XOBJECT);
stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.put(key, value);
stream.put(PdfName.FILTER, PdfName.DCTDECODE);
stream.put(PdfName.WIDTH, new PdfNumber(width));
stream.put(PdfName.HEIGHT, new PdfNumber(height));
stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
}
// Save altered PDF
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
/**
* Main method.
*
* #param args no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws IOException, DocumentException {
//createPdf(RESULT);
new ResizeImage().manipulatePdf("C:/_dev_env_/TEMP/compressPDF/TRPT_135002_1470_20131212_121423.PDF", "C:/_dev_env_/TEMP/compressPDF/compressTest.pdf");
}
}
Just to update the excellent answer from #Daniel, I update his code to be compatible with iText7.
package opencde.builder.compresspdf;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfStream;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import com.itextpdf.layout.element.Image;
public class ResizeImageV7 {
// Logging
private static Logger logger = LoggerFactory.getLogger(ResizeImageV7.class);
/**
* Manipulates a PDF file src with the file dest as result
*
* #param src the original PDF
* #param dest the resulting PDF
* #param resizeFactor factor to multiplicate to resize image
* #throws IOException
*/
public void manipulatePdf(String src, String dest,Float resizeFactor) throws IOException {
//Get source pdf
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
// Iterate over all pages to get all images.
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++)
{
PdfPage page = pdfDoc.getPage(i);
PdfDictionary pageDict = page.getPdfObject();
PdfDictionary resources = pageDict.getAsDictionary(PdfName.Resources);
// Get images
PdfDictionary xObjects = resources.getAsDictionary(PdfName.XObject);
for (Iterator<PdfName> iter = xObjects.keySet().iterator() ; iter.hasNext(); ) {
// Get image
PdfName imgRef = iter.next();
PdfStream stream = xObjects.getAsStream(imgRef);
PdfImageXObject image = new PdfImageXObject(stream);
BufferedImage bi = image.getBufferedImage();
if (bi == null)
continue;
// Create new image
int width = (int) (bi.getWidth() * resizeFactor);
int height = (int) (bi.getHeight() * resizeFactor);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(resizeFactor, resizeFactor);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
// Write new image
ImageIO.write(img, "JPG", imgBytes);
Image imgNew =new Image(ImageDataFactory.create(imgBytes.toByteArray()));
// Replace the original image with the resized image
xObjects.put(imgRef, imgNew.getXObject().getPdfObject());
}
}
pdfDoc.close();
}
/**
* Main method.
*
* #param src the original PDF
* #param dest the resulting PDF
* #param resizeFactor factor to multiplicate to resize image
* #throws IOException
*/
public static void main(String[] args) throws IOException {
//Get input parametres
if (args.length<3 ) {
System.out.println("Source PDF, Destination PDF and Resize Factor must be provided as parametres");
} else {
String sourcePDF=args[0];
String destPDF=args[1];
Float resizeFactor=Float.valueOf(new String(args[2]));
logger.info("Inovking Resize with args, source:" + sourcePDF
+ " destination:" + destPDF
+ " factor:" + resizeFactor);
//Call method to resize images
new ResizeImageV7().manipulatePdf(sourcePDF,destPDF,resizeFactor);
logger.info("PDF resized");
}
}
}

JFrame not appearing

I'm writing a simple-ish program to look up movie information, and I'm having a bit of an issue making the GUI appear.
I appreciate any help anyone might be able to offer.
package guiprojj;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import guiprojj.gui;
import javax.swing.JFrame;
#SuppressWarnings("unused")
public class Test {
public static void main(String args[]) throws IOException {
BufferedReader rd;
OutputStreamWriter wr;
String movie = null;
//Scanner s = new Scanner(System.in);
//System.out.println("Enter input:");
//movie = s.nextLine();
//movie = movie.replaceAll(" ", "%20");
while (movie != null)
{
try {
URL url = new URL("http://www.imdbapi.com/?i=&t=" + movie);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
line = rd.readLine();
if (line != null) {
System.out.println(line);
} else {
System.out.println("Sorry! That's not a valid URL.");
}
} catch (UnknownHostException codeyellow) {
System.err.println("Caught UnknownHostException: " + codeyellow.getMessage());
}
catch (IOException e)
{
System.out.println("Caught IOException:" + e.getMessage());
}
}
}
}
and
package guiprojj;
import javax.swing.*;
public class gui {
public static void main()
{
JFrame maingui = new JFrame("Gui");
JPanel pangui = new JPanel();
JTextField movie = new JTextField(16);
maingui.add(pangui);
pangui.add(movie);
maingui.setVisible(true);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
are my two classes!
Add a String array argument to the main method of gui so that the application has a valid entry point
public static void main(String[] args)

Categories