降低java中的图像分辨率

Moh*_*dil 12 java api image-processing image-resizing

我需要使用Java程序减小图像的大小(而不是宽度和高度).他们有什么好的API可用吗?

我需要将大小从1MB减小到大约50kb - 100 kb.当然,决议会减少,但这无关紧要.

iro*_*hon 10

根据这篇博客文章: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);
Run Code Online (Sandbox Code Playgroud)


Moh*_*dil 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码对我很有用.如果您需要调整图像大小,则可以在此处更改x和y比例JAI.create("SubsampleAverage", image, xscale,yscale, qualityHints);