base64加密,解密网络图片

1.遇到问题:图片显示不全,已经解决,因为网络传输图片时如果图片过大会分多次进行传输

package com.sp.util.secret;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * base64加密解密
 * 
 * @author hex
 * @version 1.0 2019年10月15日 下午12:24:13
 */
public class Base64Utils {
	private static final Logger log = LoggerFactory.getLogger(Base64Utils.class);
	/**
	 * 加密网络图片路径即可
	 * @author hex
	 * @version 1.0 2019年10月15日 下午12:27:03
	 */

	public static String encode(String filePath) {

		InputStream inStream = null;
		String encodeBase64String = null;
		byte[] result = null;
		try {
			// new一个URL对象
			URL url = new URL(filePath);
			// 打开链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方式为"GET"
			conn.setRequestMethod("GET");
			// 超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			conn.setRequestProperty("Accept-Encoding", "identity");
			conn.connect();

			inStream = conn.getInputStream();
			int count = conn.getContentLength();// 获取远程资源长度
			log.info("资源的总长度为:"+count);
			result = new byte[count];
			int readCount = 0;
			while (readCount < count) {// 循环读取数据,否则会图片显示不全
				readCount += inStream.read(result, readCount, count - readCount);
			}
			encodeBase64String = Base64.encodeBase64String(result);
			log.info("转化后的字符串为" + encodeBase64String);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return encodeBase64String;
	}

	/**
	 * 解密提供图片加密后字符串即可,返回byte数组,可以使用
	 * 
	 * @author hex
	 * @version 1.0 2019年10月15日 下午12:27:03
	 */
	public static byte[] decode(String pic) {
		return Base64.decodeBase64(pic);
	}

	public static void main(String[] args) throws IOException {
		String encode = encode(
				"http://18_fd_d2_0_13_82.tdzntech.com:9898/ftpdir/pic/Recognize/20191015/192.168.1.120_2019101513095100000_5086.jpg");
		System.out.println(encode);
		byte[] decode = decode(encode);
		// new一个文件对象用来保存图片,默认保存当前工程根目录
		File imageFile = new File("d://qr.jpg");
		// 创建输出流
		FileOutputStream outStream = new FileOutputStream(imageFile);
		// 写入数据
		outStream.write(decode);
		// 关闭输出流
		outStream.close();

	}
}
发布了55 篇原创文章 · 获赞 17 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/he_xiao123/article/details/102566805