javabase64和图片相互转换


package com.crm.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

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


/**
 * 项目名称:测试项目
 * 类  名  称:Base64ToImg
 * 类  描  述:Base 64编码转换成图片
 * 创  建  人:Frist
 * 创建时间:2016年9月21日 下午5:23:19
 * 修  改  人:Frist
 * 修改时间:2016年9月21日 下午5:23:19
 * 修改备注:
 *
 * @version 1.0
 */

public class Base64ToImg {

    public static void main(String[] args) {
        String img = getImg("\\\\http://my.zhaopin.com/pic/2013/7/29/5935CF5D3B9349CAA95B66FD189FC5BA.jpg");//存放编码
        GenerateImg(img, "E://1.jpg");
        System.out.println(getImg("D://1.jpg"));

    }

    //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    public static String getImg(String imgPath) {
        byte[] bytes = null;

        try {

            InputStream inputStream = new FileInputStream(imgPath);//将图片转换成字节数组
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    //对字节数组Base64编码
    public static boolean GenerateImg(String str, String imgPath) {//生成图片
        boolean flag = true;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            if (str != null) {
                byte[] b = decoder.decodeBuffer(str);
                for (int i = 0; i < b.length; i++) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                OutputStream out = new FileOutputStream(imgPath);
                out.write(b);
                out.flush();
                out.close();
                flag = true;
            } else {
                System.out.println("Base64编码不能为null");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值