【Java】http/https/ftp路径的图片转base64

2021/5/11 20:27:24

本文主要是介绍【Java】http/https/ftp路径的图片转base64,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用方式

String base64 = ImageUtil.transToBase64("http://xxxx.jepg", "utf-8");

代码实现

主要工具类ImageUtil.java
:提供图片url转base64功能

@Slf4j
public class ImageUtil {
	// 图片url转base64
	public static String transToBase64(String url, String charsetName) {
		byte[] data = getImageFromUrl(url, charsetName);
		return org.apache.commons.codec.binary.Base64.encodeBase64String(data);
	}
	
	public static byte[] getImageFromUrl(String imageUrl, String charsetName) {
		InputStream inputStream = null;
		try {
			imageUrl = ChineseToUtil.chineseToUrls(imageUrl, charsetName);
			log.info("转码后的url: {}", imageUrl);

			URL url = new URL(imageUrl);
			if (imageUrl.startsWith("ftp")) {
				inputStream = url.openStream();
			} else if (imageUrl.startsWith("https")) {
				inputStream = HttpsUtils.getHttpsFile(imageUrl);
			} else {
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(500);
				inputStream = conn.getInputSteam();
			}
			return readInputStream(inputStream);
		}
	}
}

依赖方法类1 ChineseToUrl.java
:处理路径中的中文字符。

/**
* 汉字转url码
*/
@Slf4j
public class ChineseToUrl {
	public static String chineseToUrls(Strint s, String charsetName) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c  <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					// 指定需要的编码类型
					b = String.valueOf(c).getBytes(charsetName);
				} catch (Exception ex) {
					log.error("", ex);
					b = new byte[0];
				}

				for (byte aB : b) {
					int k = aB;
					if (k < 0) {
						k += 256;
					}
					sb.append("%").append(Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
}

依赖方法类2 HttpsUtils.java
:避开信任证书验证获取https输入流。

public class HttpsUtils {
	public static InputStream getHttpsFile(String fileUrl) throw IOException,
			NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
		// 创建SSLContext对象,使用指定的信任管理器初始化
		TrustManager[] tm = {new MyX509TrustManager()};
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		
		URL url = new URL(fileUrl);
		HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
		httpsConn.setSSLSocketFactory(ssf);
		httpsConn.setDoInput(true);     # 打开输入流
		httpsConn.setDoOutput(true);    # 打开输出流
		return httpsConn.getInputStream();
	}
}

依赖类3 MyX509TrustManager.java
:自定义信任管理器

public class MyX509TrustManager implements X509TrustManager {
	@Override
	pulic void checkClientTrusted(X509Certificate[] xs, String s) {}
	
	@Override
	pulic void checkServerTrusted(X509Certificate[] xs, String s) {}

	@Override
	public X509Certificate[] getAcceptedIssusers() {
		return null;
	}
}


这篇关于【Java】http/https/ftp路径的图片转base64的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程