生活随笔
收集整理的這篇文章主要介紹了
java网络图片与二进制字符串相互转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
????????public?static?String?getImgeHexString(String?URLName,String?type)?{ ?????String?res?=?null; ?????try?{ ?????????int?HttpResult?=?0;??????????URL?url?=?new?URL(URLName);??????????URLConnection?urlconn?=?url.openConnection();??????????urlconn.connect(); ?????????HttpURLConnection?httpconn?=?(HttpURLConnection)?urlconn; ?????????HttpResult?=?httpconn.getResponseCode(); ?????????System.out.println(HttpResult); ?????????if?(HttpResult?!=?HttpURLConnection.HTTP_OK)??????????????System.out.print("fail"); ?????????else?{ ?????????????BufferedInputStream?bis?=?new?BufferedInputStream(urlconn.getInputStream()); ??????????????BufferedImage?bm?=?ImageIO.read(bis); ?????????????ByteArrayOutputStream?bos?=?new?ByteArrayOutputStream(); ?????????????ImageIO.write(bm,?type,?bos); ?????????????bos.flush(); ?????????????byte[]?data?=?bos.toByteArray(); ??????????????res?=?byte2hex(data); ?????????????bos.close(); ?????????} ?????}?catch?(Exception?e)?{ ?????????e.printStackTrace(); ?????} ?????return?res; ?} ?????????public?static?void?saveImage(String?data,?String?fileName,String?type)?{ ??????BufferedImage?p_w_picpath?=?new?BufferedImage(300,?300,BufferedImage.TYPE_BYTE_BINARY); ?????ByteArrayOutputStream?byteOutputStream?=?new?ByteArrayOutputStream(); ?????try?{ ?????????ImageIO.write(p_w_picpath,?type,?byteOutputStream); ??????????????????byte[]?bytes?=?hex2byte(data); ?????????System.out.println("path:"?+?fileName); ?????????RandomAccessFile?file?=?new?RandomAccessFile(fileName,?"rw"); ?????????file.write(bytes); ?????????file.close(); ?????}?catch?(IOException?e)?{ ?????????e.printStackTrace(); ?????} ?} ????????public?static?byte[]?hex2byte(String?s)?{ ?????byte[]?src?=?s.toLowerCase().getBytes(); ?????byte[]?ret?=?new?byte[src.length?/?2]; ?????for?(int?i?=?0;?i?<?src.length;?i?+=?2)?{ ?????????byte?hi?=?src[i]; ?????????byte?low?=?src[i?+?1]; ?????????hi?=?(byte)?((hi?>=?'a'?&&?hi?<=?'f')???0x0a?+?(hi?-?'a') ?????????????????:?hi?-?'0'); ?????????low?=?(byte)?((low?>=?'a'?&&?low?<=?'f')???0x0a?+?(low?-?'a') ?????????????????:?low?-?'0'); ?????????ret[i?/?2]?=?(byte)?(hi?<<?4?|?low); ?????} ?????return?ret; ?} ????????public?static?String?byte2hex(byte[]?b)?{ ?????char[]?Digit?=?{?'0',?'1',?'2',?'3',?'4',?'5',?'6',?'7',?'8',?'9',?'A', ?????????????'B',?'C',?'D',?'E',?'F'?}; ?????char[]?out?=?new?char[b.length?*?2]; ?????for?(int?i?=?0;?i?<?b.length;?i++)?{ ?????????byte?c?=?b[i]; ?????????out[i?*?2]?=?Digit[(c?>>>?4)?&?0X0F]; ?????????out[i?*?2?+?1]?=?Digit[c?&?0X0F]; ?????} ??????return?new?String(out); ?}? ?
轉載于:https://blog.51cto.com/dreamboy/916888
總結
以上是生活随笔為你收集整理的java网络图片与二进制字符串相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。