参考并感谢 Java 读取图片文件的类型(MimeType) - 煮过的花朵 - 博客园
仅针对部分图片格式进行处理,其他文件类型可以自行补充。
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.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class EzImageUtil {
public final static String TYPE_JPEG = "jpeg";
public final static String TYPE_PNG = "png";
public final static String TYPE_GIF = "gif";
public final static String TYPE_WEBP = "webp";
public final static String TYPE_BMP = "bmp";
public final static String TYPE_ICO = "ico";
public static void main(String[] args) throws IOException {
String savePath = "e:/";
String urlStr = "http://图片地址";
String filename = downloadImgFromUrl(urlStr, savePath);
System.out.println(filename);
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream)
throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 从网络Url中下载文件
*/
public static String downloadImgFromUrl(String urlStr, String savePath) throws IOException {
String fileName = UUID.randomUUID().toString().replaceAll("-", "");
if (urlStr.contains("\\u")) {
urlStr = ascii2native(urlStr);
}
System.out.println("info:downloadImgFromUrl " + urlStr);
urlStr = urlStr.replaceAll(" ", "%20").replaceAll("!", "%21").replaceAll("'", "%27").replaceAll("\\(", "%28")
.replaceAll("\\)", "%29").replaceAll("~", "%7E");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Charset", "UTF-8");
// 得到输入流
InputStream inputStream = conn.getInputStream();
// 获取自己数组
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
String filePath = saveDir + File.separator + fileName;
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
String type = readType(filePath);
copyFile(filePath, filePath + "." + type);
ifExistFileDelete(filePath);
return fileName + "." + type;
}
/**
* 读取文件类型
*
* @param filename
* @return
* @throws IOException
*/
private static String readType(String filename) throws IOException {
FileInputStream fis = null;
try {
File f = new File(filename);
if (!f.exists() || f.isDirectory() || f.length() < 8) {
throw new IOException("the file [" + f.getAbsolutePath() + "] is not image !");
}
fis = new FileInputStream(f);
byte[] bufHeaders = readInputStreamAt(fis, 0, 8);
if (isJPEGHeader(bufHeaders)) {
long skiplength = f.length() - 2 - 8; // 第一次读取时已经读了8个byte,因此需要减掉
byte[] bufFooters = readInputStreamAt(fis, skiplength, 2);
if (isJPEGFooter(bufFooters)) {
return "jpeg";
}
}
if (isPNG(bufHeaders)) {
return "png";
}
if (isGIF(bufHeaders)) {
return "gif";
}
if (isWEBP(bufHeaders)) {
return "webp";
}
if (isBMP(bufHeaders)) {
return "bmp";
}
if (isICON(bufHeaders)) {
return "ico";
}
throw new IOException("the image's format is unkown!");
} catch (FileNotFoundException e) {
throw e;
} finally {
try {
if (fis != null)
fis.close();
} catch (Exception e) {
}
}
}
/**
* 标示一致性比较
*
* @param buf
* 待检测标示
* @param markBuf
* 标识符字节数组
* @return 返回false标示标示不匹配
*/
private static boolean compare(byte[] buf, byte[] markBuf) {
for (int i = 0; i < markBuf.length; i++) {
byte b = markBuf[i];
byte a = buf[i];
if (a != b) {
return false;
}
}
return true;
}
/**
*
* @param fis
* 输入流对象
* @param skiplength
* 跳过位置长度
* @param length
* 要读取的长度
* @return 字节数组
* @throws IOException
*/
private static byte[] readInputStreamAt(FileInputStream fis, long skiplength, int length) throws IOException {
byte[] buf = new byte[length];
fis.skip(skiplength); //
fis.read(buf, 0, length);
return buf;
}
// BMP图片文件的前两个字节
private static boolean isBMP(byte[] buf) {
byte[] markBuf = "BM".getBytes();
return compare(buf, markBuf);
}
private static boolean isICON(byte[] buf) {
byte[] markBuf = { 0, 0, 1, 0, 1, 0, 32, 32 };
return compare(buf, markBuf);
}
// WebP图片识别符
private static boolean isWEBP(byte[] buf) {
byte[] markBuf = "RIFF".getBytes();
return compare(buf, markBuf);
}
private static boolean isGIF(byte[] buf) {
// GIF识别符
byte[] markBuf = "GIF89a".getBytes();
if (compare(buf, markBuf)) {
return true;
}
// GIF识别符
markBuf = "GIF87a".getBytes();
if (compare(buf, markBuf)) {
return true;
}
return false;
}
// PNG识别符
private static boolean isPNG(byte[] buf) {
byte[] markBuf = { (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
// new String(buf).indexOf("PNG")>0 //也可以使用这种方式
return compare(buf, markBuf);
}
// JPEG开始符
private static boolean isJPEGHeader(byte[] buf) {
byte[] markBuf = { (byte) 0xff, (byte) 0xd8 };
return compare(buf, markBuf);
}
// JPEG结束符
private static boolean isJPEGFooter(byte[] buf) {
byte[] markBuf = { (byte) 0xff, (byte) 0xd9 };
return compare(buf, markBuf);
}
public static void copyFile(String src, String desc) throws IOException {
FileInputStream input = new FileInputStream(src);
FileOutputStream output = new FileOutputStream(desc);
byte[] b = new byte[1024 * 64];
int len;
while ((len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
public static void ifExistFileDelete(String filename) {
try {
File file = new File(filename);
if (file.exists()) {
FileUtils.forceDelete(file);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String ascii2native(String asciicode) {
String[] asciis = asciicode.split("\\\\u");
String nativeValue = asciis[0];
for (int i = 1; i < asciis.length; i++) {
String code = asciis[i];
try {
nativeValue += (char) Integer.parseInt(code.substring(0, 4), 16);
nativeValue += code.substring(4, code.length());
} catch (Exception e) {
nativeValue += "\\u" + code;
}
}
return nativeValue;
}
}