编程语言
首页 > 编程语言> > 【Java】http/https/ftp路径的图片转base64

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

标签:httpsConn,ftp,http,String,url,imageUrl,base64,new,public
来源: https://blog.csdn.net/qq_21084687/article/details/116663303