在字节流的byte[]下判断图片文件格式(后缀)与大小


===============================直接截取后缀方式判断文件格式===================================

String originalFileName = MultipartFile.getOriginalFilename();
String substring = originalFileName.substring(originalFileName.lastIndexOf("."));

===============================byte[]方式判断文件格式========================================
import jline.internal.Log;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.io.*;
import java.util.Iterator;

public class TestImage {

public static void main(String[] args) throws IOException {
File sourceImage = new File("d:\\\\test.png");
byte[] imageByte = File2byte(sourceImage);
String strImage = getImageType(imageByte);
Log.info("strImage:"+strImage);
}
/**
* 判断图片文件格式
*
* @param mapObj
* @return
* @throws IOException
*/
public static String getImageType(byte[] mapObj) throws IOException {
// FileOutputStream fout = new FileOutputStream("d:\\test.jpg");
// //将字节写入文件
// fout.write(mapObj);
// fout.close();
//支持的文件类型: ["gif", "jpeg", "jpg", "bmp", "png"],
// if (Base64.decode(requestDTO.getCreditImg()).length > StringUtil.sizeImge) {
//大于1M
// throw new RestException(ErrorDetailEnum.FILE_SIZE_ERROR, WatchLogType.MERCHANTS_IN_CENTER);//文件过大
// }

String type = "";
ByteArrayInputStream bais = null;
MemoryCacheImageInputStream mcis = null;
try {
bais = new ByteArrayInputStream(mapObj);
mcis = new MemoryCacheImageInputStream(bais);
Iterator itr = ImageIO.getImageReaders(mcis);
while (itr.hasNext()) {
ImageReader reader = (ImageReader) itr.next();
String imageName = reader.getClass().getSimpleName();
if (imageName != null) {
if ("GIFImageReader".equals(imageName)) {
type = "gif";
} else if ("JPEGImageReader".equals(imageName)) {
type = "jpg";
} else if ("PNGImageReader".equals(imageName)) {
type = "png";
} else if ("BMPImageReader".equals(imageName)) {
type = "bmp";
} else {
type = "noPic";
}
}
}
} catch (Exception e) {
type = "noPic";
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException ioe) {
type = "noPic";
}
}
if (mcis != null) {
try {
mcis.close();
} catch (IOException ioe) {
type = "noPic";
}
}
}
return type;
}

/**
* 将文件转换成byte数组
* @param filePath
* @return
*/
public static byte[] File2byte(File tradeFile) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}
posted @ 2017-05-06 14:37  Kevin_Zhou_9  阅读(13054)  评论(0编辑  收藏  举报