ImgUtils.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.yihu.jw.utils;
  2. import sun.misc.BASE64Encoder;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.DataInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.URL;
  8. /**
  9. * Created by Trick on 2019/12/12.
  10. */
  11. public class ImgUtils {
  12. public static void main(String ag[]){
  13. try {
  14. String path ="http://ehr.yihu.com/fastdfs/group1/M00/00/1F/rBoAbl3V_yyAVdkaAAJwTja8N7I527.png";
  15. System.out.println(getImg(path));
  16. }catch (Exception e){
  17. e.printStackTrace();
  18. }
  19. }
  20. public static String getImg(String path)throws Exception{
  21. try{
  22. URL url = new URL(path);
  23. DataInputStream dataInputStream = new DataInputStream(url.openStream());
  24. return getBase64FromInputStream(dataInputStream);
  25. }catch (Exception e){
  26. e.printStackTrace();
  27. }
  28. return "";
  29. }
  30. private static String getBase64FromInputStream(InputStream is) throws Exception {
  31. // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  32. byte[] data = null;
  33. // 读取图片字节数组
  34. try {
  35. ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
  36. byte[] buff = new byte[100];
  37. int rc = 0;
  38. while ((rc = is.read(buff, 0, 100)) > 0) {
  39. swapStream.write(buff, 0, rc);
  40. }
  41. data = swapStream.toByteArray();
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. } finally {
  45. if (is != null) {
  46. try {
  47. is.close();
  48. } catch (IOException e) {
  49. throw new Exception("输入流关闭异常");
  50. }
  51. }
  52. }
  53. //转化方法1
  54. BASE64Encoder encoder = new sun.misc.BASE64Encoder();
  55. return encoder.encodeBuffer(data).trim();
  56. //转化方法2
  57. // return new String(Base64.encodeBase64(data));
  58. }
  59. }