溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串

發(fā)布時(shí)間:2021-02-22 17:38:28 來源:億速云 閱讀:296 作者:戴恩恩 欄目:編程語言

這篇文章主要介紹了如何在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)文章希望大家以后多多支持億速云!

向AI問一下細(xì)節(jié)

免責(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)容。

AI