Base64的解释:
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。
public static String imgToBase64(String imgPath, Bitmap bitmap,String imgFormat) { 20. if (imgPath !=null && imgPath.length() > 0) { 21. bitmap = readBitmap(imgPath); 22. } 23. if(bitmap == null){ 24. //bitmap not found!! 25. } 26. ByteArrayOutputStream out = null; 27. try { 28. out = new ByteArrayOutputStream();
//压缩 29. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 30. 31. out.flush(); 32. out.close(); 33. 34. byte[] imgBytes = out.toByteArray(); 35. return Base64.encodeToString(imgBytes, Base64.DEFAULT); 36. } catch (Exception e) { 37. // TODO Auto-generated catch block 38. return null; 39. } finally { 40. try { 41. out.flush(); 42. out.close(); 43. } catch (IOException e) { 44. // TODO Auto-generated catch block 45. e.printStackTrace(); 46. } 47. } 48. } 49. //根据图片路径获得bitmap 50. private static Bitmap readBitmap(String imgPath) { 51. try { 52. return BitmapFactory.decodeFile(imgPath); 53. } catch (Exception e) { 54. // TODO Auto-generated catch block 55. return null; 56. } 57. 58. } 59. 60. /** 61. * 62. * @param base64Data 63. * @param imgName 64. * @param imgFormat 图片格式 65. */ 66. public static void base64ToBitmap(String base64Data,String imgName,String imgFormat) { 67. byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT); 68. Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 69. 70. File myCaptureFile = new File("/sdcard/", imgName); 71. FileOutputStream fos = null; 72. try { 73. fos = new FileOutputStream(myCaptureFile); 74. } catch (FileNotFoundException e) { 75. // TODO Auto-generated catch block 76. e.printStackTrace(); 77. } 78. boolean isTu = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 79. if (isTu) { 80. // fos.notifyAll(); 81. try { 82. fos.flush(); 83. fos.close(); 84. } catch (IOException e) { 85. // TODO Auto-generated catch block 86. e.printStackTrace(); 87. } 88. } else { 89. try { 90. fos.close(); 91. } catch (IOException e) { 92. // TODO Auto-generated catch block 93. e.printStackTrace(); 94. } 95. }