java文件上传
public class ImageAnd64Binary {public static void main(String[] args){String imgSrcPath = "d:/abc/123.jpg"; //生成64編碼的圖片的路徑
String imgCreatePath = "E:\\apache-tomcat-6.0.37\\webapps/pro/ueditor2/jsp/upload1/20140318/480ace2bfc6e44608595bd4adbdeb067.jpg"; //將64編碼生成圖片的路徑
imgCreatePath=imgCreatePath.replaceAll("\\\\", "/");System.out.println(imgCreatePath);String strImg = getImageStr(imgSrcPath);System.out.println(strImg);generateImage(strImg, imgCreatePath);}/**
* 將圖片文件轉化為字節數組字符串,并對其進行Base64編碼處理
* @param imgSrcPath 生成64編碼的圖片的路徑
* @return
*/
public static String getImageStr(String imgSrcPath){InputStream in = null;byte[] data = null;//讀取圖片字節數組
try {in = new FileInputStream(imgSrcPath); data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}//對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);//返回Base64編碼過的字節數組字符串
}/**
* 對字節數組字符串進行Base64解碼并生成圖片
* @param imgStr 轉換為圖片的字符串
* @param imgCreatePath 將64編碼生成圖片的路徑
* @return
*/
public static boolean generateImage(String imgStr, String imgCreatePath){if (imgStr == null) //圖像數據為空
return false;
// 文件夾不存在,創建一個
File file = new File(imgCreatePath);File fileParent = file.getParentFile();
if(!fileParent.exists()){fileParent.mkdirs();}
BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解碼 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i]<0) {//調整異常數據 b[i]+=256; } } OutputStream out = new FileOutputStream(imgCreatePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e){ return false; } } }
BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解碼 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i]<0) {//調整異常數據 b[i]+=256; } } OutputStream out = new FileOutputStream(imgCreatePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e){ return false; } } }
總結
- 上一篇: 学习:二维码、QR码、J4L-QRCod
- 下一篇: 关键词过滤