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();

	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值