java上傳不同類型圖片,儲存資料庫(Base64位元影像轉網狀圖片)

來源:互聯網
上載者:User

標籤:17.   http   異常   字串   name   class   let   data   split   

直接上代碼好不好

方法名:

GenerateImage
傳參:
base64Img:上傳的base64碼
realPath:產生的圖片路徑 
imgTypes :圖片類型

 
String imgBase64 = request.getParameter("userImgbase64");
// 擷取當前伺服器路徑
 String realPath = request.getServletContext().getRealPath("")+"\\img"; 
System.out.println(
realPath ); //  http://192.168.191.1:8080/MyWeb/img


String[] imgType = imgBase64.split(",");

// 擷取圖片類型(如果沒有類型,貌似會報錯)
String imgTypes = imgType[0].toString().substring(11, imgType[0].toString().length()-7);


String userImgbase64 = GenerateImage(imgBase64,realPath,imgTypes);
System.out.println(realPath );   //  http://192.168.191.1:8080/MyWeb/img/1532493648717.png

//
對位元組數組字串進行Base64解碼並產生圖片 public static String GenerateImage(String base64Img,String realPath,String imgTypes ){ String ret_fileName = null; // 臨時檔案路徑 File file_normer = new File(realPath+"/"); if (!file_normer.exists()) { file_normer.mkdirs(); } if (base64Img == null) // 映像資料為空白 return "映像資料為空白"; base64Img = base64Img.replaceAll("data:image/"+imgTypes+";base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] b = decoder.decodeBuffer(base64Img); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常資料 b[i] += 256; } } // 產生jpeg圖片 ret_fileName = System.currentTimeMillis()+"."+imgTypes+""; File file = new File(realPath + "/" + ret_fileName ); OutputStream out = new FileOutputStream(file); out.write(b); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return ret_fileName ; }

 

java上傳不同類型圖片,儲存資料庫(Base64位元影像轉網狀圖片)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.