我试图将图像转换为字节组,然后通过使用的BufferedOutputStream在HttpServlet类用下面的代码打印我的JSP页面上:将图像转换到ByteArray中保持颜色
public byte[] extractBytes(String imagePath) {
byte[] imageInByte = new byte[0];
try {
ByteArrayOutputStream baos = null;
BufferedImage originalImage = ImageIO.read(new File(imagePath));
baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
imageInByte = baos.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
}
return imageInByte;
}
要打印:
imageInByte = extractBytes(requestedUrl);
response.setContentType(
"image/jpeg");
response.setContentLength(imageInByte.length);
response.setHeader(
"Content-Disposition", "inline; filename=\"" + name
+ "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
time = System.currentTimeMillis();
input = new BufferedInputStream(new ByteArrayInputStream(imageInByte));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
然而,结果图像失去了它的颜色。
的问题是在字节组转换部分,我猜。我该如何解决这个问题?
你是否真的需要在对图像进行编码之前对图像进行解码(即,您打算对图像执行任何图像处理还是需要将图像转换为JPEG)?如果不是,只需将文件中的字节复制到servlet'OutputStream'即可轻松避免。作为奖励,它也快得多。 – haraldK 2014-09-29 08:29:18