Java后端上传手机拍摄图片矫正方向

本文介绍了一种用于自动校正手机拍摄图片方向的方法。通过读取图片的EXIF信息,判断图片的旋转角度,并使用Java图形库进行旋转处理,确保图片在显示时方向正确。该方法适用于处理用户上传的图片,特别是来自不同手机设备的照片。
package useractivity.utils;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectoryBase;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leo
 * @version 2018/11/28 11:01
 * @Description 矫正手机拍摄图片方向问题
 */
public class RotateImage {

    private static Logger logger = Logger.getLogger(RotateImage.class);

    /**
     * 调整手机上传的图片方向
     *
     * @param userHeadImage
     * @param userHeadImage
     * @return
     */
    public static Map rotate(MultipartFile userHeadImage) {
        Image src = null;
        int angel = 0;
        try {
            src = ImageIO.read(userHeadImage.getInputStream());
            File file = File.createTempFile("tmp", null);
            userHeadImage.transferTo(file);
            file.deleteOnExit();
            angel = getRotateAngleForPhoto(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // calculate the new image size
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);

        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // transform
        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);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        try {
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);

            //scaledImage1为BufferedImage,jpg为图像的类型
            ImageIO.write(res, "jpg", imOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("转换工具类中图片大小" + bs.size());
        InputStream is = new ByteArrayInputStream(bs.toByteArray());
        result.put("is", is);
        result.put("size", bs.size());
        return result;
    }

    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // if angel is greater than 90 degree, we need to do some conversion
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }

    public static int getRotateAngleForPhoto(File file) {
        int angle = 0;
        Metadata metadata;
        try {
            metadata = ImageMetadataReader.readMetadata(file);
            Directory directory = metadata.getFirstDirectoryOfType(ExifDirectoryBase.class);
            if (directory.containsTag(ExifDirectoryBase.TAG_ORIENTATION)) {

                // Exif信息中方向  
                int orientation = directory.getInt(ExifDirectoryBase.TAG_ORIENTATION);

                // 原图片的方向信息
                if (6 == orientation) {
                    //6旋转90
                    angle = 90;
                } else if (3 == orientation) {
                    //3旋转180
                    angle = 180;
                } else if (8 == orientation) {
                    //8旋转90
                    angle = 270;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return angle;
    }
}

 

在使用Python进行图片方向矫正及位置调整时,可以借助一些流行的图像处理库,如Pillow(PIL的扩展)和OpenCV(Open Source Computer Vision Library)。这些库提供了丰富的功能,能够轻松实现图像旋转、翻转、裁剪、缩放等操作。 ### 图像方向矫正 图像方向矫正通常涉及旋转或翻转操作,以使图像达到正确的方向。以下是使用Pillow和OpenCV进行方向矫正的方法: #### 使用Pillow进行方向矫正 Pillow库提供了`rotate`和`transpose`方法来进行图像旋转和翻转。 ```python from PIL import Image # 打开图像文件 img = Image.open('example.jpg') # 旋转图像(例如旋转90度) rotated_img = img.rotate(90) # 顺时针旋转90度 rotated_img.save('rotated_example.jpg') # 翻转图像(水平或垂直) flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT) # 水平翻转 flipped_img.save('flipped_example.jpg') ``` #### 使用OpenCV进行方向矫正 OpenCV提供了`flip`函数来翻转图像,并且可以通过`warpAffine`函数实现更复杂的旋转操作。 ```python import cv2 import numpy as np # 读取图像 img = cv2.imread('example.jpg') # 旋转图像(例如绕中心旋转90度) (h, w) = img.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, 90, 1.0) # 90度旋转 rotated_img = cv2.warpAffine(img, M, (w, h)) cv2.imwrite('rotated_opencv_example.jpg', rotated_img) # 翻转图像(1表示水平翻转,0表示垂直翻转,-1表示两者都翻转) flipped_img = cv2.flip(img, 1) cv2.imwrite('flipped_opencv_example.jpg', flipped_img) ``` ### 图像位置调整 图像位置调整通常包括裁剪、缩放和平移操作。以下是如何使用Pillow和OpenCV进行这些操作的方法: #### 裁剪图像 ##### Pillow ```python # 裁剪图像(指定裁剪区域 (left, upper, right, lower)) cropped_img = img.crop((100, 100, 400, 400)) # 示例裁剪区域 cropped_img.save('cropped_example.jpg') ``` ##### OpenCV ```python # 裁剪图像(通过数组切片) cropped_img = img[100:400, 100:400] # 示例裁剪区域 cv2.imwrite('cropped_opencv_example.jpg', cropped_img) ``` #### 缩放图像 ##### Pillow ```python # 缩放图像(指定新的尺寸) resized_img = img.resize((200, 200)) # 将图像缩放到200x200像素 resized_img.save('resized_example.jpg') ``` ##### OpenCV ```python # 缩放图像(指定新的尺寸) resized_img = cv2.resize(img, (200, 200)) # 将图像缩放到200x200像素 cv2.imwrite('resized_opencv_example.jpg', resized_img) ``` #### 平移图像 ##### OpenCV ```python # 平移图像(通过仿射变换矩阵) M = np.float32([[1, 0, 50], [0, 1, 30]]) # 向右平移50像素,向下平移30像素 translated_img = cv2.warpAffine(img, M, (w, h)) cv2.imwrite('translated_opencv_example.jpg', translated_img) ``` ### 总结 Python中的Pillow和OpenCV库都提供了强大的图像处理功能,能够轻松实现图像的方向矫正和位置调整。根据具体需求选择合适的库和方法即可。Pillow更适合简单的图像处理任务,而OpenCV则更适合需要高性能和复杂操作的应用场景。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值