參考資料:https://www.jianshu.com/p/ad4501db178e/
https://github.com/think2011/localResizeIMG
前端圖片校準:
這裏貼出我使用的前端js,需要引入js
<script type="text/javascript" src="redsize/dist/lrz.bundle.js"></script>
//source是我前端進來的圖片資源
var file = source.files[0];
lrz(file).then(function (rst) {
// 處理成功會執行
//res=rst;
//console.log(rst);
// console.log(rst.base64);
})
.catch(function (err) {
// 處理失敗會執行
})
.always(function () {
// 不管是成功失敗,都會執行
});
下面貼出需要的js下載地址:https://download.csdn.net/download/weixin_42102798/12026883
後端圖片校準:
前端不保證完全都能成功,我嘗試了一些,有些手機不行。比如手機把攝像頭全部倒過來拍一張(人臉向下),發送倒服務器。發現服務器接收的是向右歪的(人臉向右)。前端好的,可以研究一下exif.js 源碼。
保證決定性,所以後端也有調整歪斜圖片,代碼如下:
第一種方式:
import 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.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.Iterator;
/**
* 圖片旋轉工具類
*/
public class PicUtil {
public static void main(String args[]) {
String src = "C:/Users/Administrator/Desktop/5.jpg";
//獲取圖片旋轉角度
int angel = getRotateAngleForPhoto(src);
System.out.println(">>>>>>>>>>>" + angel);
if (angel > 0) {
rotateImage(new File(src), angel);
}
}
/**
* 判斷圖片是否需要旋轉
*/
public static void judgeRotate(String fileName) {
//獲取圖片旋轉角度
int angel = getRotateAngleForPhoto(fileName);
if (angel > 0 && angel < 360) {
rotateImage(new File(fileName), angel);
}
}
/**
* 圖片翻轉時,計算圖片翻轉到正常顯示需旋轉角度
*/
public static int getRotateAngleForPhoto(String fileName) {
File file = new File(fileName);
int angel = 0;
try {
//核心對象操作對象
Metadata metadata = ImageMetadataReader.readMetadata(file);
//獲取所有不同類型的Directory,如ExifSubIFDDirectory, ExifInteropDirectory, ExifThumbnailDirectory等,這些類均爲ExifDirectoryBase extends Directory子類
//分別遍歷每一個Directory,根據Directory的Tags就可以讀取到相應的信息
int orientation = 0;
Iterable<Directory> iterable = metadata.getDirectories();
for (Iterator<Directory> iter = iterable.iterator(); iter.hasNext(); ) {
Directory dr = iter.next();
if (dr.getString(ExifIFD0Directory.TAG_ORIENTATION) != null) {
orientation = dr.getInt(ExifIFD0Directory.TAG_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();
}
return angel;
}
/**
* 旋轉圖片爲指定角度
*
* @param file 目標圖像
* @param angel 旋轉角度
* @return
*/
public static File rotateImage(File file, final int angel) {
BufferedImage src = null;
try {
src = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
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 bi = new BufferedImage(rect_des.width, 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);
try {
ImageIO.write(bi, "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
// 調用方法輸出圖片文件
// outImage(file.getPath(), bi, (float) 0.5);
return file;
}
/**
* 計算旋轉參數
*/
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));
}
/**
* 將圖片文件輸出到指定的路徑,並可設定壓縮質量
*
* @param outImgPath
* @param newImg
* @param quality
*/
private static void outImage(String outImgPath, BufferedImage newImg, float quality) {
// 判斷輸出的文件夾路徑是否存在,不存在則創建
File file = new File(outImgPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 輸出到文件流
FileChannel fc = null;
try {
FileOutputStream newimage = new FileOutputStream(outImgPath);
//獲取圖片大小
fc = newimage.getChannel();
//1M
if (fc.size() > 1 * 1024 * 1024) {
quality = (float) (1 * 1024 * 1024.00 / fc.size() * 0.5);
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(newImg);
// 壓縮質量
jep.setQuality(quality, true);
encoder.encode(newImg, jep);
newimage.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* * 圖片文件讀取
*
* @param srcImgPath
* @return
*/
public static BufferedImage inputImage(String srcImgPath) {
BufferedImage srcImage = null;
File file = new File(srcImgPath);
try {
// 構造BufferedImage對象
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[5];
in.read(b);
srcImage = ImageIO.read(file);
} catch (IOException e) {
System.out.println("讀取圖片文件出錯!" + e.getMessage());
e.printStackTrace();
}
return srcImage;
}
}
所需要的maven依賴:
<dependency>
<groupId>com.drewnoakes</groupId>
<artifactId>metadata-extractor</artifactId>
<version>2.11.0</version>
</dependency>
第二種方式:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
/**
* Created with IDEA
* author:Jy
* Date:2019/12/11
* Time:9:21
*/
public class IMGTest {
public static int getJpegOrientation(int naturalJpegOrientation, int deviceOrientation) {
return (naturalJpegOrientation+ deviceOrientation) % 360;
}
static byte[] bytes;
public static void main(String[] args){
String src = "C:/Users/Administrator/Desktop/5.jpg";
File file = new File(src);
fileToByte(file);
//System.out.println(bytes.length);
int reg = getNaturalOrientation(bytes);
System.out.println("需要旋轉的角度:"+reg);
}
/**
* 圖片轉byte[]
* @return
*/
public static byte[] fileToByte(File img){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
BufferedImage bi;
bi = ImageIO.read(img);
ImageIO.write(bi, "jpg", baos);
bytes = baos.toByteArray();
System.err.println(bytes.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (baos != null){
try {
baos.close();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
return bytes;
}
/**
* 從底層返回的數據拿到對應的圖片的角度,有些手機hal層會對手機拍出來的照片作相應的旋轉,有些手機不會(比如三星手機)
* @param jpeg
* @return
*/
public static int getNaturalOrientation(byte[] jpeg) {
if (jpeg == null) {
return 0;
}
int offset = 0;
int length = 0;
// ISO/IEC 10918-1:1993(E)
while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
int marker = jpeg[offset] & 0xFF;
// Check if the marker is a padding.
if (marker == 0xFF) {
continue;
}
offset++;
// Check if the marker is SOI or TEM.
if (marker == 0xD8 || marker == 0x01) {
continue;
}
// Check if the marker is EOI or SOS.
if (marker == 0xD9 || marker == 0xDA) {
break;
}
// Get the length and check if it is reasonable.
length = pack(jpeg, offset, 2, false);
if (length < 2 || offset + length > jpeg.length) {
System.out.println( "Invalid length");
return 0;
}
// Break if the marker is EXIF in APP1.
if (marker == 0xE1 && length >= 8 &&
pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
pack(jpeg, offset + 6, 2, false) == 0) {
offset += 8;
length -= 8;
break;
}
// Skip other markers.
offset += length;
length = 0;
}
// JEITA CP-3451 Exif Version 2.2
if (length > 8) {
// Identify the byte order.
int tag = pack(jpeg, offset, 4, false);
if (tag != 0x49492A00 && tag != 0x4D4D002A) {
System.out.println( "Invalid byte order");
return 0;
}
boolean littleEndian = (tag == 0x49492A00);
// Get the offset and check if it is reasonable.
int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
if (count < 10 || count > length) {
System.out.println( "Invalid offset");
return 0;
}
offset += count;
length -= count;
// Get the count and go through all the elements.
count = pack(jpeg, offset - 2, 2, littleEndian);
while (count-- > 0 && length >= 12) {
// Get the tag and check if it is orientation.
tag = pack(jpeg, offset, 2, littleEndian);
if (tag == 0x0112) {
// We do not really care about type and count, do we?
int orientation = pack(jpeg, offset + 8, 2, littleEndian);
System.out.println(orientation);
switch (orientation) {
case 1:
return 0;
case 3:
return 180;
case 6:
return 90;
case 8:
return 270;
}
System.out.println( "Unsupported orientation");
return 0;
}
offset += 12;
length -= 12;
}
}
return 0;
}
private static int pack(byte[] bytes, int offset, int length,
boolean littleEndian) {
int step = 1;
if (littleEndian) {
offset += length - 1;
step = -1;
}
int value = 0;
while (length-- > 0) {
value = (value << 8) | (bytes[offset] & 0xFF);
offset += step;
}
return value;
}
}