我正在尝试使用Java创建一个程序,该程序截取用户屏幕的截图,压缩图像,并通过套接字将其发送到服务器。 由于某种原因,图像最终被破坏(它是不可读的)。你能帮我找一下问题吗?
客户端:(屏幕截图以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());
}
}
SERVER :(收到的图像保存到带有时间戳的文件夹中)
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。
答案 0 :(得分:1)
当您编写图像时,首先要编写一个包含图像长度的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