2010-02-06 74 views
1

ImageIO在Windows文件資源管理器中正確生成的JPEG圖像以及safari webbrowser,但在FireFox中,重新採樣的圖像被剪切。jpeg在使用java重新採樣時損壞imageIO

如何在不破壞重採樣的情況下使用ImageIO?

該代碼應調整圖像保持寬高比,以及做JPEG壓縮,將其轉換爲可以寫入套接字的byte []數組。

我的一些代碼。在這個片段中,我嘗試添加Jui庫,但仍然是同樣的問題。

public static BufferedImage imageistream; 

public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException 
{ 
    String imagePath = ""; 
    if(this.is_mac_unix == true) 
    { 
     imagePath = this.path+"/"+child; 
    } 
    else 
    { 
     imagePath = this.path+"\\"+child; 
    }  
     PixelImage bmp = null; 
     try { 
      bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);    
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Resample resample = new Resample(); 
     resample.setInputImage(bmp); 
     double fixedRatio = width/height; 

     if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio) 
     { 

     resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width))); 

     } 
     else 
     { 
      resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));  

     } 
     resample.setFilter(Resample.FILTER_TYPE_LANCZOS3); 
     resample.process(); 
     PixelImage scaledImage = resample.getOutputImage();   
     Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage); 
     bmp = null;    
     Runtime rt = Runtime.getRuntime(); 
     rt.gc();       
} 


     ... 


     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     try { 
     ImageIO.write(Processor.imageistream, "jpg", baos); 
        // ImageIO.write(Processor.imageistream, "png", baos); Works! 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    byte bytes[] = baos.toByteArray(); 

    ByteArrayInputStream is = new ByteArrayInputStream(bytes); 

     OutputStream os = (OutputStream)obj[1]; 
     OutputStreamWriter writer = (OutputStreamWriter)obj[0]; 

     byte[] buf= new byte[4096]; 
     int c; 

     try { 

     while (true) { 
    c= is.read(buf); 
    if (c<= 0) break; 
    os.write(buf, 0, c); 

     } 
     writer.close(); 
     os.close(); 
     is.close(); 

回答

1

我已經成功地使用:

BufferedImage bufferedImage = ImageIO.read(..); 
Image img = bufferedImage.getScaledInstance(..); 
BufferedImage result = // transform Image to BufferedImage 
ImageIO.write(result, "image/jpeg", response.getOutputStream()); 

變換,簡單地寫圖像的內容到一個新的BufferedImage