java 中图片base64编码.解码
Java中经常会遇到图片上传,
package test;/**
 * Created by chenjia on 2018/5/16.
 */

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.awt.image.ImagingOpException;
import java.io.*;

/**
 * @author chenjia
 * @create 2018-05-16 17:15
 * @desc
 **/
public class Test64Bit {

    public static void main(String[] args){
        String imageStr = getImageStr("报告列表.png");
        System.out.println(imageStr);

        GenerateImage(imageStr,"生成图片");
    }

    public static String getImageStr(String imgFilePath){
        byte[] data = null;
        try {

            InputStream in = new FileInputStream(new File(imgFilePath));
            final File file = new File(imgFilePath);
            if (file.exists()) {
                System.out.println("存在");
            }
            data = new byte[in.available()];
            System.out.println(data.toString());
            in.read(data);
            in.close();
        }catch (IOException exception){
            exception.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }


    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(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();
            File file = new File(imgFilePath);
            System.out.println(file.getAbsolutePath());
            System.out.println(file.getPath());
            file.renameTo(new File(imgFilePath+".png"));
            System.out.println(file.getAbsolutePath());
            System.out.println(file.getPath());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

java 中图片base64编码.解码

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