图片流转base64遇到的坑
生活随笔
收集整理的這篇文章主要介紹了
图片流转base64遇到的坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java學習問題2:網絡傳輸的圖片轉base64遇到的坑
1.之前寫圖片轉base64流的寫法
File file = new File("D:\\test\\img11.jpg");InputStream inputStream = null;BufferedOutputStream bos = null;FileOutputStream outputStream = null;try {//讀取文件轉圖片base64流inputStream = new FileInputStream(file);//inputStream.available()可以在讀寫操作前提前得知數據流有多少字節,初始化byte數組byte[] image = new byte[inputStream.available()];int readBytes = 0;inputStream.read(image);//將圖片轉為base64流BASE64Encoder encoder = new BASE64Encoder();String imageString = encoder.encode(image);//將base64流轉圖片File dir = new File("D:\\test");if(!dir.exists() && dir.isDirectory()){dir.mkdir();}BASE64Decoder decoder = new BASE64Decoder();byte[] outByte = decoder.decodeBuffer(imageString);File outFile = new File("D:\\test\\test1.jpg");outputStream = new FileOutputStream(outFile);bos = new BufferedOutputStream(outputStream);bos.write(outByte);} catch (IOException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (bos != null) {try {bos.close();} catch (IOException e1) {e1.printStackTrace();}}if (outputStream != null) {try {outputStream.close();} catch (IOException e1) {e1.printStackTrace();}}}但是inputStream.available()在網絡傳輸過程中,很有可能返回的是0,非常不靠譜!基本網上都是這個寫法,在本地無論測試多少遍都是ok的。
2.不應該定義數組大小,而是交給緩存數組遍歷while來做,修改后的代碼如下。
InputStream in = null;String imageString = null;byte[] image = null;try {in = new FileInputStream("F:\\xsnasnew\\groupvisit\\actword\\test.jpg");ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int n = 0;while (-1 != (n = in.read(buffer))) {output.write(buffer, 0, n);}image = output.toByteArray();} catch (Exception e) {e.printStackTrace();} finally {if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}}}if(image != null && image.length > 0){BASE64Encoder encoder = new BASE64Encoder();imageString = encoder.encode(image);}總結
以上是生活随笔為你收集整理的图片流转base64遇到的坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git push error:OpenS
- 下一篇: 主观分析法汇总