工程作完了,用到了图片字符流的转换,特此记录下来java
package com.cheqiren.caren.util; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import javax.imageio.ImageIO; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** 程序名 ImageUtils.java 程序功能 Base64编码和解码图片文件 做成者 xxx 做成日期 2015-11-05 ======================修改履历====================== 项目名 状态 做成者 做成日期 -------------------------------------------------- caren 新规 xxx 2015-11-05 ================================================= */ @SuppressWarnings("restriction") public class ImageUtils { /** * 将网络图片进行Base64位编码 * * @param imgUrl * 图片的url路径,如http://.....xx.jpg * @return */ public static String encodeImgageToBase64(URL imageUrl) throws Exception {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 ByteArrayOutputStream outputStream = null; BufferedImage bufferedImage = ImageIO.read(imageUrl); outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", outputStream); // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 return encoder.encode(outputStream.toByteArray()); } /** * 将本地图片进行Base64位编码 * * @param imgUrl * 图片的url路径,如http://.....xx.jpg * @return */ public static String encodeImgageToBase64(File imageFile) throws Exception {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 ByteArrayOutputStream outputStream = null; BufferedImage bufferedImage = ImageIO.read(imageFile); outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", outputStream); // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串 } /** * 将Base64位编码的图片进行解码,并保存到指定目录 * * @param base64 * base64编码的图片信息 * @param path * 文件存储的路径 * @param imgName * 保存的文件名 * @return */ public static void decodeBase64ToImage(String base64, String path, String imgName) throws Exception { BASE64Decoder decoder = new BASE64Decoder(); FileUtils.creatFolder(path); FileOutputStream write = new FileOutputStream(new File(path + imgName)); byte[] decoderBytes = decoder.decodeBuffer(base64); write.write(decoderBytes); write.close(); } /** * 将字符流图片进行解码,并保存到指定目录 * * @param stream * 文件字符流 * @param path * 文件存储的路径 * @param imgName * 保存的文件名 * @return */ @SuppressWarnings("unused") public static void saveFileFromInputStream(InputStream stream,String path, String imgName) throws Exception{ FileUtils.creatFolder(path); FileOutputStream fs=new FileOutputStream(path + imgName); System.out.println("文件保存路径:"+path + imgName); byte[] buffer =new byte[1024*1024]; int bytesum = 0; int byteread = 0; while ((byteread=stream.read(buffer))!=-1){ bytesum += byteread; fs.write(buffer,0,byteread); fs.flush(); } fs.close(); stream.close(); System.out.println("文件写入完毕。"); } }