java获取图片dpi
时间: 2023-12-03 15:40:08 浏览: 265
以下是Java获取图片dpi的代码示例:
```java
import org.apache.commons.imaging.ImageReadException;import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.ImageMetadata;
import org.apache.commons.imaging.common.RationalNumber;
import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
import org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants;
import org.apache.commons.imaging.formats.tiff.fieldtypes.FieldType;
import org.apache.commons.imaging.formats.tiff.taginfos.TagInfo;
import java.io.File;
import java.io.IOException;
public class GetImageDpi {
public static void main(String[] args) throws IOException, ImageReadException {
File file = new File("test.jpg");
ImageMetadata metadata = Imaging.getMetadata(file);
if (metadata instanceof JpegImageMetadata) {
JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
TiffImageMetadata exif = jpegMetadata.getExif();
if (exif != null) {
TagInfo tagInfo = TiffTagConstants.TIFF_TAG_XRESOLUTION;
FieldType fieldType = tagInfo.getDataType().getFieldType();
RationalNumber rationalNumber = exif.getRational(tagInfo);
if (rationalNumber != null) {
int dpi = rationalNumber.intValue();
System.out.println("DPI: " + dpi);
}
}
}
}
}
```
阅读全文