将jpeg图像发送到Servlet并将其转换为BufferedImage

时间:2017-02-28 00:42:31

标签: java servlets

我需要将一个jpeg图像发送(上传)到Servlet,而不是将其保存在文件中,我想将其转换为BufferedImage并对其进行一些处理。

这是我的客户端代码:

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost httppost = new HttpPost("http://localhost:9000/upload");
File file = new File("/tmp/lena.jpg");

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);


httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
    System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
    resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();

如何在Servlet中接收图像并进行处理?

我在我的接收端Servlet上尝试了这个,但图像为空:

InputStream is = request.getInputStream();
BufferedImage bImageFromConvert = ImageIO.read(is); 

最后,我不应该在进程中将任何内容保存在磁盘上。

1 个答案:

答案 0 :(得分:1)

尝试:

Part file = request.getPart("userfile");
InputStream is = file.getInputStream();