Java中图片与base64位编码互转

Java代码   收藏代码
  1. import java.io.FileInputStream;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6.   
  7. import sun.misc.BASE64Decoder;  
  8. import sun.misc.BASE64Encoder;  
  9.   
  10. public class Test64Bit {  
  11. public static void main(String[] args) {  
  12. // 测试从Base64编码转换为图片文件  
  13.   
  14.   String strImg = "这里放64位编码";  
  15. GenerateImage(strImg, "D:\wangyc.jpg");  
  16.   
  17. // 测试从图片文件转换为Base64编码  
  18. System.out.println(GetImageStr("d:\wangyc.jpg"));  
  19.   
  20.   
  21. }  
  22.   
  23. public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理  
  24. byte[] data = null;  
  25.   
  26. // 读取图片字节数组  
  27. try {  
  28. InputStream in = new FileInputStream(imgFilePath);  
  29. data = new byte[in.available()];  
  30. in.read(data);  
  31. in.close();  
  32. catch (IOException e) {  
  33. e.printStackTrace();  
  34. }  
  35.   
  36. // 对字节数组Base64编码  
  37. BASE64Encoder encoder = new BASE64Encoder();  
  38. return encoder.encode(data);// 返回Base64编码过的字节数组字符串  
  39. }  
  40.   
  41. public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片  
  42. if (imgStr == null// 图像数据为空  
  43. return false;  
  44. BASE64Decoder decoder = new BASE64Decoder();  
  45. try {  
  46. // Base64解码  
  47. byte[] bytes = decoder.decodeBuffer(imgStr);  
  48. for (int i = 0; i < bytes.length; ++i) {  
  49. if (bytes[i] < 0) {// 调整异常数据  
  50. bytes[i] += 256;  
  51. }  
  52. }  
  53. // 生成jpeg图片  
  54. OutputStream out = new FileOutputStream(imgFilePath);  
  55. out.write(bytes);  
  56. out.flush();  
  57. out.close();  
  58. return true;  
  59. catch (Exception e) {  
  60. return false;  
  61. }  
  62. }  
  63. }  

猜你喜欢

转载自18519721986.iteye.com/blog/2325660