Java rotating image, java rotating
Package test; import java. awt. dimension; import java. awt. graphics2D; import java. awt. rectangle; import java. awt. image. bufferedImage; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. nio. channels. fileChannel; import java. util. iterator; import org. apache. log4j. logger; impor T com. drew. imaging. imageMetadataReader; import com. drew. metadata. directory; import com. drew. metadata. metadata; import com. drew. metadata. exif. exifIFD0Directory; import com.sun.image.codec.jpeg. imageFormatException; import com.sun.image.codec.jpeg. export codec; import com.sun.image.codec.jpeg. export encodeparam; import com.sun.image.codec.jpeg. required imageencoder; public class Test {private static Logger logger = Lo Gger. getLogger (Test. class); public static void main (String args []) {String src = "d:/2.jpg"; // get the image rotation angle int angel = getRotateAngleForPhoto (src ); if (angel> 0) {rotateImage (new File (src), angel) ;}}/*** when the image is flipped, rotate the calculated image to the normal display. */public static int getRotateAngleForPhoto (String fileName) {File file = new File (fileName); int angel = 0; InputStream is = null; try {is = new FileInputStream (file);} catch (FileNot FoundException e1) {e1.printStackTrace ();} try {// core object operation object Metadata metadata = ImageMetadataReader. readMetadata (is); // obtain all different types of directories, such as ExifSubIFDDirectory, ExifInteropDirectory, and ExifThumbnailDirectory. These classes are the ExifDirectoryBase extends Directory subclass. // traverse each Directory separately, according to the Tags of Directory, you can read the corresponding information int orientation = 0; Iterable <Directory> iterable = metadata. getDirectories (); for (Iterator <Directory> iter = I Terable. iterator (); iter. hasNext ();) {Directory dr = iter. next (); if (dr. getString (ExifIFD0Directory. TAG_ORIENTATION )! = Null) {orientation = dr. getInt (ExifIFD0Directory. TAG_ORIENTATION);} logger. debug ("orientation =" + orientation);/* Collection <Tag> tags = dr. getTags (); for (Tag tag: tags) {System. out. println (tag. getTagName () + ":" + tag. getDescription ();} */} if (orientation = 0 | orientation = 1) {angel = 360;} else if (orientation = 3) {angel = 180;} else if (orientation = 6) {angel = 90;} else if (orientation = 8) {angel = 270;} Catch (Exception e) {e. printStackTrace ();} logger.info ("image rotation angle:" + angel); return angel ;} /*** rotate the image to the specified angle ** @ param bufferedimage * Target Image * @ param degree * Rotation Angle * @ return */public static File rotateImage (File file, final int angel) {BufferedImage src = InputImage (file. getPath (); BufferedImage bi = null;/* int w = bufferedimage. getWidth (); int h = bufferedimage. getHeight (); int type = bufferedimage. g EtColorModel (). getTransparency (); BufferedImage img; Graphics2D graphics2d; (graphics2d = (img = new BufferedImage (w, h, type )). createGraphics ()). setRenderingHint (RenderingHints. KEY_INTERPOLATION, RenderingHints. VALUE_INTERPOLATION_BILINEAR); graphics2d. rotate (Math. toRadians (degree), w * 0.99, h * 0.99); graphics2d. drawImage (bufferedimage, 0, 0, null); graphics2d. dispose (); */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); bi = new BufferedImage (vertex, rect_des.height, BufferedImage. TYPE_INT_RGB); Graphics2D g2 = bi. 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); // call the method to output the image file OutImage (file. getPath (), bi, (float) 0.5); return file;}/*** calculate the Rotation Parameter */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/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);}/*** output the image file to the specified path, you can also set the compression quality ** @ param outImgPath * @ param newImg * @ param per */private static void OutImage (String outImgPath, Buffe RedImage newImg, float per) {// determine whether the Output Folder path exists. if not, Create File file = new File (outImgPath); if (! File. getParentFile (). exists () {file. getParentFile (). mkdirs ();} // output to the file stream FileChannel fc = null; try {FileOutputStream newimage = new FileOutputStream (outImgPath); // obtain the image size fc = newimage. getChannel (); logger.info ("image size:" + fc. size ()/1024/1024 + "M"); if (fc. size ()> 1*1024*1024) {// 1 Mper = (float) (1*1024*1024.00/fc. size () * 0.5);} required imageencoder encoder = required codec. createJPEGEncoder (newimage); JPEGEncodeParam j Ep = required codec. getdefajpegjpegencodeparam (newImg); // Compression Quality jep. setQuality (per, true); encoder. encode (newImg, jep); newimage. close ();} catch (FileNotFoundException e) {logger. error (e); // TODO Auto-generated catch blocke. printStackTrace ();} catch (ImageFormatException e) {logger. error (e); // TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {logger. error (e); // TODO Auto-generated Catch blocke. printStackTrace () ;}/ ***** read image files ** @ param srcImgPath * @ return */public static BufferedImage InputImage (String srcImgPath) {// logger. debug (srcImgPath); BufferedImage srcImage = null; File file = new File (srcImgPath); try {// construct the BufferedImage object FileInputStream in = new FileInputStream (file ); byte [] B = new byte [5]; in. read (B); srcImage = javax. imageio. imageIO. read (file);} catch (IOExcepti On e) {System. out. println ("An error occurred while reading the image file! "+ E. getMessage (); e. printStackTrace ();} return srcImage ;}}
Attachment download (metadata-extractor-2.8.1.jar, xmpcore-5.1.2.jar)