[英]How to send images from PC to Android by using Socket?
I send a image using this code in pc:我在 pc 中使用此代码发送图像:
public static void sendImage(File image,Socket socket) throws IOException {
OutputStream outputStream = socket.getOutputStream();
BufferedImage Bimage = ImageIO.read(image);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(Bimage, "png", byteArrayOutputStream);
byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
outputStream.write(size);
System.out.println("size");
outputStream.write(byteArrayOutputStream.toByteArray());
System.out.println("BT");
outputStream.flush();
}
And I receive the image using this code in android:我在 android 中使用此代码接收图像:
private void show_imageFromService() throws IOException {
InputStream inputStream = CreateActivity.client.socket.getInputStream();
byte[] sizeAr = new byte[4];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
byte[] imageAr = new byte[size];
inputStream.read(imageAr);
Rect rect=new Rect();
rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=1;
Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);
imageView.setImageBitmap(bmp);
}
But the image can't show in android, can anyone have other way to deal with this?但是图像无法在 android 中显示,还有其他方法可以解决这个问题吗?
I fixed the send code:我修复了发送代码:
public static void sendImage(File image,Socket socket) throws IOException {
FileInputStream fileInputStream=new FileInputStream(image);
int size=fileInputStream.available();
byte[] imageByte=new byte[size];
fileInputStream.read(imageByte);
DataOutputStream dataOutputStream=new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeInt(imageByte.length);
System.out.println(imageByte.length);
dataOutputStream.write(imageByte);
dataOutputStream.flush();
}
And fixed the receiver code:并修复了接收器代码:
private void show_imageFromService() throws IOException {
DataInputStream dataInputStream=new DataInputStream(CreateActivity.client.socket.getInputStream());
int size=dataInputStream.readInt();
byte[] imageAr = new byte[size];
int len = 0;
while (len < size) {
len += dataInputStream.read(imageAr, len, size - len);
}
Rect rect=new Rect();
rect.set(imageView.getLeft(),imageView.getTop(),imageView.getRight(),imageView.getBottom());
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=1;
Bitmap bmp=BitmapFactory.decodeByteArray(imageAr,0,imageAr.length,options);
imageView.setImageBitmap(bmp);
}
Now I success to show the image in Android.现在我成功地在 Android 中显示图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.