2014-09-28 33 views
1

我试图将图像转换为字节组,然后通过使用的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); 
      } 

然而,结果图像失去了它的颜色。

Before After

的问题是在字节组转换部分,我猜。我该如何解决这个问题?

+0

你是否真的需要在对图像进行编码之前对图像进行解码(即,您打算对图像执行任何图像处理还是需要将图像转换为JPEG)?如果不是,只需将文件中的字节复制到servlet'OutputStream'即可轻松避免。作为奖励,它也快得多。 – haraldK 2014-09-29 08:29:18

回答

0

有两个字节数组转换,一个读取文件并进入字节数组缓冲区,另一个写入http响应流。

1) 您可以尝试写入文件以确认是哪种情况。 从我所看到的here,阅读的代码似乎很好。

2) 您确定您正在编写和刷新输出流的情况吗?

3) 您也可以尝试为内容类型添加http响应标头以帮助浏览器。

+0

我试图按照你的建议将它写入文件。 JPEG版本与我在下面发布的第二张(丢失的颜色)相同,但PNG和GIF版本很好。我用头文件更新了我的问题。我应该用png改变jpeg吗?但是,为什么JPG文件在写入JPG文件时失去了颜色? – ftb 2014-09-28 19:46:34

+0

如果即使在写入文件时颜色仍未编码,则问题出现在该步骤中。也许你可以直接从文件中读取字节并将其转储到流中,而不是像转换它那样产生开销,正如'haraldK'的建议 – 2014-10-03 03:08:35

相关问题