Use of metadata-extractor to read image EXIF metadata in Android

Source: Internet
Author: User
Tags color gamut

Use of metadata-extractor to read image EXIF metadata in Android

 

I. Introduction

 

Recently used in the development of metadata-extractor-xxx.jar and xmpcore-xxx.jar this thing, simply read a lot of articles to learn, to share and share. Work is often dealing with big pictures, and it is also more beneficial to explore and explore.

 

First, we will introduce what is EXIF and EXIF is the abbreviation of Exchangeable Image File, which is a format specially set for digital camera photos. This format can be used to record attributes of a digital photo, such as the brand and model of the camera, the shooting time of the photo, the aperture size set during shooting, the shutter speed, and ISO. In addition, it can also record the shooting data and the image formatting method, so that it can be output to peripherals compatible with EXIF format, such as photo printers.


Currently, the most common image format that supports EXIF information is JPG. Many image tools can directly display the EXIF information of images, some famous album websites also provide pages for displaying the EXIF information of photos. This article describes how to read the EXIF information of an image in Java, including how to adjust the Image Based on the EXIF information for user browsing.

When you use the BufferedImage class to read a large image, the OutOfMemoryException is often thrown, which is quite painful.

 

BufferedImage image = ImageIO.read(File file);

 

Currently, the most easy-to-use Java package for EXIF information processing isDrew NoakesWrite metadata-extractor. This is a simple Java library that can read metadata (Exif, IPTC, XMP, ICC, etc.) from image files. It is easy to use:

 

Metadata metadata = ImageMetadataReader.readMetadata(imagePath);

 

This library can understand metadata in multiple formats, many of which can exist in a single image:
Exif, IPTC, XMP, JFIF/JFXX, ICC Profiles, Photoshop fields, PNG properties, BMP properties, GIF properties

It can process types of files:JPEG, TIFF, PSD, PNG, BMP, GIF, Camera Raw (NEF/CR2/LF/ARW/RW2 /...)

 

Note: Not every JPG image file contains EXIF information. You can click Select image in Windows resource manager. If this image contains EXIF information, the camera model is displayed in the status bar of the window.

 

Ii. sample code and description

The following code prints all the image information containing EXIF.

Example 1 ):

import java.io.File;
    import java.util.Iterator;
     
    import com.drew.imaging.jpeg.JpegMetadataReader;
    import com.drew.metadata.Directory;
    import com.drew.metadata.Metadata;
    import com.drew.metadata.Tag;
    import com.drew.metadata.exif.ExifDirectory;
     
    / **
     * Read EXIF information of pictures
     * /
    public class ExifTest {
        
         public static void main (String [] args) throws Exception {
             
             // Image address containing EXIF information
             File jpegFile = new File (D: \ XXXX \ XXXX \ XXXX.JPG);
             
             Metadata metadata = JpegMetadataReader.readMetadata (jpegFile);
             
             Directory exif = metadata.getDirectory (ExifDirectory.class);
             
             Iterator tags = exif.getTagIterator ();
             
             while (tags.hasNext ()) {
                 
                 Tag tag = (Tag) tags.next ();
                 
                 System.out.println (tag);
                 
             }
         }
    }

 

Example 2 :)

public static void main (String [] args) throws Exception {

        File mFile = new File (F: /XXX.JPG);
        Metadata metadata = ImageMetadataReader.readMetadata (mFile);
        for (Directory directory: metadata.getDirectories ()) {

            if (ExifSubIFDDirectory.equalsIgnoreCase (directory.getClass (). getSimpleName ())) {

                // F-number of the aperture = focal length of the lens / diameter of the lens aperture
                System.out.println (Aperture value: f / + directory.getString (ExifSubIFDDirectory.TAG_FNUMBER));

                System.out.println (Exposure time: + directory.getString (ExifSubIFDDirectory.TAG_EXPOSURE_TIME) + seconds);
                System.out.println (ISO speed: + directory.getString (ExifSubIFDDirectory.TAG_ISO_EQUIVALENT));
                System.out.println (focal length: + directory.getString (ExifSubIFDDirectory.TAG_FOCAL_LENGTH) + mm);

                System.out.println (Photo time: + directory.getString (ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL));
                System.out.println (width: + directory.getString (ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH));
                System.out.println (High: + directory.getString (ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT));

            }

            if (ExifIFD0Directory.equalsIgnoreCase (directory.getClass (). getSimpleName ())) {
                System.out.println (camera manufacturer: + directory.getString (ExifIFD0Directory.TAG_MAKE));
                System.out.println (Camera model: + directory.getString (ExifIFD0Directory.TAG_MODEL));
                System.out.println (horizontal resolution: + directory.getString (ExifIFD0Directory.TAG_X_RESOLUTION));
                System.out.println (vertical resolution: + directory.getString (ExifIFD0Directory.TAG_Y_RESOLUTION));
            }
        }
    }

 

Example 3 ):

 

File mFilePath = C: //XXX.jpg;

     Metadata metadata = com.drew.imaging.jpeg.JpegMetadataReader.readMetadata (mFilePath);

     JpegDirectory jd = (JpegDirectory) metadata.getDirectory (JpegDirectory.class);
     System.out.println (------------ + jd.getImageHeight ()); // The height of the picture
     System.out.println (------------ + jd.getImageWidth ()); // Image width
    
     // Because only the header information of the picture is read, no matter how big the picture can be read, and it is fast.

 

 

