我在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();
}
我在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);
}
但是图像无法在android中显示,有人可以用其他方法来处理吗?
最佳答案
我修复了发送代码:
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();
}
并修复了接收者代码:
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);
}
现在,我成功地在Android中显示了图像。
关于java - 如何使用Socket将图片从PC发送到Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62111695/