图片base64加密解密


Java中Base64编码使用

  JDK中Base64的实现在JDK1.7之前是没有对外的公共接口的,只有一个非标准实现,位于sun.misc包中,提供BASE64Encoder类和BASE64Decoder类。由于是不对外,所以不建议使用,并且后续JDK版本可能会去掉对这两个类的支持。

  所以说在JDK1.8之前,如果我们要对数据进行Base64编码,一般会借助于第三方的实现,比如Apache Commons包或者Google Guava包。

但在JDK1.8之后,这个问题就不复存在了。JDK1.8提供了一个完整的类用于实现Base64编码解码,这个类是java.util.Base64。以后我们如果需要对Base64编码解码,就可以使用这个类来完成了。


public class Base64Convert {

/**

    * @Description: 图片转化成base64字符串

    * @param:    path

    * @Return:

    */

    public static StringimageToBase64(String path){

if(TextUtils.isEmpty(path)){

return null;

        }

InputStream is =null;

        byte[] data =null;

        String result =null;

        try{

is =new FileInputStream(path);

            //创建一个字符流大小的数组。

            data =new byte[is.available()];

            //写入数组

            is.read(data);

            //用默认的编码格式进行编码

            result = Base64.getEncoder().encodeToString(data);

        }catch (IOException e){

e.printStackTrace();

        }finally {

if(null !=is){

try {

is.close();

                }catch (IOException e) {

e.printStackTrace();

                }

}

}

System.out.println(result);

        return result;

    }

public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片

        if (imgStr ==null)// 图像数据为空

            return false;

        try {

// Base64解码

            byte[] bytes = Base64.getDecoder().decode(imgStr);

            for (int i =0; i < bytes.length; ++i) {

if (bytes[i] <0) {// 调整异常数据

                    bytes[i] +=256;

                }

}

// 生成jpeg图片

            OutputStream out =new FileOutputStream(imgFilePath);

            out.write(bytes);

            out.flush();

            out.close();

return true;

        }catch (Exception e) {

return false;

        }

}

// public static void main(String[] args) {

//        String[] profiles = "http://localhost/profile/upload/photos/banner/2019/9c4f0fcd4fd59eb56940f333330105ab.jpg".split("profile");

//        String s = Global.getFileFolder()+ profiles[1];

//        String imageStr = Base64Convert.imageToBase64(s);

//        System.out.println(s);

//        System.out.println(imageStr);

//        GenerateImage(imageStr,"D://picture.jpg");

//        long endTime = 259200 * 60 * 1000 + System.currentTimeMillis();

//        String encode = Base64.getEncoder().encodeToString((1 + "=" + endTime).getBytes(StandardCharsets.UTF_8));

//        System.out.println(encode);

//

//        String[] split = new String(Base64.getDecoder().decode(encode), StandardCharsets.UTF_8).split("=");

//        System.out.println(split[1]);

//

//    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容