降低java中的图像分辨率
我需要使用Java程序缩小图像的大小(而不是宽度和高度)。 他们有什么好的API可用于此 我需要将大小从1MB减少到大约50kb-100KB。降低java中的图像分辨率,java,api,image-processing,image-resizing,Java,Api,Image Processing,Image Resizing,我需要使用Java程序缩小图像的大小(而不是宽度和高度)。 他们有什么好的API可用于此 我需要将大小从1MB减少到大约50kb-100KB。 当然,分辨率会降低,但这并不重要。根据这篇博文:你可以用它来做你想做的事。下面的示例代码应该为您提供一个良好的起点。这将调整图像的大小,包括高度和宽度,以及图像质量。图像达到所需文件大小后,可以在显示图像时将其缩放回所需的像素高度和宽度 // read in the original image from an input stream Seekable
当然,分辨率会降低,但这并不重要。根据这篇博文:你可以用它来做你想做的事。下面的示例代码应该为您提供一个良好的起点。这将调整图像的大小,包括高度和宽度,以及图像质量。图像达到所需文件大小后,可以在显示图像时将其缩放回所需的像素高度和宽度
// 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);
您可以使用JAI增加已写入JPEG的压缩,而无需进行任何缩放。请参见如果您的图像类型受的实现支持,则您可以调整质量,如下所示。其他方法,如
getBitRate()
,可能允许您优化结果。这是工作代码
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(“子采样范围”、图像、xscale、yscale、质量提示)代码>比提高分辨率的问题要好得多…问题解决了!!检查我的答案。我试过那个例子,但它不起作用。当我传递除1.0f以外的任何浮点值时,它会创建更大的图像大小。当我通过1.0f时,它正在创建一个大小很小但质量太低的文件,或者我可以说图像丢失了;含义因格式而异。顺便说一句,你用的是什么格式?回答得很好,年轻人。但是我可以提高这张图片的dpi级别吗?有什么方法可以做到这一点吗?