PNG图像数据的Javax.ImageIO.IIOException

时间:2015-04-08 04:42:33

标签: java android tcp

我在java中实现一个服务器,它从Android应用程序中接收图像。基本上它是从Android模拟器接收图像,但不是从Android设备。从android模拟器或Android设备接收图像的所有过程都在localhost上完成。

这是我的服务器代码。

public class Server {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static byte[] image;

public static void main(String[] args) throws UnknownHostException, IOException {
    try {
        serverSocket = new ServerSocket(4000); // Server socket

    } catch (IOException e) {
        System.out.println("Could not listen on port: 4000");
    }
    System.out.println("Server started. Listening to the port 4000");

    while (true) {
        clientSocket = serverSocket.accept(); // accept the client connection
        inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
        bufferedReader = new BufferedReader(inputStreamReader); // get the client message
        DataInputStream inputFromClient = new DataInputStream(clientSocket.getInputStream());
        int count = inputFromClient.available();
        System.out.println(count);
        image = new byte[count];
        inputFromClient.readFully(image);
        final BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(image));
        ImageIO.write(bufferedImage, "jpg", new File("image.jpg"));
    }
}

异常

Exception in thread "main" javax.imageio.IIOException: Error reading PNG image data
at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1308)
at com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1577)
at javax.imageio.ImageIO.read(ImageIO.java:1448)
at javax.imageio.ImageIO.read(ImageIO.java:1352)
at server.Server.main(Server.java:39)

Caused by: java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at java.io.DataInputStream.readFully(DataInputStream.java:195)
at com.sun.imageio.plugins.png.PNGImageReader.decodePass(PNGImageReader.java:1092)
at com.sun.imageio.plugins.png.PNGImageReader.decodeImage(PNGImageReader.java:1196)
at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1301)
... 4 more

Java Result: 1

我从javax.imageiio.exception得到一个例外,如果从Android设备发送图像,但对于android模拟器它工作正常。请帮我解决问题。谢谢。

1 个答案:

答案 0 :(得分:0)

您的主要问题在于此行:

int count = inputFromClient.available();

它返回当时已接收的字节数。但是,可能有更多字节等待在服务器端传输。 因此,当您尝试加载时,传输的图像会被截断/不完整。

您现在有两个选择:

  1. 在传输图像数据之前,发送包含数据长度的整数

  2. 如果在写入图像后,只在客户端传输一个图像。在服务器端,您现在必须阅读,直到到达流的末尾。