先是读取照片
package com.fh.util;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Picture {
/**
* 读取指定图片
*/
public BufferedImage getPicture(String name) {
BufferedImage bi = null;
try{
File file = new File(name);
if(!file.exists()){
return null;
}
bi = ImageIO.read(file);
} catch (Exception e){
e.printStackTrace();
}
return bi;
}
}
然后计算读取照片的旋转角度
package com.fh.util;
import java.io.File;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectory;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference.Metadata;
public class RotateAngleForPhoto{
/**
* 图片翻转时,计算图片翻转到正常显示需旋转角度
*/
public int getRotateAngleForPhoto(String fileName){
File file = new File(fileName);
int angel = 0;
com.drew.metadata.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
angel = 90;
}else if( 3 == orientation){
//3旋转180
angel = 180;
}else if( 8 == orientation){
//8旋转90
angel = 270;
}
}
} catch(JpegProcessingException e){
e.printStackTrace();
} catch(MetadataException e){
e.printStackTrace();
}
/*logger.info("图片旋转角度:" + angel);*/
return angel;
}
}
计算旋转参数再去旋转
package com.fh.util;
import java.awt.Dimension;
import java.awt.Rectangle;
public class CalcRotated {
/**
* 计算旋转参数
*/
public static Rectangle CalcRotatedSize(Rectangle src,int angel){
// if angel is greater than 90 degree,we need to do some conversion.
if(angel!=180){
if(angel > 90){
if(angel / 9%2 ==1){
int temp = src.height;
src.height = src.width;
src.width = temp;
}
angel = angel % 90;
}
if(angel ==0){
int temp = src.height;
src.height = src.width;
src.width = temp;
angel = angel % 90;
}
}else{
if(angel > 90){
if(angel / 9%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 java.awt.Rectangle(new Dimension(des_width, des_height));
}
}