2011-06-17 88 views
10

我需要使用Java程序減小圖像的大小(不是寬度和高度)。 他們有任何好的API可用於此?在java中減少圖像分辨率

我需要從1MB減小到大約50kb - 100 kb的大小。 當然,分辨率會降低,但這並不重要。

+2

比提高分辨率的問題好得多... –

+0

問題解決了!檢查我的答案。 –

回答

6

這是工作的代碼

public class ImageCompressor { 
    public void compress() throws IOException { 
     File infile = new File("Y:\\img\\star.jpg"); 
     File outfile = new File("Y:\\img\\star_compressed.jpg"); 

     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
       infile)); 
     BufferedOutputStream bos = new BufferedOutputStream(
       new FileOutputStream(outfile)); 

     SeekableStream s = SeekableStream.wrapInputStream(bis, true); 

     RenderedOp image = JAI.create("stream", s); 
     ((OpImage) image.getRendering()).setTileCache(null); 

     RenderingHints qualityHints = new RenderingHints(
       RenderingHints.KEY_RENDERING, 
       RenderingHints.VALUE_RENDER_QUALITY); 

     RenderedOp resizedImage = JAI.create("SubsampleAverage", image, 0.9, 
       0.9, qualityHints); 

     JAI.create("encode", resizedImage, bos, "JPEG", null); 

    } 

    public static void main(String[] args) throws IOException { 

     new ImageCompressor().compress(); 
    } 
} 

此代碼是偉大的工作對我來說。如果你需要調整圖像大小,那麼你可以 這裏改變x和y的比例JAI.create("SubsampleAverage", image, xscale,yscale, qualityHints);

+0

很好的答案年輕的男人。但是,我可以增加這個圖像的dpi級別有沒有辦法做到這一點? – Buntylm

+0

@BuntyMadan看到這個:http://stackoverflow.com/a/14050844/235710 –

9

根據此博客文章:http://i-proving.com/2006/07/06/java-advanced-imaging/您可以使用Java Advanced Imaging Library做你想做的。以下示例代碼應該爲您提供一個很好的起點。這將調整圖像的高度和寬度以及圖像質量。一旦您的圖像具有所需的文件大小,當您顯示圖像時,可以將其縮小到所需的像素高度和寬度。

// read in the original image from an input stream 
SeekableStream s = SeekableStream.wrapInputStream(
    inputStream, true); 
RenderedOp image = JAI.create("stream", s); 
((OpImage)image.getRendering()).setTileCache(null); 

// now resize the image 

float scale = newWidth/image.getWidth(); 

RenderedOp resizedImage = JAI.create("SubsampleAverage", 
    image, scale, scale, qualityHints); 


// lastly, write the newly-resized image to an 
// output stream, in a specific encoding 

JAI.create("encode", resizedImage, outputStream, "PNG", null); 
0

如果您的圖像類型由實施ImageWriteParam支持,您可以調整質量,如example所示。其他ImageWriteParam方法(如getBitRate())可能允許您優化結果。

+0

我試過這個例子,它不工作。當我通過除1.0f之外的任何浮點值時,它會創建更大的圖像大小。當我通過1.0f它創建一個低尺寸的文件,但質量太低,或者我可以說圖像簡單地丟失了。 –

+0

您可以查看可用的質量說明和值;含義因格式而異。順便說一句,你使用什麼格式? – trashgod