zoukankan      html  css  js  c++  java
  • Java图片base64编码解码,接口使用

    在很多要求上传图片的接口中需要上传图片,可能使用最多的方式就是将图片经过base64编码后以字符串的形式上传,此处介绍一下如何将图片进行base64编码以及解码

    1、图片编码。首先要将图片以文件的形式解析为byte[]数组,然后进行编码,在编码时,需要使用BASE64Encoder,此时需要引用sun.misc.BASE64Encoder类

    import sun.misc.BASE64Encoder;

    具体实现如下:

           //将文件转成byte数组,可使用多种方法
        public static byte[] getFileByte(String filePath) throws IOException{
            byte[] bs=null;
            InputStream in=null;
            File file=new File(filePath);
            try {
                in=new FileInputStream(file);
                bs=new byte[(int)file.length()];
                in.read(bs);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            in.close();
            return bs;
        }
        
        /** byte[] 转 base64编码 **/
        public static String getBase64EncodeString(byte[] bytes){
            BASE64Encoder base=new BASE64Encoder();
            return base.encode(bytes);
        }    

    2、讲经过base64编码的字符串进行解码,保存成图片。在解码时,需要使用BASE64Decoder,此时需要引用import sun.misc.BASE64Decoder类

    import sun.misc.BASE64Decoder;

    具体实现如下:

    /**解码base64
         * @throws IOException **/
        public static void createImage(String base64String,String imgPath) throws IOException{
            BASE64Decoder decoder =new BASE64Decoder();
            //解码
            byte[] bytes = decoder.decodeBuffer(base64String);
            //检查调整异常数据  
            for (int i = 0; i < bytes.length; ++i) {  
                    if (bytes[i] < 0) {
                    bytes[i] += 256;  
                }  
            }  
            
            OutputStream out=new FileOutputStream(imgPath);
            //生成图片
            out.write(bytes);
            
            out.flush();
            out.close();
        }

    可能遇到的问题:在引用sun.misc的包时,可能无法引用,此时需要在Build Path-Libraries-Remove [JRE System Library]-然后重新 Add Libraries[JRE System Library]

  • 相关阅读:
    Java的代码风格
    哪些你容易忽略的C语言基础知识
    Java基础学习笔记第二章
    Java代码性能优化总结
    Java并发编程(2):线程中断(含代码)
    C语言代码训练(一)
    数控G代码编程详解大全
    PLC编程算法
    博客转移到新地址
    一些吐槽
  • 原文地址:https://www.cnblogs.com/LeeForLeslie/p/4920281.html
Copyright © 2011-2022 走看看