• base64编码转图片,图片转base64编码


    亲测可用:

    代码:

     1 import sun.misc.BASE64Decoder;
     2 import sun.misc.BASE64Encoder;
     3 
     4 import java.io.*;
     5 
     6 public class Base64Util {
     7 
     8     /*把base64编码转换为图片*/
     9     public static boolean generateImage(String imgStr, String path) {
    10         if (imgStr == null)
    11             return false;
    12         BASE64Decoder decoder = new BASE64Decoder();
    13         try {
    14             byte[] b = decoder.decodeBuffer(imgStr);
    15             for (int i = 0; i < b.length; i++) {
    16                 if (b[i] < 0) {
    17                     b[i] += 256;
    18                 }
    19             }
    20             OutputStream out = new FileOutputStream(path);
    21             out.write(b);
    22             out.flush();
    23             out.close();
    24             return true;
    25         } catch (Exception e) {
    26             e.printStackTrace();
    27             return false;
    28         }
    29     }
    30 
    31     /*把图片转换为base64编码*/
    32     public static String getImageStr(String imgFile) {
    33         InputStream inputStream = null;
    34         byte[] data = null;
    35         try {
    36             inputStream = new FileInputStream(imgFile);
    37             data = new byte[inputStream.available()];
    38             inputStream.read(data);
    39             inputStream.close();
    40         } catch (IOException e) {
    41             e.printStackTrace();
    42         }
    43         BASE64Encoder encoder = new BASE64Encoder();
    44         return encoder.encode(data);
    45     }
    46     /*此为以上方法的用法,可以忽略*/
    47     /*public static void main(String[] args) {
    48         *//*把图片转换为base64编码*//*
    49         String strImg = getImageStr("这里传图片的路径:c:/users/图片.png");
    50         System.out.println(strImg);
    51         *//*把base64编码转换为图片*//*
    52         generateImage(strImg,strImg*//*strImg这里是base64编码*//*);
    53     }*/
    54 }
  • 相关阅读:
    还不知道spring的RestTemplate的妙用吗
    【学习笔记】机器学习之特征工程
    《饥饿的盛世》总结
    我是如何解决java.security.cert.CertPathValidatorException异常的
    《机器学习
    2018年总结
    元类实现ORM
    元类
    python中的装饰器
    python中的闭包
  • 原文地址:https://www.cnblogs.com/wangquanyi/p/11328907.html
Copyright © 2020-2023  润新知