private static IIOMetadata setDPIViaAPI ( IIOMetadata imageMetadata , int dpiX , int dpiY ) throws IIOInvalidTreeException { // Derive the TIFFDirectory from the metadata. TIFFDirectory dir = TIFFDirectory . createFromMetadata ( imageMetadata ) ; // Get {X,Y}Resolution tags. BaselineTIFFTagSet base = BaselineTIFFTagSet . getInstance ( ) ; TIFFTag tagXRes = base . getTag ( BaselineTIFFTagSet . TAG_X_RESOLUTION ) ; TIFFTag tagYRes = base . getTag ( BaselineTIFFTagSet . TAG_Y_RESOLUTION ) ; // Create {X,Y}Resolution fields. TIFFField fieldXRes = new TIFFField ( tagXRes , TIFFTag . TIFF_RATIONAL , 1 , new long [ ] [ ] { { dpiX , 1 } } ) ; TIFFField fieldYRes = new TIFFField ( tagYRes , TIFFTag . TIFF_RATIONAL , 1 , new long [ ] [ ] { { dpiY , 1 } } ) ; // Append {X,Y}Resolution fields to directory. dir . addTIFFField ( fieldXRes ) ; dir . addTIFFField ( fieldYRes ) ; // Convert to metadata object. IIOMetadata metadata = dir . getAsMetadata ( ) ; // Add other metadata. IIOMetadataNode root = new IIOMetadataNode ( "javax_imageio_1.0" ) ; IIOMetadataNode horiz = new IIOMetadataNode ( "HorizontalPixelSize" ) ; horiz . setAttribute ( "value" , Double . toString ( 25.4f / dpiX ) ) ; IIOMetadataNode vert = new IIOMetadataNode ( "VerticalPixelSize" ) ; vert . setAttribute ( "value" , Double . toString ( 25.4f / dpiY ) ) ; IIOMetadataNode dim = new IIOMetadataNode ( "Dimension" ) ; dim . appendChild ( horiz ) ; dim . appendChild ( vert ) ; root . appendChild ( dim ) ; metadata . mergeTree ( "javax_imageio_1.0" , root ) ; return metadata ; }
Set DPI using API .