java如何将图片转为字符数据方法实例代码。
我使用的jdk为1.7 64位的
- /**
- * 获得图片的字符数据
- * @author 胡汉三
- * 2014年6月19日 上午11:37:46
- * @param url 图片存储路径
- * @return
- * @throws IOException
- */
- public static String getImageString(String url) throws IOException{
- if(url==null||url.equals(“”))
- return null;
- InputStream in = null;
- byte[] data = null;
- // 读取图片字节数组
- try {
- in = new FileInputStream(url);
- data = new byte[in.available()];
- in.read(data);
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // 对字节数组Base64编码
- BASE64Encoder encoder = new BASE64Encoder();
- return encoder.encode(data);// 返回Base64编码过的字节数组字符串
- }
- /**
- * 根据图片的字符数据创建图片
- * @author 胡汉三
- * 2014年6月19日 上午11:40:24
- * @param str 图片的字符数据
- * @return
- * @throws IOException
- */
- public static String createImageByString(String str) throws IOException{
- String url = ”E:\\我的二维码\\ticket2.png”;
- BASE64Decoder decoder=new BASE64Decoder();
- byte[] bytes=decoder.decodeBuffer(str);
- for (int i = 0; i < bytes.length; ++i) {
- if (bytes[i] < 0) {// 调整异常数据
- bytes[i] += 256;
- }
- }
- File file=new File(url);
- FileOutputStream fos=new FileOutputStream(file);
- fos.write(bytes);
- fos.flush();
- fos.close();
- return url;
- }
- public static void main(String[] args) throws IOException {
- String path = ”E:\\我的二维码\\ticket.png”;
- String str = getImageString(path);
- String url = createImageByString(str);
- System.out.println(url);
- }