ImageConvertUtil.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.yihu.jw.utils;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import javax.imageio.ImageIO;
  5. import java.awt.image.BufferedImage;
  6. import java.io.ByteArrayInputStream;
  7. import java.io.ByteArrayOutputStream;
  8. import java.io.File;
  9. import java.io.IOException;
  10. /**
  11. * @ClassName ImageConvertUtil
  12. * @Description TODO
  13. * @Author heqian
  14. * @Date 2019/5/16 17:05
  15. * @Version 1.0
  16. */
  17. public class ImageConvertUtil {
  18. static BASE64Encoder encoder = new BASE64Encoder();
  19. static BASE64Decoder decoder = new BASE64Decoder();
  20. static String upload_home = System.getProperty("catalina.home")+"resources/repository/";
  21. public static void main(String[] args) {
  22. String str = getImageBinary("C://Users//Administrator//Desktop//医生信息//陈兰//资格证.jpg");
  23. System.out.println(str);
  24. }
  25. public static String getImageBinary(){
  26. File f = new File("d://123.jpg");
  27. BufferedImage bi;
  28. try {
  29. bi = ImageIO.read(f);
  30. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  31. ImageIO.write(bi, "jpg", baos);
  32. byte[] bytes = baos.toByteArray();
  33. return encoder.encodeBuffer(bytes).trim();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. return null;
  38. }
  39. public static String getImageBinary(String path){
  40. File f = new File(path);
  41. BufferedImage bi;
  42. try {
  43. bi = ImageIO.read(f);
  44. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  45. ImageIO.write(bi, "jpg", baos);
  46. byte[] bytes = baos.toByteArray();
  47. return encoder.encodeBuffer(bytes).trim();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. return null;
  52. }
  53. public static void base64StringToImage(String base64String, String fileName){
  54. try {
  55. byte[] bytes1 = decoder.decodeBuffer(base64String);
  56. ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
  57. BufferedImage bi1 =ImageIO.read(bais);
  58. File w2 = new File(upload_home + fileName);//鍙互鏄痡pg,png,gif鏍煎紡
  59. ImageIO.write(bi1, "jpg", w2);//涓嶇杈撳嚭浠�涔堟牸寮忓浘鐗囷紝姝ゅ涓嶉渶鏀瑰姩
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }