简体   繁体   English

使用 BufferWriter 和 BufferReader 通过 TCP 套接字发送图像

[英]Send image by TCP Socket using BufferWriter and BufferReader

I send from PC to Android App some text, and I also want to send image data by the same Socket.我从 PC 向 Android App 发送一些文本,我也想通过同一个 Socket 发送图像数据。 I try to encoding this in Base64 but on the end piture is corrupted.我尝试在 Base64 中对此进行编码,但最终 piture 已损坏。 My code looks like this.我的代码看起来像这样。

Get data screen:获取数据屏幕:

public static byte[] getScreen()
{
    BufferedImage imagebuf = null;
    try {
        imagebuf = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    } catch (HeadlessException | AWTException e) {
        System.err.println("Can't get screen.");
        return null;
    }           

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] imageInByte;
    try {
        ImageIO.write(imagebuf, "jpg", baos);
        baos.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    finally {       
        imageInByte = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return imageInByte; 
}

Then send data by socket:然后通过socket发送数据:

BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
List<ScreenBuffor> screenList = ScreenBuffor.getScreenList();//Place where I keep all screen data with names
            if(!screenList.isEmpty())
            {
                for(ScreenBuffor screen : screenList)
                {                       bufferedWriter.write(InformationCommunicate.screenData);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();                     

                    bufferedWriter.write(screen.getNameScreen());
                    bufferedWriter.newLine();
                    bufferedWriter.flush();

                    String image = Base64.getEncoder().encodeToString(screen.getDataScreen());

                    char[] imageCharacter = image.toCharArray();
                    int sizeArray = imageCharacter.length;

                    bufferedWriter.write(String.valueOf(sizeArray));
                    bufferedWriter.newLine();
                    bufferedWriter.flush();                     

                    bufferedWriter.write(imageCharacter, 0, sizeArray);
                    bufferedWriter.flush();                             
                }
            }

And read and save this image data on Android:并在 Android 上读取并保存此图像数据:

InputStream input = clientSocket.getInputStream();
        InputStreamReader isr = new InputStreamReader(input, "UTF-8");
        BufferedReader reader = new BufferedReader(isr);

String lineCharacter = reader.readLine();

if(lineCharacter.equals(InformationCommunicate.screenData))
            {
                lineCharacter = reader.readLine();
                Log.i("PictureSave", "Image name: " + lineCharacter);
                nameScreen = new String(lineCharacter);
                lineCharacter = reader.readLine();
                Log.i("PictureSave", "Buffor Size: " + lineCharacter);
                int lengthBuf = Integer.parseInt(lineCharacter);
                char[] screenCharBuff = new char[lengthBuf];
                for(int i = 0; i < lengthBuf; i++)
                {
                    int onecharacter = reader.read();
                    if((int) onecharacter == -1)
                        throw new IllegalStateException("Image data is Incomplete");
                    screenCharBuff[i] = (char) onecharacter;
                }

                String imageString = new String (screenCharBuff);
                byte[] imageData = imageString.getBytes();

                File photo=new File(Environment.getExternalStorageDirectory(), "Picture" + lengthBuf + ".jpg");


                try {
                    FileOutputStream fos=new FileOutputStream(photo.getPath());

                    fos.write(imageData);
                    fos.close();
                }
                catch (java.io.IOException e) {
                    Log.e("PictureSave", "Exception in photoCallback", e);
                }

Image is save, but like I wrote, is broken, and I can't open it.图像已保存,但就像我写的那样,已损坏,无法打开。 Please help.请帮忙。

You aren't de-encoding it from base64 So you're saving base64(picturedata), not picture data.您没有从 base64 对其进行解码,因此您正在保存 base64(picturedata),而不是图片数据。 You have two options- decode it first, or don't encode it at all.您有两个选择——先解码,或者根本不编码。 Really I'd take the second option- the only reason to use Base64 is to send binary data over a text-only input stream.我真的会选择第二个选项——使用 Base64 的唯一原因是通过纯文本输入流发送二进制数据。 Since you don't have a text only input stream here using Base64 is unneeded and wasteful.由于您在这里没有纯文本输入流,因此使用 Base64 是不必要且浪费的。

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

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