java如何将图片转为字符数据



java如何将图片转为字符数据方法实例代码。

我使用的jdk为1.7 64位的

 

  1. /**
  2.      * 获得图片的字符数据
  3.      * @author 胡汉三
  4.      * 2014年6月19日 上午11:37:46
  5.      * @param url   图片存储路径
  6.      * @return
  7.      * @throws IOException
  8.      */
  9.     public static String getImageString(String url) throws IOException{
  10.         if(url==null||url.equals(“”))
  11.             return null;
  12.         InputStream in = null;
  13.         byte[] data = null;
  14.         // 读取图片字节数组
  15.         try {
  16.             in = new FileInputStream(url);
  17.             data = new byte[in.available()];
  18.             in.read(data);
  19.             in.close();
  20.         } catch (IOException e) {
  21.             e.printStackTrace();
  22.         }
  23.         // 对字节数组Base64编码
  24.         BASE64Encoder encoder = new BASE64Encoder();
  25.         return encoder.encode(data);// 返回Base64编码过的字节数组字符串
  26.     }
  27.     /**
  28.      * 根据图片的字符数据创建图片
  29.      * @author 胡汉三
  30.      * 2014年6月19日 上午11:40:24
  31.      * @param str   图片的字符数据
  32.      * @return
  33.      * @throws IOException
  34.      */
  35.     public static String createImageByString(String str) throws IOException{
  36.         String url = ”E:\\我的二维码\\ticket2.png”;
  37.         BASE64Decoder decoder=new BASE64Decoder();
  38.         byte[] bytes=decoder.decodeBuffer(str);
  39.         for (int i = 0; i < bytes.length; ++i) {
  40.             if (bytes[i] < 0) {// 调整异常数据
  41.                 bytes[i] += 256;
  42.             }
  43.         }
  44.         File file=new File(url);
  45.         FileOutputStream fos=new FileOutputStream(file);
  46.         fos.write(bytes);
  47.         fos.flush();
  48.         fos.close();
  49.         return url;
  50.     }
  51.     public static void main(String[] args) throws IOException {
  52.         String path = ”E:\\我的二维码\\ticket.png”;
  53.         String str = getImageString(path);
  54.         String url = createImageByString(str);
  55.         System.out.println(url);
  56.     }