Error in Sending captured image from Java to Android - java

I have the code to capture image from screen in java, I have the final captured image as BufferedImage object and Can cast it to ImageIcon
The problem is when sending that file to android can't read it as bitmap drawable. Any one have answer to this ?
Code to send (Java)
BufferedImage image = robot.createScreenCapture(rectangle);
ImageIcon imageIcon = new ImageIcon(image);
//Send captured screen to the server
try {
System.out.println("before sending image");
oos.writeObject(imageIcon);
oos.reset(); //Clear ObjectOutputStream cache
System.out.println("New screenshot sent");
} catch (IOException ex) {
ex.printStackTrace();
}
Android Receiver Part
Thread t= new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
client= sc.accept();
is = client.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapDrawable imageIcon = null;
try {
ois = new ObjectInputStream(is);
imageIcon = (BitmapDrawable) ois.readObject();
//Drawable d = Drawable.createFromStream(is, null);
IV.setImageDrawable(imageIcon);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("New image recieved");
}
}
I get the exception of it can't cast the imageIcon or the BufferedImage to Bitmap drawable.

You should not use objects, because oracle jvm is not the same as android's dalvik.
Try to convert captured image to raw bytes and send those bytes to android. Then in android covert this raw data to drawable.

Related

Jframe.setContentPane(new JLabel([image])); background image not loading after built .jar

I am having a problem with loading images, as I am trying to load a background for my launcher. It works when I run it in Eclipse, but when I export it to a jar file, it doesn't. I have paged through the already asked questions, No luck.
Here is my code:
public void initializeJFrame(){
ImageIcon bg = new ImageIcon("src/background.png");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (jta.getText().length() < 3 || jta.getText().length() > 16) {
System.exit(-1);
} else {
try {
Runtime.getRuntime().exec(cmd, null, dir);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
}
});
jf.setSize(WIDTH,HEIGHT);
jf.setTitle("Cracked Launcher");
jf.setLayout(null);
jf.setContentPane(new JLabel(bg));
jf.setResizable(false);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.start();
My image is in the src folder, nothing else. I cannot find what the problem is.
Thanks for your support.
ImageIcon bg = new ImageIcon("src/background.png");
This constructor takes a filename; it will not load resources from a jar. You want to pass a URL generated by a classloader, like so:
ImageIcon bg = new ImageIcon(getClass().retResource("background.png"));

Download image from URL keeping exif data

