OpenapiUtil.java 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package com.huimv.admin.common.utils;
  2. import javax.imageio.ImageIO;
  3. import java.awt.image.BufferedImage;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.util.Base64;
  11. import java.util.Base64.Decoder;
  12. import java.util.Base64.Encoder;
  13. /**
  14. * Openapi接口调用过程中会用到的一些工具方法
  15. * @author shengyiling
  16. *
  17. */
  18. public class OpenapiUtil {
  19. /**
  20. * BASE64加密网络图片,返回加密之后的字符串
  21. * @param imageUrl 图片的绝对地址
  22. * @param extensioName 图片的扩展名,例如 jpg、bmp等
  23. * @return 加密之后的字符串
  24. */
  25. public static String encodeImage2Base64(URL imageUrl, String extensioName){
  26. ByteArrayOutputStream outputStream = null;
  27. try {
  28. BufferedImage bufferedImage = ImageIO.read(imageUrl); //读取网络图片
  29. outputStream = new ByteArrayOutputStream(); //文件输出流
  30. ImageIO.write(bufferedImage, extensioName, outputStream);
  31. } catch (MalformedURLException e1) {
  32. e1.printStackTrace();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. Encoder encoder = Base64.getEncoder();
  37. return encoder.encodeToString(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
  38. }
  39. /**
  40. * 将本地图片进行Base64位编码
  41. *
  42. * @param imgUrl
  43. * 图片的url路径,如http://.....xx.jpg
  44. * @param extensioName 图片的扩展名
  45. * @return 加密之后的字符串
  46. */
  47. public static String encodeImgageToBase64(File imageFile, String extensioName) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  48. ByteArrayOutputStream outputStream = null;
  49. try {
  50. BufferedImage bufferedImage = ImageIO.read(imageFile);
  51. outputStream = new ByteArrayOutputStream();
  52. ImageIO.write(bufferedImage, extensioName, outputStream);
  53. } catch (MalformedURLException e1) {
  54. e1.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. // 对字节数组Base64编码
  59. Encoder encoder = Base64.getEncoder();
  60. return encoder.encodeToString(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
  61. }
  62. /**
  63. * 将Base64位编码的图片进行解码,并保存到指定目录
  64. * @param base64Str 利用base64加密之后的字符串
  65. * @param path 文件解密之后存放的地址 例如:D://
  66. * @param imgName 文件解密之后命名的名称 例如: test.jpg
  67. */
  68. public static void decodeBase64ToImage(String base64Str, String path,
  69. String imgName) {
  70. Decoder decoder = Base64.getDecoder();
  71. try {
  72. FileOutputStream write = new FileOutputStream(new File(path
  73. + imgName));
  74. byte[] decoderBytes = decoder.decode(base64Str);
  75. write.write(decoderBytes);
  76. write.close();
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. }