You can see the detailed shooting time, camera model, exposure time, aperture value, focal length, ISO value, and so on.


You can also directly specify the value to read any of these parameters. The ExifDirectory class defines manyTAG _An integer constant at the beginning. These constants represent a specific parameter value. For example, to read the camera model, you can obtain them using the following code.

 

Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
        
Directory exif = metadata.getDirectory(ExifDirectory.class);
        
String model = exif.getString(ExifDirectory.TAG_MODEL);

 

The above mentioned is how to obtain the EXIF information of a photo, which contains a very important information-shooting direction. For example, the image shooting direction is Orientation-Top, left side (Horizontal/normal ). When taking a photo, we often choose the camera direction based on different scenes. For example, if we take a tall tree, we will take the camera vertically so that the scenery is suitable for the entire scene frame, however, if you use a normal image browser to view the image, you need to adjust the angle to obtain a normal image.

 

By reading the EXIF information of an image, you can obtain the following result about the shooting direction:Orientation-Left side, bottom (Rotate 270 CW).

The value of Directly Reading The ExitDirectory. TAG_ORIENTATION tag is 8.

Let's take a look at how this project defines these returned values. Open the getOrientationDescription () of the ExifDescriptor class in the source package. The code for this method is as follows:

public String getOrientationDescription() throws MetadataException{
        
        if (!_directory.containsTag(ExifDirectory.TAG_ORIENTATION)) return null;
        
        int orientation = _directory.getInt(ExifDirectory.TAG_ORIENTATION);
        
        switch (orientation) {
            
            case 1: return Top, left side (Horizontal / normal);
            case 2: return Top, right side (Mirror horizontal);
            case 3: return Bottom, right side (Rotate 180);
            case 4: return Bottom, left side (Mirror vertical);
            case 5: return Left side, top (Mirror horizontal and rotate 270 CW);
            case 6: return Right side, top (Rotate 90 CW);
            case 7: return Right side, bottom (Mirror horizontal and rotate 90 CW);
            case 8: return Left side, bottom (Rotate 270 CW);
            default:
                return String.valueOf(orientation);
        }
    }

 

The meaning of each return value can be clearly seen from this method, so that we can rotate the image or process the image based on the actual return value.

 

The following code is used to rotate an image. Other image processing tools such as images can be pushed as follows:

 

String mPath = D: \ XXX.JPG;
    
     File img = new File (mPath);
     BufferedImage old_img = (BufferedImage) ImageIO.read (img);
     int w = old_img.getWidth ();
     int h = old_img.getHeight ();
     
     BufferedImage new_img = new BufferedImage (h, w, BufferedImage.TYPE_INT_BGR);
     Graphics2D g2d = new_img.createGraphics ();
          
     AffineTransform origXform = g2d.getTransform ();
     AffineTransform newXform = (AffineTransform) (origXform.clone ());
     // center of rotation is center of the panel
    
     double xRot = w / 2.0;
     newXform.rotate (Math.toRadians (270.0), xRot, xRot); // rotate 270 degrees
     
     g2d.setTransform (newXform);
     // draw image centered in panel
     g2d.drawImage (old_img, 0, 0, null);
     // Reset to Original
     g2d.setTransform (origXform);
    
     // Write to new file
     FileOutputStream out = new FileOutputStream (D: \ XXX2.jpg);
     try {
         ImageIO.write (new_img, JPG, out);
     } finally {
         out.close ();
     }

 

Note: after rotating the photo using the code above, the EXIF information contained in the original photo will not exist. You can useMediaUtilPackage to write EXIF information to the image file. For more information about how to use this package, see the final link.

You can use the drawImage method of Graphic2D to flip the image mirror:

 

public abstract boolean drawImage(Image img,
            int dx1,int dy1,
            int dx2,int dy2,
            int sx1,int sy1,
            int sx2,int sy2,
            ImageObserver observer);

 

Iii. Additional instructions

 

Explain the actual meanings of some parameters:

 

Make producer refers to the product manufacturer

Model indicates the device Model.

Orientation supports some cameras, and some do not.

X Resolution/Y Resolution X/Y direction Resolution this topic already has a special item to explain this problem

ResolutionUnit resolution unit is generally PPI

The Software displays the Firmware version.

DateTime Date and Time

YCbCrPositioning color phase Positioning

ExifOffsetExif information location, defines the write of Exif information in the file, some software does not show.

ExposureTime: shutter speed

FNumber aperture Coefficient

ISO speed ratings sensitivity

ExifVersionExif version

DateTimeOriginal Creation Time

DateTimeDigitized digitization time

ComponentsConfiguration Image Construction (Multi-finger color combination solution)

CompressedBitsPerPixel (BPP) indicates the degree of compression of each pixel color bit.

ExposureBiasValue exposure compensation.

MaxApertureValue maximum aperture

MeteringMode: Average, central, and point.

Lightsource light source refers to white balance settings

Whether or not Flash is used.

FocalLength focal length. Generally, the physical focal length of the lens is displayed. Some software can define a coefficient to display the author's mark, description, and record of the MakerNote (User Comment) equivalent to the focal length of 35mm cameras.

FlashPixVersionFlashPix version (supported by some models)

ColorSpace Color Gamut and Color Space

ExifImageWidth (Pixel X Dimension) Image Width refers to the number of horizontal dimensions

ExifImageLength (Pixel Y Dimension) Image Height refers to the number of vertical dimensions

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.