I'm trying to download an image with exif data from URL to my pc, the problem is that exif data is gone after the image has been downloaded.
here's the code i use
public static void downloadImage(String str) {
try {
URL url = new URL("https://upload.wikimedia.org/wikipedia/commons/6/68/Goldmantelziesel.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("F:\\Photos\\ww123\\"+str+".jpg");
ImageIO.write(img, "jpg", file);
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

Get bitmap image from file

I need to save a captured image from camera on a tmp file and retrieve it on the next activity, so i can handle better the OOM error.
So i did something like this to write the file:
public void savePicAtFile(Bitmap pic){
FileOutputStream out = null;
try {
out = new FileOutputStream("tmpCameraPic");
pic.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
now i don't know how to retrieve the compressed image, should i just create a bitmap and getall the stream?
Any help?

Android pdf maker code error

I'm trying to take a screenshot of my Android activity (bitmap) and then making a PDF file out of it. I used the itextpdf library. Here's what I have:
public void onSaveDataClicked(View reportsLayout){
//take screen shot
Bitmap screen; View v1 = reportsLayout.getRootView();
v1.setDrawingCacheEnabled(true);
screen = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
addImage(document,byteArray);
document.close();
}
catch (Exception e){
e.printStackTrace();
}
}
private static void addImage(Document document,byte[] byteArray) {
Image image = null;
try {
image = Image.getInstance(byteArray);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// image.scaleAbsolute(150f, 150f);
try {
document.add(image);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I try to run I get the errors: "Image cannot be converted to Element" and "cannot find symbol method getInstance(byte[])"
A lot of the code I found online through a tutorial on how to achieve this. I'm kind of unfamiliar with this sort of thing. Any help and ideas would be appreciated.
Use import com.itextpdf.text.Image;and remove the default Android one.

Update TextFlow from another class JavaFx

I'm here with my JavaFx app.
I have two class:
I start these class in two different Thread. Because server is blockable.
My UI class ( Called Main ( I know i need to change this)).
A Server class ( Called Serveur )).
In my Server Class when i receive bytes with a ServerSocket.
I need to update a TextFlow (called flowMessafe) in my UI class :
with flowMessage.getChildren().add(); I can update this TextFlow without problem in my UI class.
But i my Server class i can't.
EDIT : I try all the things, but i think i found a big problem. I update the wrong instance of my javafx app. I change the code with current code
He is a part of my server code
My Server Constructor
public Serveur(Mediator med){
this.med=med;
try {
lancer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Loop to catch message or file.
for(;;){
try {
Thread.sleep(1L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Attente de communication ...");
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
byte[] bytes = new byte[16*1024];
while ((count = in.read(bytes)) > 0) {}
String mode = new String(bytes);
String[] split = mode.split(";");
if(split[0].compareTo("Message")==0){
recevoirMessage();
} else if(split[0].compareTo("Fichier")==0){
recevoirFichier(split[2]);
}
in.close();
socket.close();
}
When i receive a message i go to this function :
public void recevoirMessage() {
output = new ByteArrayOutputStream();
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
byte[] bytes = new byte[16*1024];
try {
while ((count = in.read(bytes)) > 0) {}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Message reçus");
String recu = "Message : "+new String(bytes);
System.out.println(recu);
Platform.runLater(() -> {
Label mes = new Label(new String(bytes));
med.cli.flowMessage.getChildren().add(mes);
});
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And in my main i have only empty constructor like
public Main(){}
In my UI class i have this to create my App :
'#Override
public void start(Stage primaryStage) {
try {
this.pStage = primaryStage;
this.pStage = new Stage();
idPane = new BorderPane();
Parent page;
page = FXMLLoader.load(getClass().getResource("/application/application.fxml"));
this.pStage.setTitle("Messagerie");
Scene scene = new Scene(page);
flowMessage = new TextFlow();
idContenuMessage= new ChoiceBox<String>();
scrollPane= new ScrollPane();
//flowMessage = new TextFlow();
String css = this.getClass().getResource("application.css").
toExternalForm();
scene.getStylesheets().clear();
scene.getStylesheets().add(css);
this.pStage.setScene(scene);
this.pStage.setResizable(false);
this.pStage.show();
this.pStage.setOnCloseRequest(event -> {
Serveur.close();
});
} catch (IOException e) {
e.printStackTrace();
}
}'
And i don't know how to update my UI TextFlow in my server Class.
I saw different things like the Mediator Pattern, i try this but it didn't work ( maybe i do something wrong ).
I start my app with this class :
package communication;
import application.Main;
import javafx.application.Application;
import javafx.stage.Stage;
public class Mediator extends Application implements Runnable {
private Serveur serv;
public Main cli;
public Thread thread;
private Stage primaryStage;
public static void main(String args[]){
launch(args);
}
public Mediator(){
cli = new Main();
thread = new Thread(this,"serv");
thread.start();
}
#Override
public void run() {
setServ(new Serveur(this));
}
#Override
public void start(Stage stage) throws Exception {
primaryStage = stage;
cli.start(primaryStage);
}
public Serveur getServ() {
return serv;
}
public void setServ(Serveur serv) {
this.serv = serv;
}
}
Thanks for Helping.
I would use Platform.runLater() to put your GUI changes on the Javafx application thread, e.g.
public void recevoirMessage() {
output = new ByteArrayOutputStream();
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
byte[] bytes = new byte[16*1024];
try {
while ((count = in.read(bytes)) > 0) {}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Message reçus");
String recu = "Message : "+new String(bytes);
System.out.println(recu);
//inserted here
Platform.runLater(new Runnable() {
#Override public void run() {
//HERE I WANT TO UPDATE MY TEXTFLOW
}
});
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Firstly TextFlow does not have text property so you can't set that value to it. Add Text object to text flow:
Text text = new Text();
flowMessage = new TextFlow(text);
Then create StringProperty, bind it to Text component textProperty and update this value in Server class.
Application class:
public class Mediator extends Application implements Runnable {
private Serveur serv;
public Main cli;
private StringProperty textProperty = new SimpleStringProperty("text");
public Thread thread;
private Stage primaryStage;
public static void main(String args[]){
launch(args);
}
public Mediator(){
cli = new Main(this,textProperty);
thread = new Thread(this,"serv");
thread.start();
}
#Override
public void run() {
serv = new Serveur(this,textProperty);
}
#Override
public void start(Stage stage) throws Exception {
primaryStage = stage;
cli.start(primaryStage);
}
}
Pass textProperty to Main and Serveur classes.
cli = new Main(this, textProperty);
serv = new Serveur(this, textProperty);
Bind text property to Text component:
text.textProperty().bind(textProperty);
Finally update textProperty in JavaFX Application Thread in your Serveur class:
public void recevoirMessage() {
output = new ByteArrayOutputStream();
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
byte[] bytes = new byte[16*1024];
try {
while ((count = in.read(bytes)) > 0) {}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Message reçus");
String recu = "Message : "+new String(bytes);
System.out.println(recu);
//inserted here
Platform.runLater(new Runnable() {
#Override public void run() {
//HERE I WANT TO UPDATE MY TEXTFLOW
textProperty.setValue(new String(bytes));
}
});
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories