我正在製作一個程序,將客戶端屏幕發送到服務器並顯示它,但速度非常慢。一幀需要2-3秒,上傳/下載速度不成問題。有什麼我做錯了/我可以改變以加快速度?Java ImageIO非常慢
服務器:
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.GZIPInputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Server {
public static void main(String[] args) {
try {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel label = new JLabel();
label.setSize(800, 600);
label.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.getViewport().add(label);
panel.add(scroll, BorderLayout.CENTER);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setSize(800, 600);
frame.setVisible(true);
ServerSocket serverSocket = new ServerSocket(25565);
Socket socket = serverSocket.accept();
GZIPInputStream in = new GZIPInputStream(socket.getInputStream());
BufferedImage image = null;
while(socket.isConnected()) {
image = ImageIO.read(in);
if(image != null) {
label.setIcon(new ImageIcon(image));
label.repaint();
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶:
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.Socket;
import java.util.zip.GZIPOutputStream;
import javax.imageio.ImageIO;
public class Client {
public static void main(String[] args) {
try {
Robot robot = new Robot();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Rectangle screen = new Rectangle((int) toolkit.getScreenSize().getWidth(), (int) toolkit.getScreenSize().getHeight());
Socket socket = new Socket("127.0.0.1", 25565);
GZIPOutputStream out = new GZIPOutputStream(socket.getOutputStream());
while(socket.isConnected()) {
ImageIO.write(robot.createScreenCapture(screen), "png", out);
}
out.close();
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
你嘗試過什麼到目前爲止找出性能瓶頸?你有沒有做任何分析? – cyroxx 2012-08-10 23:47:33
看這裏:http://stackoverflow.com/questions/2293556/looking-for-a-faster-alternative-to-imageio或在這裏:http://stackoverflow.com/questions/7726583/java-imageio-write-佔用達6秒 – paulsm4 2012-08-11 00:01:06
我很確定它是ImageIO,因爲我記得當我檢查哪種圖像格式最好時,其中一些圖像格式最多需要7秒才能寫入磁盤。 – user1007883 2012-08-11 00:02:12