ImgUtils.java 2.5 KB

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