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]

原文地址:https://www.cnblogs.com/LeeForLeslie/p/4920281.html