是否有用于以90度为增量旋转JPEG文件的Java库,而不会导致图像质量下降?
我发现了这个:http://mediachest.sourceforge.net/mediautil/
API:http://mediachest.sourceforge.net/mediautil/javadocs/mediautil/image/jpeg/LLJTran.html
以Henry的答案为基础,这是一个如何使用MediaUtil根据EXIF数据执行无损JPEG旋转的示例:
try { // Read image EXIF data LLJTran llj = new LLJTran(imageFile); llj.read(LLJTran.READ_INFO, true); AbstractImageInfo> imageInfo = llj.getImageInfo(); if (!(imageInfo instanceof Exif)) throw new Exception("Image has no EXIF data"); // Determine the orientation Exif exif = (Exif) imageInfo; int orientation = 1; Entry orientationTag = exif.getTagValue(Exif.ORIENTATION, true); if (orientationTag != null) orientation = (Integer) orientationTag.getValue(0); // Determine required transform operation int operation = 0; if (orientation > 0 && orientation < Exif.opToCorrectOrientation.length) operation = Exif.opToCorrectOrientation[orientation]; if (operation == 0) throw new Exception("Image orientation is already correct"); OutputStream output = null; try { // Transform image llj.read(LLJTran.READ_ALL, true); llj.transform(operation, LLJTran.OPT_DEFAULTS | LLJTran.OPT_XFORM_ORIENTATION); // Overwrite original file output = new BufferedOutputStream(new FileOutputStream(imageFile)); llj.save(output, LLJTran.OPT_WRITE_ALL); } finally { IOUtils.closeQuietly(output); llj.freeMemory(); } } catch (Exception e) { // Unable to rotate image based on EXIF data ... }
关于EXIF数据的问题不一定正确处理,因为EXIF数据在许多情况下都无关紧要,这里的示例代码仅演示了LLJTran无损JPEG旋转功能(感谢user113215):
final File SrcJPEG = new File("my-input.jpg"); final File DestJPEG = new File("my-output.jpg"); final FileInputStream In = new FileInputStream(SrcJPEG); try { final LLJTran LLJT = new LLJTran(In); LLJT.read(LLJTran.READ_ALL, true); LLJT.transform(LLJTran.ROT_90); final FileOutputStream Out = new FileOutputStream(DestJPEG); try { LLJT.save(Out, LLJTran.OPT_WRITE_ALL); } finally { Out.close(); } } finally { In.close(); }
如果你让输入和输出File
对象引用同一个文件,你可以一遍又一遍地运行它,并观察图像不会降低,无论它经过多少次迭代.