package com.qunzhixinxi.hnqz.admin.util;

import cn.hutool.http.HttpUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64Util {
	public static String encode(BufferedImage bufferedImage, String imgType) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, imgType, outputStream);
		return encode(outputStream);
	}

	public static String encode(ByteArrayOutputStream outputStream) {
		return Base64.getEncoder().encodeToString(outputStream.toByteArray());
	}

	/**
	 * 将指定url的图片转换为base64字符串
	 *
	 * @param url
	 * @return
	 */
	public static String picToBase64(String url){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		// false:是否关闭输出流
		HttpUtil.download(url,outputStream,true);

		byte[] bytes = outputStream.toByteArray();

		StringBuffer base64 = new StringBuffer();
		// 用于说明文件格式
		base64.append("data:").append("image/").append(url.substring(url.lastIndexOf(".") + 1)).append(";base64,");
		base64.append(Base64.getEncoder().encodeToString(bytes));
		return base64.toString();
	}

	/**
	 * 将指定url的视频转换为base64字符串
	 *
	 * @param url
	 * @return
	 */
	public static String videoToBase64(String url){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		// false:是否关闭输出流
		HttpUtil.download(url,outputStream,true);

		byte[] bytes = outputStream.toByteArray();

		StringBuffer base64 = new StringBuffer();
		// 用于说明文件格式
		base64.append("data:").append("video/").append(url.substring(url.lastIndexOf(".") + 1)).append(";base64,");
		base64.append(Base64.getEncoder().encodeToString(bytes));
		return base64.toString();
	}
}
