#获取BASE64 利用Webuploader获取所选图片的文件大小,如果图片过大设定一个压缩比例,然后利用API:makeThumb生成缩略图,并获取第一次缩略图的BASE64编码,并讲该编码放置为页面一个隐藏div的html代码,利用js的Image对象获取图片的原始尺寸
uploader.makeThumb(file, function (error, src) {
if (error) {
$('#headerImage').html("图片加载失败,请重新选择!");
return;
}
$('#id_img_file_type').val(file.ext);
var img = new Image();
img.onload = function () {
var width = img.width;
var height = img.height;
$('#id_img_src').html(src);
var showImgSize = cacluateShowImgSize(width, height);
showHeaderImg(showImgSize, file);
};
img.src = src;
}, compressPercent, compressPercent);
#利于jquery插件imgAreaSelect进行裁剪 利用将图片展示在页面上,然后进行相应的裁剪动作; #保存图片 提交base64编码、裁剪的四个定位数据,在后台生成图片并进行相应的裁剪,即可生成相应的头像图片。 #遇到的坑
ie8页面img的src如果为base64编码,最大只支持32KB的数据,所以可能js中要进行二次压缩,如果第一次压缩过剧,会影响头像最后的显示效果。 这就是开始时base64编码过大在页面产生的效果:
java转base64编码为图片,需要去掉编码前面的头数据,形如:“data:image/jpeg;base64,”,否则图片会转化失败。
public static File base64ToImage(String fileBasePath, String base64src, String fileType) {// 对字节数组字符串进行Base64解码并生成图片
if (base64src.indexOf(",") > 0) {
base64src = base64src.substring(base64src.indexOf(",") + 1);
}
String fileDir = fileBasePath + File.separator + "temp";
File targetDir = new File(fileDir);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
File targetFile = new File(fileDir + File.separator + UUID.randomUUID().toString() + "." + fileType);
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(base64src);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
OutputStream out = new FileOutputStream(targetFile);
out.write(bytes);
out.flush();
out.close();
return targetFile;
} catch (Exception e) {
logger.error("base64转图片失败", e);
return null;
}
}