简介
图转Base64编码字符集,服务器端处理。JAVA有API(需jar包),安卓有Base64类。
工具
package util;
import android.text.TextUtils;
import android.util.Base64;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created on 2018/7/10.
*
* @desc ImageUtils
*/
public class ImageUtils {
/**
* 图转Base64编码字符集
*
* @param path 路径
* @return Base64编码字符集
*/
public static String imageToBase64(String path) {
if (TextUtils.isEmpty(path)) {
return null;
}
InputStream is = null;
byte[] data;
String result = null;
try {
is = new FileInputStream(path);
// 创字符流大小数组
data = new byte[is.available()];
// 写入数组
is.read(data);
// 默认编码格式编码
result = Base64.encodeToString(data, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Base64编码字符集转图
*
* @param base64Str Base64编码字符集
* @param path 路径
* @return 成否
*/
public static boolean base64ToFile(String base64Str, String path) {
byte[] data = Base64.decode(base64Str, Base64.DEFAULT);
for (int i = 0; i < data.length; i++) {
if (data[i] < 0) {
// 调整异常数据
data[i] += 256;
}
}
OutputStream os;
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;
}
}
}