图片base64编码解码
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.io.IOUtils; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * * @author shellingford * @version 2015年1月23日 */ public class ImgBase64Util { public static String getImageStr(File imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64编码过的字节数组字符串 } catch (IOException e) { throw new RuntimeException(e); } finally{ IOUtils.closeQuietly(in); } } public static void generateImage(String imgStr,File imgFile) {// 对字节数组字符串进行Base64解码并生成图片 BASE64Decoder decoder = new BASE64Decoder(); OutputStream out =null; try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } // 生成jpeg图片 out = new FileOutputStream(imgFile); out.write(b); out.flush(); } catch (Exception e) { throw new RuntimeException(e); } finally{ IOUtils.closeQuietly(out); } } public static void main(String[] args) { File file=new File("d:/temp/321321.jpg"); String str=getImageStr(file); System.out.println(str); generateImage(str, new File("d:/temp/321321321.jpg")); } }
iasuna 》原创,转载请保留文章出处。
本文链接:图片base64编码解码 http://www.iasuna.com/post-43.html
版权声明:若无特殊注明,本文皆为《
正文到此结束
发表吐槽
你肿么看?
既然没有吐槽,那就赶紧抢沙发吧!