标签:style c class blog code java
1 package base64StringToImage; 2 import java.awt.image.BufferedImage; 3 import java.io.ByteArrayInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.File; 6 import java.io.IOException; 7 import javax.imageio.ImageIO; 8 import sun.misc.BASE64Decoder; 9 import sun.misc.BASE64Encoder; 10 11 public class TestImageBinary { 12 13 /** 14 * 15 *@param filePath 照片绝对路径 16 *@return String base64码字符串 17 * 18 **/ 19 public String changeImagetoBase64String(String filePath){ 20 BASE64Encoder encoder = new BASE64Encoder(); 21 String base64String = ""; 22 File file = new File(filePath); 23 BufferedImage buffer; 24 try { 25 buffer = ImageIO.read(file); 26 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 27 ImageIO.write(buffer, "jpg", baos); //第二个参数“jpg”不需要修改 28 byte[] bytes = baos.toByteArray(); 29 base64String = encoder.encodeBuffer(bytes).trim(); 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } 33 return base64String; 34 } 35 36 /** 37 * 38 *@param base64String base64码字符串 39 *@param filePath 照片绝对路径 40 * 41 **/ 42 public void changeBase64StringtoImage(String base64String, String filePath){ 43 BASE64Decoder decoder = new BASE64Decoder(); 44 try { 45 byte[] bytes = decoder.decodeBuffer(base64String); 46 ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 47 BufferedImage buffer =ImageIO.read(bais); 48 File file = new File(filePath); //jpg,png,gif等格式 49 ImageIO.write(buffer, "jpg", file); //第二个参数“jpg”不需要修改 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 }
标签:style c class blog code java
原文地址:http://www.cnblogs.com/baifeilong/p/3745979.html