json传输图片
2017-06-15 11:46
260 查看
json是无法传输二进制的文本格式
可以将图片转为字符串形式传输
Test
ImgIOJsonOutputUtils
可以将图片转为字符串形式传输
Test
**package test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import utils.ImgIOJsonOutputUtils; public class Test { public static void main(String[] args) throws Exception { String str; try { str = ImgIOJsonOutputUtils.encodeImage("F:/android_img/ljgjjd.jpg"); System.out.println(str); // 字符串解码为byte数组 byte[] decode = ImgIOJsonOutputUtils.decode(str); FileOutputStream fos = new FileOutputStream( "F:/android_img/ljgjjd_copy.jpg"); fos.write(decode); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }**
ImgIOJsonOutputUtils
package utils; import java.io.FileInputStream; import java.io.IOException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class ImgIOJsonOutputUtils { /** * TODO:将byte数组以Base64方式编码为字符串 * @param bytes 待编码的byte数组 * @return 编码后的字符串 * */ public static String encode(byte[] bytes){ return new BASE64Encoder().encode(bytes); } /** * TODO:将以Base64方式编码的字符串解码为byte数组 * @param encodeStr 待解码的字符串 * @return 解码后的byte数组 * @throws IOException * */ public static byte[] decode(String encodeStr) throws IOException{ byte[] bt = null; BASE64Decoder decoder = new BASE64Decoder(); bt = decoder.decodeBuffer(encodeStr); return bt; } /** * TODO:将两个byte数组连接起来后,返回连接后的Byte数组 * @param front 拼接后在前面的数组 * @param after 拼接后在后面的数组 * @return 拼接后的数组 * */ public static byte[] connectBytes(byte[] front, byte[] after){ byte[] result = new byte[front.length + after.length]; System.arraycopy(front, 0, result, 0, after.length); System.arraycopy(after, 0, result, front.length, after.length); return result; } /** * TODO:将图片以Base64方式编码为字符串 * @param imgUrl 图片的绝对路径(例如:D:\\jsontest\\abc.jpg) * @return 编码后的字符串 * @throws IOException * */ public static String encodeImage(String imgUrl) throws IOException{ FileInputStream fis = new FileInputStream(imgUrl); byte[] rs = new byte[fis.available()]; fis.read(rs); fis.close(); return encode(rs); } }
相关文章推荐
- 使用volley实现简单的操作,json传输,网络图片显示
- JSON传输图片帮助类
- json传输图片 等二进制数据
- 笔记:使用json传输图片,根据个人经验:我做不到,想了个办法将文件转变成字符串并压缩
- JSON传输图片帮助类
- JSON传输图片帮助类
- JSON传输图片帮助类
- Servlet利用base64和json向客户端传输图片
- 掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输
- Ajax中使用XML和JSON格式传输的优劣比较
- 使用 JSON 进行数据传输
- 使用 JSON 进行数据传输
- 使用 JSON 进行数据的异步传输
- 掌握 Ajax,第 9 部分: 使用 JSON 进行数据传输
- Ext2.2与Struts2集成,使用Json数据格式传输数据问题
- 掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输
- 掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输
- 利用json和prototype来做用户是否正确的判断,传统的方式是提交后做判断,这里使用的是ajax异步传输的方式。
- Ajax: 使用 JSON 进行数据传输
- 掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输