(java)利用BASE64编码和解码图片文件

来源:互联网 发布:xp怎么查找网络打印机 编辑:程序博客网 时间:2024/06/05 13:29

<p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; line-height: 14.615385055541992px; font-size: 13.076923370361328px; background-color: rgb(254, 254, 242);">有时候会有这样的一个需求,那就是将界面上的图片,或者文件系统的图片进行base64编码,之后存进数据库。</p><p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; line-height: 14.615385055541992px; font-size: 13.076923370361328px; background-color: rgb(254, 254, 242);">在需要的时候从数据库中讲base64编码提取出来重新生成图片文件。</p><p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; line-height: 14.615385055541992px; font-size: 13.076923370361328px; background-color: rgb(254, 254, 242);">下面给出一个利用base64编码存取文件系统上的图片的例子:</p>
package com.mai.base64;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.junit.Test;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class Base64Test {    private String imageURL = "c:/test.png";    @Test    public void testBase64Encoder(){        BASE64Encoder encoder = new BASE64Encoder();                try {            StringBuilder pictureBuffer = new StringBuilder();            InputStream input = new FileInputStream(new File(imageURL));            ByteArrayOutputStream out = new ByteArrayOutputStream();            byte[] temp = new byte[1024];            for(int len = input.read(temp); len != -1;len = input.read(temp)){                out.write(temp, 0, len);                pictureBuffer.append(encoder.encode(out.toByteArray()));                //out(pictureBuffer.toString());                out.reset();            }                        out(pictureBuffer.toString());            out("Encoding the picture Success");                                        BASE64Decoder decoder = new BASE64Decoder();        FileOutputStream write = new FileOutputStream(new File("c:/test2.png"));        byte[] decoderBytes = decoder.decodeBuffer(pictureBuffer.toString());        write.write(decoderBytes);        out("Decoding the picture Success");                    } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e){            e.printStackTrace();        }    }        public void out(Object o){        System.out.println(o.toString());    }}



0 0
原创粉丝点击