当前位置:   article > 正文

Base64工具类(文件、base64字符串、Bitmap相互转换)

base64工具类
  1. /**
  2. * Author : 马占柱
  3. * E-mail : mazhanzhu_3351@163.com
  4. * Time : 2019/5/19 9:30
  5. * Desc : Base64工具类
  6. */
  7. public class Base64Util {
  8. public static final String TAG = "Base64Util";
  9. private static final char last2byte = (char) Integer.parseInt("00000011", 2);
  10. private static final char last4byte = (char) Integer.parseInt("00001111", 2);
  11. private static final char last6byte = (char) Integer.parseInt("00111111", 2);
  12. private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
  13. private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
  14. private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
  15. private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
  16. //取到 SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
  17. public static String Mzz_File = BaseApplication.getContext().getExternalCacheDir().getAbsolutePath();
  18. public static void gcBitmap(Bitmap bitmap) {
  19. if (bitmap != null && !bitmap.isRecycled()) {
  20. bitmap.recycle(); // 回收图片所占的内存
  21. bitmap = null;
  22. System.gc(); // 提醒系统及时回收
  23. }
  24. }
  25. /**
  26. * Bitmap To Base64
  27. */
  28. public static String bitmapToBase64(Bitmap bitmap) {
  29. // 要返回的字符串
  30. String reslut = null;
  31. ByteArrayOutputStream baos = null;
  32. try {
  33. if (bitmap != null) {
  34. baos = new ByteArrayOutputStream();
  35. //压缩只对保存有效果bitmap还是原来的大小
  36. bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
  37. baos.flush();
  38. baos.close();
  39. // 转换为字节数组
  40. byte[] byteArray = baos.toByteArray();
  41. // 转换为字符串
  42. reslut = Base64.encodeToString(byteArray, Base64.NO_WRAP);
  43. } else {
  44. return null;
  45. }
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. } finally {
  49. try {
  50. if (baos != null) {
  51. baos.close();
  52. }
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. return reslut;
  58. }
  59. /**
  60. * Bitmap To Bitmap
  61. */
  62. public static Bitmap base64ToBitmap(String base64String) {
  63. byte[] decode = Base64.decode(base64String, Base64.DEFAULT);
  64. Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
  65. return bitmap;
  66. }
  67. /**
  68. * Bitmap 转化为 二维数组
  69. */
  70. public static byte[] getBytesByBitmap(Bitmap bitmap) {
  71. try {
  72. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bitmap.getByteCount());
  73. bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
  74. return outputStream.toByteArray();
  75. } catch (Exception e) {
  76. return new byte[10];
  77. }
  78. }
  79. /**
  80. * 文件 转 base64字符串
  81. */
  82. public static String fileToBase64(File file) {
  83. String base64 = null;
  84. try {
  85. InputStream in = new FileInputStream(file);
  86. byte[] bytes = new byte[in.available()];
  87. int length = in.read(bytes);
  88. base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
  89. in.close();
  90. } catch (Exception e) {
  91. }
  92. return base64;
  93. }
  94. /**
  95. * Bitmap 转 文件
  96. */
  97. public static File bitmapToFile(Bitmap bitmap) {
  98. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  99. //第二个参数是压缩比重,图片存储在磁盘上的大小会根据这个值变化。值越小存储在磁盘的图片文件越小,
  100. bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
  101. File fileDir = new File(Base64Util.Mzz_File);
  102. if (!fileDir.exists()) {
  103. fileDir.mkdirs();
  104. }
  105. File file = new File(Mzz_File, System.currentTimeMillis() + "压缩图片_Mzz.jpg");
  106. try {
  107. FileOutputStream fos = new FileOutputStream(file);
  108. InputStream is = new ByteArrayInputStream(baos.toByteArray());
  109. int x = 0;
  110. byte[] b = new byte[1024 * 100];
  111. while ((x = is.read(b)) != -1) {
  112. fos.write(b, 0, x);
  113. }
  114. fos.close();
  115. } catch (Exception e) {
  116. Log_Ma.e(TAG, e.toString());
  117. e.printStackTrace();
  118. }
  119. return file;
  120. }
  121. public static String encode(byte[] from) {
  122. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
  123. int num = 0;
  124. char currentByte = 0;
  125. int i;
  126. for (i = 0; i < from.length; ++i) {
  127. for (num %= 8; num < 8; num += 6) {
  128. switch (num) {
  129. case 0:
  130. currentByte = (char) (from[i] & lead6byte);
  131. currentByte = (char) (currentByte >>> 2);
  132. case 1:
  133. case 3:
  134. case 5:
  135. default:
  136. break;
  137. case 2:
  138. currentByte = (char) (from[i] & last6byte);
  139. break;
  140. case 4:
  141. currentByte = (char) (from[i] & last4byte);
  142. currentByte = (char) (currentByte << 2);
  143. if (i + 1 < from.length) {
  144. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
  145. }
  146. break;
  147. case 6:
  148. currentByte = (char) (from[i] & last2byte);
  149. currentByte = (char) (currentByte << 4);
  150. if (i + 1 < from.length) {
  151. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
  152. }
  153. }
  154. to.append(encodeTable[currentByte]);
  155. }
  156. }
  157. if (to.length() % 4 != 0) {
  158. for (i = 4 - to.length() % 4; i > 0; --i) {
  159. to.append("=");
  160. }
  161. }
  162. return to.toString();
  163. }
  164. /**
  165. * @param key 加密秘钥
  166. * @param filepath 源文件地址
  167. */
  168. public static Map<String, String> IMG_Jiami(int key, String filepath) {
  169. File fileDir = new File(Base64Util.Mzz_File);
  170. if (!fileDir.exists()) {
  171. fileDir.mkdirs();
  172. }
  173. File file = new File(fileDir, System.currentTimeMillis() + "_Mzz.jpg");
  174. String path_jiami;
  175. long available = 0;
  176. try {
  177. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filepath));
  178. available = bis.available();
  179. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getPath()));
  180. int b;
  181. while ((b = bis.read()) != -1) {
  182. bos.write(b ^ key);
  183. }
  184. path_jiami = file.getPath();
  185. bis.close();
  186. bos.close();
  187. } catch (Exception e) {
  188. path_jiami = filepath;
  189. }
  190. Map<String, String> map = new HashMap<>();
  191. map.put("path", path_jiami);
  192. map.put("size", available + "");
  193. return map;
  194. }
  195. /**
  196. * 获取视频封面
  197. */
  198. public static Bitmap getVideoThumb(String path) {
  199. MediaMetadataRetriever media = new MediaMetadataRetriever();
  200. media.setDataSource(path);
  201. return media.getFrameAtTime();
  202. }
  203. /**
  204. * 获取视频时长
  205. */
  206. public static long getLocalVideoDuration(String videoPath) {
  207. int duration;
  208. try {
  209. MediaMetadataRetriever mmr = new MediaMetadataRetriever();
  210. mmr.setDataSource(videoPath);
  211. duration = Integer.parseInt(mmr.extractMetadata
  212. (MediaMetadataRetriever.METADATA_KEY_DURATION));
  213. } catch (Exception e) {
  214. e.printStackTrace();
  215. return 0;
  216. }
  217. return duration;
  218. }
  219. /**
  220. * @return view的截图,在InVisible时也可以获取到bitmap
  221. */
  222. public static Bitmap getViewBitmap(View view) {
  223. view.measure(View.MeasureSpec.makeMeasureSpec(view.getMeasuredWidth(), View.MeasureSpec.EXACTLY),
  224. View.MeasureSpec.makeMeasureSpec(view.getMeasuredHeight(), View.MeasureSpec.EXACTLY));
  225. view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
  226. view.setDrawingCacheEnabled(true);
  227. view.buildDrawingCache(true);
  228. return view.getDrawingCache(true);
  229. }
  230. /**
  231. * 获取系统相册文件路径
  232. */
  233. public static File getDCIMDirectory() {
  234. File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
  235. if (!dcim.exists()) {
  236. dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
  237. }
  238. return dcim;
  239. }
  240. /**
  241. * 根据绝对路径得到图片的宽高,亲测比楼上速度快几十倍
  242. *
  243. * @param path 绝对路径!绝对路径!绝对路径!
  244. * @return 宽高
  245. */
  246. public static int[] getImageWidthHeight(String path) {
  247. try {
  248. BitmapFactory.Options options = new BitmapFactory.Options();
  249. options.inJustDecodeBounds = true;
  250. BitmapFactory.decodeFile(path, options);
  251. return new int[]{options.outWidth, options.outHeight};
  252. } catch (Exception e) {
  253. e.printStackTrace();
  254. }
  255. return new int[]{0, 0};
  256. }
  257. /**
  258. * 根据相对路径获取图片宽高
  259. *
  260. * @param c 上下文
  261. * @param uri 图片uri地址
  262. * @return 宽高信息
  263. */
  264. public static int[] getImageWidthHeight(Context c, Uri uri) {
  265. try {
  266. ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
  267. .openFileDescriptor(uri, "r");
  268. if (parcelFileDescriptor != null) {
  269. FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
  270. Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
  271. parcelFileDescriptor.close();
  272. return new int[]{image.getWidth(), image.getHeight()};
  273. }
  274. } catch (Exception e) {
  275. e.printStackTrace();
  276. }
  277. return new int[]{0, 0};
  278. }
  279. /**
  280. * @param context
  281. * @param filePath 路径
  282. * @param reqWidth 要求压缩的宽
  283. * @param reqHeight 要求压缩的高
  284. * @return
  285. */
  286. public static Bitmap getSmallBitmap(Context context, String filePath, int reqWidth, int reqHeight) {
  287. final BitmapFactory.Options options = new BitmapFactory.Options();
  288. options.inJustDecodeBounds = true;//只解析图片边沿,获取宽高
  289. // 计算缩放比
  290. options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
  291. // 完整解析图片返回bitmap
  292. options.inJustDecodeBounds = false;
  293. return BitmapFactory.decodeFile(filePath, options);
  294. }
  295. /**
  296. * @param context
  297. * @param filePath 路径
  298. * @param reqWidth 要求压缩的宽
  299. * @param reqHeight 要求压缩的高
  300. * @return
  301. */
  302. public static Bitmap getSmallBitmap(Context context, int filePath, int reqWidth, int reqHeight) {
  303. final BitmapFactory.Options options = new BitmapFactory.Options();
  304. options.inJustDecodeBounds = true;//只解析图片边沿,获取宽高
  305. // 计算缩放比
  306. options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
  307. // 完整解析图片返回bitmap
  308. options.inJustDecodeBounds = false;
  309. return BitmapFactory.decodeResource(context.getResources(), filePath, options);
  310. }
  311. public static int calculateInSampleSize(BitmapFactory.Options options,
  312. int reqWidth, int reqHeight) {
  313. final int height = options.outHeight;
  314. final int width = options.outWidth;
  315. int inSampleSize = 1;
  316. if (height > reqHeight || width > reqWidth) {
  317. final int heightRatio = Math.round((float) height / (float) reqHeight);
  318. final int widthRatio = Math.round((float) width / (float) reqWidth);
  319. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  320. }
  321. return inSampleSize;
  322. }
  323. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/202979
推荐阅读
相关标签
  

闽ICP备14008679号