Base64工具类(JAVA&JS)
JAVA:
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; } }
JS:
<script type="text/javascript"> function test() { var url = "1.png";//这是站内的一张图片资源,采用的相对路径 convertImgToBase64(url, function (base64Img) { //转化后的base64 document.write(base64Img); }); } //实现将项目的图片转化成base64 function convertImgToBase64(url, callback, outputFormat) { var canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function () { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url; } </script>