- try{
- OutputStream o = response.getOutputStream();
- // 将圖檔轉換成字元串
- File f = new File("f:\\Vista.png");
- FileInputStream fis = new FileInputStream( f );
- byte[] bytes = new byte[fis.available()];
- fis.read(bytes);
- fis.close();
- // 生成字元串
- String imgStr = byte2hex( bytes );
- System.out.println( imgStr);
- // 将字元串轉換成二進制,用于顯示圖檔
- // 将上面生成的圖檔格式字元串 imgStr,還原成圖檔顯示
- byte[] imgByte = hex2byte( imgStr );
- InputStream in = new ByteArrayInputStream( imgByte );
- byte[] b = new byte[1024];
- int nRead = 0;
- while( ( nRead = in.read(b) ) != -1 ){
- o.write( b, 0, nRead );
- }
- o.flush();
- o.close();
- in.close();
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- }
- public static String byte2hex(byte[] b) // 二進制轉字元串
- {
- StringBuffer sb = new StringBuffer();
- String stmp = "";
- for (int n = 0; n < b.length; n++) {
- stmp = Integer.toHexString(b[n] & 0XFF);
- if (stmp.length() == 1){
- sb.append("0" + stmp);
- }else{
- sb.append(stmp);
- }
- return sb.toString();
- }
- public static byte[] hex2byte(String str) { // 字元串轉二進制
- if (str == null)
- return null;
- str = str.trim();
- int len = str.length();
- if (len == 0 || len % 2 == 1)
- byte[] b = new byte[len / 2];
- try {
- for (int i = 0; i < str.length(); i += 2) {
- b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
- }
- return b;
- } catch (Exception e) {
- }