您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串,此處給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考價(jià)值,需要的朋友可以參考下:
public static String getImgStr(String imgFile){ //將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對其進(jìn)行Base64編碼處理 InputStream in = null; byte[] data = null; //讀取圖片字節(jié)數(shù)組 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } return new String(Base64.encodeBase64(data)); }
--
利用以上的思路寫的一個(gè)測試
public class ReadImageTest { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(new File("C:\\Users\\luzhifei\\Pictures\\hc_logo.png")); String picStr=""; byte[] read = null; int len = 0; read= new byte[fis.available()]; fis.read(read); String baseStr= Base64.getEncoder().encodeToString(read); //System.out.println( baseStr); byte[] op= Base64.getDecoder().decode(baseStr); // System.out.println(new String(op)); FileOutputStream fos = new FileOutputStream(new File("d:\\temp\\1.jpg")); fos.write(op,0,op.length ); fos.flush(); fos.close(); } }
但是available()有一定的限制。
為了穩(wěn)妥,嚴(yán)重建議采取以下方式:
public static void imageToBase64Str() throws IOException{ FileInputStream fis = new FileInputStream(new File("C:\\Users\\luzhifei\\Pictures\\hc_logo.png")); byte[] read = new byte[1024]; int len = 0; List<byte[]> blist=new ArrayList<byte[]>(); int ttllen=0; while((len = fis.read(read))!= -1){ byte[] dst=new byte[len]; System.arraycopy(read, 0, dst, 0, len); ttllen+=len; blist.add(dst); } fis.close(); byte[] dstByte=new byte[ttllen]; int pos=0; for (int i=0;i<blist.size();i++){ if (i==0){ pos=0; } else{ pos+=blist.get(i-1).length; } System.arraycopy(blist.get(i), 0, dstByte, pos, blist.get(i).length); } String baseStr= Base64.getEncoder().encodeToString(dstByte); byte[] op= Base64.getDecoder().decode(baseStr); FileOutputStream fos = new FileOutputStream(new File("d:\\temp\\2.jpg")); fos.write(op,0,op.length ); fos.flush(); fos.close(); }
到此這篇關(guān)于如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串的文章就介紹到這了,更多相關(guān)的內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。