我尝试将图像转换为 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) 您可以尝试写入文件以确认是这种情况。 据我所知here ,阅读代码似乎没问题。
2) 您确定在输出流的情况下也正在写入和刷新吗?
3) 您还可以尝试为内容类型添加 http 响应 header 以帮助浏览器。
关于java - 将图像转换为 byteArray 并保持颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087826/