如果将手机等移动设备中的照片上传至服务器,再显示已上传的图片,可能会有方向不正确的问题,这是因为照片中含有方向信息,它告知你照片是什么方向的,但我们如果没有处理方向,显示就会不正确。如果用正常方法读取已上传照片的宽和高:

BufferedImage p_w_picpath = ImageIO.read(new File(fullPath)); 
int width = p_w_picpath.getWidth();  //图片的宽
int height = height.getHeight();  //图片的高

这样获取出的宽和高,可能不是正确的,因为没有考虑图片的方向信息,简单说,我发现如果是手机,将手机顺时针旋转90度成为横屏,这时候照相,照出的照片,上传到服务器是正常的,也就是说,这时的照片中的方向信息是标准方向,如果你是用手机正常竖屏来照,则需要要把照片旋转90度才和你照照片时方向相同,同理,还有两个方向是需要把照片旋转180度和270度才能够正确显示。

照片的方向信息在图片文件的EXIF信息中,那么只要读取到图片文件的EXIF信息,就能知道需要旋转的角度,那么在上传完成后,把图片再按角度旋转一下重新写到服务器,不就正常了么,我解决这个问题的思路就是这样。

那么,获取图片的EXIF信息,需要使用mediautil-1.0.jar、metadata-extractor-2.3.1.jar,已上传到附件中。获取需要旋转的角度,代码:

/**
     * 获取图片正确显示需要旋转的角度(顺时针)
     * @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);
           
           Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);

           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;
       
   }


这样,手机照片上传上来方向就正常了。