我正在读取 servlet 中的两个图像,并且需要同时显示这两个图像。目前,仅显示一个图像(首先写入的图像)。无法写入另一个图像。我没有收到任何错误。
我的 servlet 代码如下所示:
BufferedImage buffImageA = ImageIO.read(getServletContext().getResourceAsStream("/images/3520276097315A.jpg"));
BufferedImage buffImageB = ImageIO.read(getServletContext().getResourceAsStream("/images/3520276097315B.jpg"));
logger.logDebug("Images has been read");
watermark(buffImageA,ApplicationConfig.WATERMARK_TEXT);
watermark(buffImageB,ApplicationConfig.WATERMARK_TEXT);
byte[] resultDataA = encodeJPEG(buffImageA, 100);
byte[] resultDataB = encodeJPEG(buffImageB, 100);
byte[] combinedImage = new byte[resultDataA.length+resultDataB.length];
for(int i=0; i<resultDataA.length ;i++){
combinedImage[i] = resultDataA[i];
}
for(int i=resultDataA.length; i<resultDataB.length ;i++){
combinedImage[i] = resultDataB[i];
}
response.setContentType("image/jpeg");
response.setContentLength(resultDataA.length + resultDataB.length);
OutputStream os = response.getOutputStream();
os.write(combinedImage);
os.close();
//水印处理到这里
private void watermark(BufferedImage original, String watermarkText) {
}
private byte[] encodeJPEG(BufferedImage image, int quality) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream((int) ((float) image.getWidth() * image.getHeight() / 4));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float) quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(image);
byte[] result = baos.toByteArray();
baos.close();
return result;
}
我曾尝试使用 ImageIO.write 写入图像,但未能获得所需的内容。