降低 Java 中的图像分辨率

2022-09-04 02:43:21

我需要使用Java程序减小图像的大小(而不是宽度和高度)。他们是否有任何好的API可用于此?

我需要将大小从1MB减少到大约50kb - 100 kb。当然,分辨率会降低,但这并不重要。


答案 1

根据这篇博客文章: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);

答案 2

这是工作代码

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


推荐