栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 下载网络图片,根据字节流判断文件类型,并补充扩展名 通过URL下载网络文件,获取文件流并修改文件名

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 下载网络图片,根据字节流判断文件类型,并补充扩展名 通过URL下载网络文件,获取文件流并修改文件名

参考并感谢 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);
	}

	
	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 = EzFileUtil.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;
	}

	
	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) {
			}
		}

	}

	
	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;
	}

	
	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;
	}

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315611.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号