Issue
in my code I transfer a image from a PC to a phone via a java socket. Everything works fine, the picture is saved to the phone and there are no problems. But the question arose, is it possible to display image on the screen without saving?
Server code:
FileInputStream fis = new FileInputStream("D:\\fon2.jpg");
byte [] buffer = new byte[fis.available()];
fis.read(buffer);
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
oos.writeObject(buffer);
oos.close();
System.out.println("Done");
client code:
class ClientThread implements Runnable {
@Override
public void run() {
try {
Socket s = new Socket(HOST, 4444);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("hello");
output.flush();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
byte [] buffer = (byte[]) ois.readObject();
// save image
@SuppressLint("SdCardPath") FileOutputStream fos = new FileOutputStream("/sdcard/2.jpg");
fos.write(buffer);
fos.close();
output.close();
out.close();
s.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
solution to this problem:
when you click on the image, a connection to the server is made and the image is sent
main code:
public void image(View view) {
new Thread(new ClientThread()).start();
do {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
break;
}
}while (true);
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
Socket s = new Socket(HOST, 4444);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(tour);
output.flush();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
buffer = (byte[]) ois.readObject();
bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
bitmap = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);
Log.d("log", String.valueOf(buffer));
output.close();
out.close();
s.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
layout:
<ImageView
android:id="@+id/mainImage"
android:layout_width="150dp"
android:layout_height="160dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="image"
android:src="@drawable/ic_gps"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UsingOnClickInXml" />
Solution
Yes that is possible.
Your image is in byte [] buffer = ..
.
You can make a Bitmap
instance with BitmapFactory.decodeByteArray().
After that assign bitmap to an ImageView
.
Answered By - blackapps
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.