java 中图片base64编码.解码

本文介绍了一个Java程序,该程序实现了将本地图片文件转换为Base64字符串,并能将Base64字符串还原为图片文件的功能。通过使用sun.misc包下的BASE64Encoder和BASE64Decoder类,程序能够方便地完成图片的编码和解码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值