java获取图片朝向并旋转

本文提供了一种方法来解决手机拍摄的照片在不同设备上显示时出现的旋转问题。通过读取JPEG图片的EXIF信息确定正确的旋转角度,并使用Java代码实现图片的旋转修正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	/**
     * 获取图片正确显示需要旋转的角度(顺时针)
     * @return
     */
    public static int getRotateAngleForPhoto(String filePath){
        File file = new File(filePath);
        int angle = 0;
        Metadata metadata;
        try {
            metadata = JpegMetadataReader.readMetadata(file);
            Directory directory = metadata.getDirectory(ExifDirectory.class);
                if(directory.containsTag(ExifDirectory.TAG_ORIENTATION)){ 
                
                  // Exif信息中方向  
                   int orientation = directory.getInt(ExifDirectory.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 (JpegProcessingException e) {
            e.printStackTrace();
        } catch (MetadataException e) {
            e.printStackTrace();
        }
        return angle;
    }/**
     * 旋转照片
     * @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包 mediautil-1.0.jar 和 metadata-extractor-2.3.1.jar,下载地址:后续补上
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值