base64工具类

70 篇文章 1 订阅
package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.alibaba.druid.util.Base64;

/**
 * @description base64工具类
 * @author 
 * 
 */
public class Base64Util {
	 /**
		 * @desctiption base64转图片 (默认存放Tomcat中upload_files下,默认格式png)
		 * @param strBase64(base64),path(相对路径存储路径),filename(文件名,默认为时间戳)
		 * @author 
		 */
	  public static  boolean  base64ToPic(String strBase64,String path,String filename){
			 if(StringUtils.isEmpty(strBase64)){
				   System.out.println("Base64为空");
				   return false; 
			   }
			 Date date = new Date();
			  long datetime =  date.getTime();
			  String catalina_base=System.getProperty("catalina.base");
			  //上传文件保存位置
			  path =catalina_base+"/upload_files/"+path;
			  File f = new File(path);
			  if(!f.exists()){
				f.mkdirs();
			  }
			 Base64 base = new Base64();

			 byte[] b = base.base64ToByteArray(strBase64);
			 for(int i=0;i<b.length;++i){
				 if(b[i]<0){
					 b[i]+=256;
				 }
			 }
			 String imgFilePath = path+"/"+datetime+".png";
			 if(StringUtils.isNotEmpty(filename)){
				    imgFilePath = path+"/"+filename;
			 }
			 try {
				OutputStream out = new FileOutputStream(imgFilePath);
				out.write(b);
				out.flush();
				out.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("Base64转图片失败");
				return false;
			}
		   
		
		    
		   return true;
	 }
	   
	  /**
	 * @desctiption 图片转base64
	 * @param picPath (文件路径)
	 * @author 
	 */
	  public  static  String picToBase64(String picPath){
		
		  File f = new File(picPath);
		  if(!f.isDirectory()){
			  System.out.println("此文件路径无效!");
			  return null;
		  }
		
	    InputStream in = null;
	    byte[] data = null;
	    try {
			in = new FileInputStream(picPath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    Base64 base = new Base64();
	    String base64 = base.byteArrayToBase64(data);
		return base64;
	  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图图小淘气_real

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值