Base64Utils.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.ydtech.utils;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.Base64;
  4. /**
  5. * 2021/6/4
  6. **/
  7. public class Base64Utils {
  8. /**
  9. * 判断图片base64字符串的文件格式
  10. *
  11. * @param base64ImgData
  12. * @return
  13. */
  14. public static String checkImageBase64Format(String base64ImgData) {
  15. byte[] b = base64ImgData.getBytes();
  16. String type = "";
  17. if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
  18. type = "bmp";
  19. } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
  20. type = "png";
  21. } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
  22. type = "jpg";
  23. } else {
  24. type = "jpeg";
  25. }
  26. return type;
  27. }
  28. // 加密
  29. public static String getBase64Encode(String str) {
  30. byte[] b = null;
  31. String s = null;
  32. b = str.getBytes(StandardCharsets.UTF_8);
  33. s = Base64.getEncoder().encodeToString(b);
  34. // s = new BASE64Encoder().encode(b);
  35. return s;
  36. }
  37. // 解密
  38. public static String getBase64Decode(String s) {
  39. byte[] b = null;
  40. String result = null;
  41. if (s != null) {
  42. // BASE64Decoder decoder = new BASE64Decoder();
  43. try {
  44. // b = decoder.decodeBuffer(s);
  45. b = Base64.getDecoder().decode(s);
  46. result = new String(b, StandardCharsets.UTF_8);
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. return result;
  52. }
  53. }