繁体   English   中英

如何使用Socket将图像从PC发送到Android?

[英]How to send images from PC to Android by using Socket?

我在 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 中显示图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM