java獲取圖片朝向並旋轉

	/**
     * 獲取圖片正確顯示需要旋轉的角度(順時針)
     * @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,下載地址:後續補上
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章