我正在创建一个桌面客户端-服务器应用程序,在该应用程序中,我捕获由渲染器渲染的jpg图像中的帧,并将它们存储在客户端。现在我需要把图片上传到服务器上。我试过了为每个捕获的图像放置一个单独的线程,将其直接上传到服务器,但这非常耗时。此外,我试图在拍摄停止后从客户端上传所有图像,但这不是我想要的情况。
所以有没有一种方法可以有效地将直接拍摄的图像上传到服务器。
对于捕获图像,我使用BufferedImage和ImageIO.write方法
提前感谢
通过套接字上传图像是在服务器上上传图像的最快方式,因为数据将作为字节流传递到服务器。
下面是简单的套接字客户端和套接字服务器来实现图像上传
客户端
public class ImageUploadSocketClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost",6666);
OutputStream outputStream = socket.getOutputStream();
BufferedImage image = ImageIO.read(new File("path to image /your_image.jpg"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
outputStream.write(size);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
socket.close();
}
}
服务器
public class ImageUploadSocketRunnable implements Runnable{
public static final String dir="path to store image";
Socket soc=null;
ImageUploadSocketRunnable(Socket soc){
this.soc=soc;
}
@Override
public void run() {
InputStream inputStream = null;
try {
inputStream = this.soc.getInputStream();
System.out.println("Reading: " + System.currentTimeMillis());
byte[] sizeAr = new byte[4];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
byte[] imageAr = new byte[size];
inputStream.read(imageAr);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
ImageIO.write(image, "jpg", new File(dir+System.currentTimeMillis()+".jpg"));
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(ImageUploadSocketRunnable.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(13085);
while(true){
Socket socket = serverSocket.accept();
ImageUploadSocketRunnable imgUploadServer=new ImageUploadSocketRunnable(socket);
Thread thread=new Thread(imgUploadServer);
thread.start();
}
}
}
在服务器上你应该为不同的客户端套接字创建不同的线程,这样你就可以实现从不同客户端并发上传图像。
希望上面的例子能对你有所帮助。