天天看點

圖檔和字元串互相轉換

  1. try{  
  2.         OutputStream o = response.getOutputStream();  
  3.         // 将圖檔轉換成字元串  
  4.         File f = new File("f:\\Vista.png");  
  5.         FileInputStream fis = new FileInputStream( f );  
  6.         byte[] bytes = new byte[fis.available()];  
  7.         fis.read(bytes);  
  8.         fis.close();  
  9.         // 生成字元串  
  10.         String imgStr = byte2hex( bytes );  
  11.         System.out.println( imgStr);  
  12.         // 将字元串轉換成二進制,用于顯示圖檔  
  13.         // 将上面生成的圖檔格式字元串 imgStr,還原成圖檔顯示  
  14.         byte[] imgByte = hex2byte( imgStr );  
  15.         InputStream in = new ByteArrayInputStream( imgByte );  
  16.         byte[] b = new byte[1024];  
  17.         int nRead = 0;  
  18.         while( ( nRead = in.read(b) ) != -1 ){  
  19.             o.write( b, 0, nRead );  
  20.         }  
  21.         o.flush();  
  22.         o.close();  
  23.         in.close();  
  24.     }catch(Exception e){  
  25.         e.printStackTrace();  
  26.     }finally{  
  27.     }  

  1. public static String byte2hex(byte[] b) // 二進制轉字元串  
  2. {  
  3.    StringBuffer sb = new StringBuffer();  
  4.    String stmp = "";  
  5.    for (int n = 0; n < b.length; n++) {  
  6.     stmp = Integer.toHexString(b[n] & 0XFF);  
  7.     if (stmp.length() == 1){  
  8.         sb.append("0" + stmp);  
  9.     }else{  
  10.         sb.append(stmp);  
  11.    }  
  12.    return sb.toString();  
  13. }  
  14. public static byte[] hex2byte(String str) { // 字元串轉二進制  
  15.     if (str == null)  
  16.      return null;  
  17.     str = str.trim();  
  18.     int len = str.length();  
  19.     if (len == 0 || len % 2 == 1)  
  20.     byte[] b = new byte[len / 2];  
  21.     try {  
  22.      for (int i = 0; i < str.length(); i += 2) {  
  23.       b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();  
  24.      }  
  25.      return b;  
  26.     } catch (Exception e) {  
  27.  }