1. <dependency>
    2. <groupId>com.google.api-client</groupId>
    3. <artifactId>google-api-client</artifactId>
    4. <version>1.32.2</version>
    5. </dependency>
    1. import java.io.FileInputStream;
    2. import java.io.FileNotFoundException;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.OutputStream;
    7. import com.google.api.client.util.Base64;
    8. public class Base64Utils {
    9. /**
    10. * 图片转化成base64字符串
    11. * @param imgPath
    12. * @return string
    13. */
    14. public static String imageToBase64(String imgPath) {
    15. String imgFile = imgPath;// 待处理的图片
    16. InputStream in = null;
    17. byte[] data = null;
    18. String encode = null; // 返回Base64编码过的字节数组字符串
    19. // 对字节数组Base64编码
    20. try {
    21. // 读取图片字节数组
    22. in = new FileInputStream(imgFile);
    23. data = new byte[in.available()];
    24. in.read(data);
    25. encode = Base64.encodeBase64String(data);
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. } finally {
    29. try {
    30. in.close();
    31. } catch (IOException e) {
    32. // TODO Auto-generated catch block
    33. e.printStackTrace();
    34. }
    35. }
    36. return encode;
    37. }
    38. /**
    39. * base64字符串转化成图片
    40. * @param imgData 图片Base64编码
    41. * @param imgFilePath 存放到本地路径
    42. * @return bool
    43. * @throws IOException
    44. */
    45. public static boolean base64ToImage(String imgData, String imgFilePath) throws IOException {
    46. if (imgData == null) // 图像数据为空
    47. return false;
    48. OutputStream out = null;
    49. try {
    50. out = new FileOutputStream(imgFilePath);
    51. // Base64解码
    52. byte[] b = Base64.decodeBase64(imgData);
    53. for (int i = 0; i < b.length; ++i) {
    54. if (b[i] < 0) {// 调整异常数据
    55. b[i] += 256;
    56. }
    57. }
    58. out.write(b);
    59. } catch (FileNotFoundException e) {
    60. // TODO Auto-generated catch block
    61. e.printStackTrace();
    62. } catch (IOException e) {
    63. // TODO Auto-generated catch block
    64. e.printStackTrace();
    65. } finally {
    66. out.flush();
    67. out.close();
    68. return true;
    69. }
    70. }
    71. }