簡體   English   中英

降低java中的圖像分辨率

[英]decrease image resolution in java

我需要使用Java程序減小圖像的大小(而不是寬度和高度)。 他們有什么好的API可用嗎?

我需要將大小從1MB減小到大約50kb - 100 kb。 當然,決議會減少,但這無關緊要。

根據這篇博客文章: http//i-proving.com/2006/07/06/java-advanced-imaging/您可以使用Java高級成像庫來執行您想要的操作。 以下示例代碼應為您提供一個良好的起點。 這將調整圖像的高度和寬度以及圖像質量。 一旦您的圖像具有所需的文件大小,您可以在顯示圖像時將其縮放回所需的像素高度和寬度。

// 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);

這是工作代碼

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);

您可以使用JAI來增加書寫JPEG的壓縮,而無需進行任何縮放。 請參閱http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM