Android实现将图片转换上传服务器功能
让客户端将图片上传到服务器,将图片的网络URL告诉服务器
将图片转成Base64编码,传递给服务器,服务器将Base64字符串解码之后生成一张图片。
Android在util包中提供了android.util.Base64类
该类提供了四个编码方法,分别是:
public static byte[] encode(byte[] input, int flags)public static byte[] encode(byte[] input, int offset, int len, int flags)public static String encodeToString(byte[] input, int flags)public static String encodeToString(byte[] input, int offset, int len, int flags)
提供了三个解码
public static byte[] decode(String str, int flags)public static byte[] decode(byte[] input, int flags)public static byte[] decode(byte[] input, int offset, int len, int flags)
CRLF
Win风格的换行符,意思就是使用CR和LF这一对作为一行的结尾而不是Unix风格的LF。CRLF是Carriage-Return Line-Feed的缩写,意思是回车(\r)换行(\n)。也就是说,Window风格的行结束标识符是\r\n,Unix风格的行结束标识符是\n。
DEFAULT
这个参数是默认,使用默认的方法来加密NO_PADDING
这个参数是略去加密字符串最后的“=”NO_WRAP
这个参数意思是略去所有的换行符(设置后CRLF就没用了)URL_SAFE
这个参数意思是加密时不使用对URL和文件名有特殊意义的字符来作为加密字符,具体就是以-和_取代+和/。NO_CLOSE
通常与`Base64OutputStream`一起使用,是传递给`Base64OutputStream`的标志指示它不应关闭正在包装的输出流。图片转Base64代码如下:
/*** 将图片转换成Base64编码的字符串*/public static String imageToBase64(String path){if(TextUtils.isEmpty(path)){return null;}InputStream is = null;byte[] data = null;String result = null;try{is = new FileInputStream(path);//创建一个字符流大小的数组。data = new byte[is.available()];//写入数组is.read(data);//用默认的编码格式进行编码result = Base64.encodeToString(data,Base64.NO_CLOSE);}catch (Exception e){e.printStackTrace();}finally {if(null !=is){try {is.close();} catch (IOException e) {e.printStackTrace();}}}return result;}
Base64转图片代码如下:
/*** 将Base64编码转换为图片* @param base64Str* @param path* @return true*/public static boolean base64ToFile(String base64Str,String path) {byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);for (int i = 0; i < data.length; i++) {if(data[i] < 0){//调整异常数据data[i] += 256;}}OutputStream os = null;try {os = new FileOutputStream(path);os.write(data);os.flush();os.close();return true;} catch (FileNotFoundException e) {e.printStackTrace();return false;}catch (IOException e){e.printStackTrace();return false;}}
评论
