一、引言

在公司做项目的时候,发现ios端拍的图片会出现宽高不一致的情况,后来才发现其实是需要将其旋转才能获得正确的宽高,下面记录一下解决办法

二、 引入依赖

compile group: 'com.drewnoakes', name: 'metadata-extractor', version: '2.14.0'

三、编写工具类

package album;


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.ExifInteropDirectory;
import org.apache.commons.lang3.StringUtils;


import javax.imageio.*;

import java.awt.*;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;

import java.util.Collection;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageUtils {


    /**
     * 获取图片正确显示需要旋转的角度(顺时针)
     *
     * @param filePath
     * @return
     */
    public static int getRotateAngleForPhoto(String filePath) {
        File file = new File(filePath);
        int angle = 0;
        Metadata metadata;
        try {
            metadata = JpegMetadataReader.readMetadata(file);
            Iterable<Directory> directories = metadata.getDirectories();
            metadata.getFirstDirectoryOfType(ExifInteropDirectory.class);
            for (Directory directory : directories) {
                /*System.out.println(directory);
                Collection<Tag> tags = directory.getTags();
                for (Tag tag : tags) {
                    System.out.println(tag.getTagName()+":"+tag.getDescription());
                }
                System.out.println("-----------------------");*/
                if ("Exif IFD0".equals(directory.getName())) {
                    Collection<Tag> tags = directory.getTags();
                    for (Tag tag : tags) {
                        if ("Orientation".equals(tag.getTagName())) {
                            angle = getNum(tag.getDescription());
                            break;
                        }
                    }
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return angle;
    }

    /**
     * 旋转照片
     *
     * @param fullPath
     * @param angel
     * @return
     */
    public static String rotatePhonePhoto(String fullPath, int angel) {
        BufferedImage src;
        try {
            src = ImageIO.read(new File(fullPath));
            int src_width = src.getWidth(null);
            int src_height = src.getHeight(null);

            int swidth = src_width;
            int sheight = src_height;

            if (angel == 90 || angel == 270) {
                swidth = src_height;
                sheight = src_width;
            }

            Rectangle rect_des = new Rectangle(new Dimension(swidth, sheight));

            BufferedImage res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = res.createGraphics();

            g2.translate((rect_des.width - src_width) / 2,
                    (rect_des.height - src_height) / 2);
            g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

            g2.drawImage(src, null, null);

            ImageIO.write(res, "jpg", new File(fullPath));

        } catch (IOException e) {

            e.printStackTrace();
        }
        return fullPath;
    }


    private static int getNum(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String numStr = m.replaceAll("").trim();
        if (StringUtils.isNotBlank(numStr)) {
            return Integer.valueOf(numStr);
        } else {
            return 0;
        }
    }

    /**
     * 处理ios照片
     *
     * @param filePath
     */
    public static void processIosPhotos(String filePath) {
        //计算旋转的角度
        int angle = getRotateAngleForPhoto(filePath);
        if (angle != 0) {
            rotatePhonePhoto(filePath, angle);
        }
    }

   public static void main(String[] args) throws Exception {
        //不需要旋转
        //String filePath = "C:\\Users\\Administrator\\Desktop\\1598182253HOqheeJY.png";
        //需要旋转90度
        String filePath = "C:\\Users\\Administrator\\Desktop\\微信图片_20200821160115.jpg";
        //需要旋转180度
        //String filePath = "C:\\Users\\Administrator\\Desktop\\1598182214VTZwNVHf.png";
        //安卓照片
        //String filePath = "C:\\Users\\Administrator\\Desktop\\22e2d04abf-6525-4425-b86c-ceacbb2540ab.jpg";
        int angle = getRotateAngleForPhoto(filePath);
        System.out.println("旋转角度:" + angle);
        BufferedImage bufImage = JpegReader.readImage(new File(filePath));
        System.out.println("旋转前的宽高:"+bufImage.getWidth()+"*"+bufImage.getHeight());
        rotatePhonePhoto(filePath,angle);
        BufferedImage bufImage2 = JpegReader.readImage(new File(filePath));
        System.out.println("旋转后的宽高:"+bufImage2.getWidth()+"*"+bufImage2.getHeight());
    }
}

调用processIosPhotos方法就能获得正确方向的图片啦

Q.E.D.


愿你编码半生,归来仍是少年