java将jpg文件转化为base64字节(互转)

package renew1;
import java.io.FileWriter;   
import java.io.File;  
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.codec.binary.Base64;
//https://www.cnblogs.com/jyiqing/p/10256178.html

public class BaseUtil {
	public static String filePath = "D:\\test_1.txt";
	
	public static void main(String[] args) throws Exception {  
		
		byte[] b1 = image2Bytes("D:\\1.jpg"); //path是绝对路径	
//		System.out.println(new String(b1));
//		System.out.println("*图片的字节数组 = " + Arrays.toString(b1));
		
		byte[] b2 = Base64.encodeBase64(b1);
		
//		System.out.println("编码后的字节数组 = "+Arrays.toString(b2));
//		System.out.println("编码后的字节数组对应的ascil码值 = "+new String(b2));
		
		saveAsFileWriter(new String(b2));//将base64编码的数据保存到文件中
		
//		byte[] b3 = Base64.decodeBase64(b2);	
//		System.out.println("解码后的字节数组 = "+Arrays.toString(b3));		
//		buff2Image(b3, "D:\\2.jpg");

	  }    
	  
	  public static void saveAsFileWriter(String content) {
	        FileWriter fwriter = null;
	        try {
	            // true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好
	            fwriter = new FileWriter(filePath, true);
	            fwriter.write(content);
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        } finally {
	            try {
	                fwriter.flush();
	                fwriter.close();
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	    }
	
	static void buff2Image(byte[] b,String tagSrc) throws Exception {
        FileOutputStream fout = new FileOutputStream(tagSrc);
        //将字节写入文件
        fout.write(b);
        fout.close();
        
    }

	  public static byte[] image2Bytes(String imgSrc) throws Exception {
	      FileInputStream fin = new FileInputStream(new File(imgSrc));
	      //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
	      byte[] bytes  = new byte[fin.available()];
	      //将文件内容写入字节数组,提供测试的case
	      fin.read(bytes);

	      fin.close();
	      return bytes;
	  }
	  	  
}

  

posted @ 2021-11-02 10:22  小晓风  阅读(1205)  评论(0编辑  收藏  举报