因为java默认的图片像素分辨率DPI=72,分辨率有点低。所以研究了一下如何创建指定DPI的方案。
DPI: 指的是每英尺的像素点(dots per inch)
JPEG图片
JPEG图片的元数据定义参看oracle官网。
https://docs.oracle.com/javase/8/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html
参数说明
参数 | 默认值 | 说明 |
---|---|---|
resUnits | 0 | 单位(0 = no units, just aspect ratio; 1 = dots/inch; 2 = dots/cm) |
Xdensity | 1 | The horizontal density or aspect ratio numerator |
Ydensity | 1 | The vertical density or aspect ratio denominator |
如下代代码创建一张分辨率为300DPI(dots/inch)的jpg图片。
String path = "res.jpg";
final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
// // fill all the image with white
g2d.setColor(Color.white);
g2d.fillRect(0, 0, w, h);// Disposes of this graphics context and releases any system resources that it is using.
g2d.dispose();ImageIO.write(image, "jpg", Files.newOutputStream(Paths.get(path)));final ImageWriter writer = ImageIO.getImageWritersBySuffix("jpeg").next();
// writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//调整图片质量
// writeParams.setCompressionQuality(1f);ImageOutputStream ios = ImageIO.createImageOutputStream(new File(path));
writer.setOutput(ios);ImageWriteParam param = writer.getDefaultWriteParam();
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel()), param);
Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", "300");
jfif.setAttribute("Ydensity", "300");
jfif.setAttribute("resUnits", "1"); // density is dots per inchmetadata.mergeTree("javax_imageio_jpeg_image_1.0", tree);
writer.write(null, new IIOImage(image, null, metadata), param);
writer.dispose();
可以在ps上看到分辨率是300.(打开ps,点击“图像”->“图像大小”)
TIFF图片
commons-imaging 对Tiff的支持比较好。
使用commons-imaging 创建一张分辨率为300DPI(dots/inch)的tiff图片。
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-imaging</artifactId><version>1.0-alpha3</version>
</dependency>
String path = "res.tif";
final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
final TiffImagingParameters params = new TiffImagingParameters();
final PixelDensity pixelDensity = PixelDensity.createFromPixelsPerInch(300, 300);
params.setPixelDensity(pixelDensity);
TiffImageParser tiffImageParser = new TiffImageParser();
tiffImageParser.writeImage(image, new FileOutputStream(path), params);final ImageInfo imageInfo = Imaging.getImageInfo(new File(path));
if (imageInfo != null) {final int xReadDPI = imageInfo.getPhysicalWidthDpi();final int yReadDPI = imageInfo.getPhysicalHeightDpi();System.out.println(xReadDPI);System.out.println(yReadDPI);
}
ps查看下分辨率。确实是300.