
[英]need to convert a bytearray to an image without using imageIO or fileoutputstream
[英]Convert an Image to byteArray keeping the color
我尝试将图像转换为byteArray,然后通过使用以下代码在HttpServlet类中使用BufferedOutputStream将其打印在我的jsp页面上:
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);
}
但是,结果图像失去其颜色。
我猜问题出在byteArray转换部分。 我该如何解决?
有两种字节数组转换,一种是在读取文件时进入字节数组缓冲区,另一种是在写入http响应流时。
1)您可以尝试写入文件以确认是哪种情况。 从这里我可以看到,阅读代码似乎很好。
2)您确定还要在输出流的情况下进行写入和刷新吗?
3)您也可以尝试为内容类型添加http响应标头,以帮助浏览器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.