java获取图片朝向并旋转

/**
     * 获取图片旋转角度
     */
    public static int rotateAngleForPhoto(String url) {
        int angel = 0;
        try {
            File file = new File(url);
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    if (tag.getTagType() == ExifDirectoryBase.TAG_ORIENTATION) {
                        String description = tag.getDescription();
//						System.out.println(description);
                        if (description.contains("90")) {
                            // 顺时针旋转90度
                            angel = 90;
                        } else if (description.contains("180")) {
                            // 顺时针旋转180度
                            angel = 180;
                        } else if (description.contains("270")) {
                            // 顺时针旋转270度
                            angel = 270;
                        }
                    }
                }
            }
            System.out.println(angel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 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;
    }

依赖jar包:

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

2019-08-03 01:49:04

共有0条评论!

发表评论