图片与字符串互相转换

 图片文件-----》字符串  :图片需要先读取成byte[] ,再使用BASE64将byte[] 编码后成为字符串;

字符串-----》图片文件 :先将字符串使用Base64解码得到byte[] ,然后写出成为文件;

package com.test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

public class Test {

	public static void main(String[] args) throws IOException {
		String path = "D:\\B_Link.png"; // 图片资源路径
		File file = new File(path);
		String imageStr = getImageStr(file);
		System.out.println("BASE64后的图片字符串:" + imageStr);

		File imageFile = getImageFile(imageStr);
		System.out.println(imageFile.getAbsolutePath());

	}

	public static String getImageStr(File imageFile) {
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(imageFile));
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			String imageStr = new String(Base64.getEncoder().encode(data));
			return imageStr;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static File getImageFile(String imageStr) {
		File file = new File("D:\\" + System.currentTimeMillis() + ".png");
		try {
			OutputStream out = new FileOutputStream(file);
			byte[] data = Base64.getDecoder().decode(imageStr);
			out.write(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

}

猜你喜欢

转载自blog.csdn.net/yk614294861/article/details/82803493