转载: http://blog.csdn.net/mashihao123/article/details/50429203
JSON传输图片帮助类
(为什么这样做,是因为图片,通过IO操作之后获取的是byte[]字节数组,而JSON传输用的是String,所以需要转换为String,但是直接转换的话会因为,字符的编码不同而导致,得不到最终的效果)
所以需要到由图片到String的帮助类
贴上代码
[java]
view plain
copy
package org.helper; import java.io.FileInputStream; import java.io.IOException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class ImgHelper { public static String encode(byte[] bytes){ return new BASE64Encoder().encode(bytes); } public static byte[] decode(String encodeStr) throws IOException{ byte[] bt = null; BASE64Decoder decoder = new BASE64Decoder(); bt = decoder.decodeBuffer(encodeStr); return bt; } 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; } 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); } public static void main(String[] args) { String str; try { str = encodeImage("E:\\yunifang_img\\1.jpg"); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } } }
转载请注明原文地址: https://www.6miu.com/read-33770.html