itext 7.1 how to check if image is rotated

倖福魔咒の 提交于 2020-01-14 05:50:09

问题


in itext 7.1, I am adding an image to a pdf document with following code :

Document document = new Document(writerPdf);   //make a new document object
ImageData imgData = ImageDataFactory.create(imageBytes);
Image image = new Image(imgData);
document.add(image);

This works fine for most images but I have come across an image that seems normal on desktop but when adding to pdf it is rotated by -90 .

imgData.getRotation() gives 0 as output

My question is :

  1. how to check if image has any rotation set.

  2. imgData.setRotation(90) does not seem to work for me. How to rotate . Thanks.


回答1:


iText 7 unfortunately in general does not read (or at least not provide) that information, the Rotation property of ImageData currently is only extracted for TIFF files.

If the image has EXIF metadata and the orientation is properly contained in them, though, you can try and read those metadata using an appropriate library and use that orientation for inserting the image using iText.

One such library is Drew Noakes's metadata-extractor, cf. e.g. his answer here. It can be retrieved via maven using

<dependency>
    <groupId>com.drewnoakes</groupId>
    <artifactId>metadata-extractor</artifactId>
    <version>2.11.0</version>
</dependency>

With that dependency available, you can go ahead and try:

Metadata metadata = ImageMetadataReader.readMetadata(new ByteArrayInputStream(imageBytes));
ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
int orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);

double angle = 0;
switch (orientation)
{
case 1:
case 2:
    angle = 0; break;
case 3:
case 4:
    angle = Math.PI; break;
case 5:
case 6:
    angle = - Math.PI / 2; break;
case 7:
case 8:
    angle = Math.PI / 2; break;
}

Document document = new Document(writerPdf);
ImageData imgData = ImageDataFactory.create(imageBytes);
Image image = new Image(imgData);
image.setRotationAngle(angle);
document.add(image);

(from the RecognizeRotatedImage test testOskar)

(For values 2, 4, 5, and 7 one actually also needs to flip the image; for more backgrounds look e.g. here.)

To be safe, consider wrapping the EXIF related code parts in an appropriate try-catch envelope.




回答2:


for anyone else facing this issue , this is response from iText team You will have to write your own logic for this. iText has no way of detecting whether or not your image has been rotated. If your working with portrait images for example, you could create a method that compares the width of the image to its height and rotates it accordingly. However this is out of scope for iText.



来源:https://stackoverflow.com/questions/48509488/itext-7-1-how-to-check-if-image-is-rotated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!