我正在尝试使用 Java 创建一个程序,它可以截取用户屏幕的屏幕截图,压缩图像,然后通过套接字将其发送到服务器。 由于某种原因,图像最终被保存损坏(无法读取)。你能帮我找出问题所在吗?
CLIENT:(屏幕截图作为 BufferedImage 输入,然后返回的字节数组返回到第二个函数,该函数将其发送到服务器)
public static byte[] compressImage(BufferedImage image) throws IOException {
System.out.println("starting compression");
ByteArrayOutputStream os = new ByteArrayOutputStream(37628);
float quality = 0.16f;
// create a BufferedImage as the result of decoding the supplied InputStream
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
//Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// compress to a given quality
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// appends a complete image stream containing a single image and
//associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(image, null, null), param);
os.flush();
return os.toByteArray();
}
public void uploadShot(byte[] imgData, String nickname) {
try {
/* Try to connect to the server on localhost, port 5555 */
Socket sk = new Socket("localhost", 23232);
OutputStream output = sk.getOutputStream();
/* Send filename to server */
OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream());
outputStream.write(nickname + "\n");
outputStream.flush();
/* Get response from server */
BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
String serverStatus = inReader.readLine(); // Read the first line
/* If server is ready, send the file */
if (serverStatus.equals("READY")){
int len = imgData.length;
int start = 0;
if (len < 0)
throw new IllegalArgumentException("Negative length not allowed");
if (start < 0 || start >= imgData.length)
throw new IndexOutOfBoundsException("Out of bounds: " + start);
// Other checks if needed.
// May be better to save the streams in the support class;
// just like the socket variable.
OutputStream out = sk.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(len);
if (len > 0) {
dos.write(imgData, start, len);
}
dos.close();
output.close();
sk.close();
System.out.println("Transfer complete.");
}
} catch (Exception ex){
/* Catch any errors */
System.out.println(ex.getMessage());
}
}
服务器:(接收到的图像保存到带有时间戳的文件夹中)
public static void main(String args[]) throws Exception{
System.out.println("Server running...");
/* Listen on port 5555 */
ServerSocket server = new ServerSocket(23232);
/* Accept the sk */
Socket sk = server.accept();
System.out.println("Server accepted client");
InputStream input = sk.getInputStream();
BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));
/* Read the filename */
String nickname = inReader.readLine();
if ( !nickname.equals("") ){
/* Reply back to client with READY status */
outReader.write("READY\n");
outReader.flush();
}
String current = "/home/kasgel/screenshots";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy__HH:mm:ss");
Date timestamp = new Date();
File filename = new File(current + "/" + nickname + "-" + dateFormat.format(timestamp) + ".jpg");
if (!filename.exists()) {
filename.createNewFile();
}
FileOutputStream wr = new FileOutputStream(filename);
byte[] buffer = new byte[sk.getReceiveBufferSize()];
int bytesReceived = 0;
while((bytesReceived = input.read(buffer))>0) {
wr.write(buffer,0,bytesReceived);
}
wr.close();
}
打开保存的屏幕截图时收到的错误消息如下: display.im6:不是 JPEG 文件:以 0x00 0x03 `MyNick-30-03-2015__19:27:58.jpg' @ error/jpeg.c/JPEGErrorHandler/316 开头。
最佳答案
当您写入图像时,首先写入一个 32 位有符号整数,其中包含图像的字节长度:
dos.writeInt(len);
if (len > 0) {
dos.write(imgData, start, len);
}
但是当你读回图像时,你不会先读长度;而是先读长度。您正在读取所有数据(包括长度),就好像它们是图像的一部分一样。
但是你还有第二个问题,它本身也会导致这个问题。当您创建 BufferedReader 并对其调用 readLine 时,它将读取换行符以外的内容 - 它将读取直到缓冲区已满。如果您继续从中读取,这不是问题,但在读取该行后,您将继续从底层 InputStream 中读取,这通常会在换行符之后消耗更多字节。
解决方案是:仅使用一种抽象来读/写数据。在这种情况下,最简单的绝对是使用 DataOutputStream 和 DataInputStream。使用writeUTF
写入文件名并使用readUTF
读回。使用writeInt
写入文件的长度并使用readInt
读取它。使用 write
写入数据并使用 read
读取数据 - 并确保仅读取从 readInt
调用接收到的字节数。最重要的是,继续使用相同的 DataOutputStream 和 DataInputStream 实例;不要在同一底层 InputStream
上构造缓冲读取器和输入流
关于java - 通过套接字发送压缩的 JPG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369831/