图片Base64编码 简单使用

时间:2022-01-06 10:26:00

图片在线转换Base64,图片编码base64 http://tool.css-js.com/base64.html

HTML5 + js

<input type="file" id="photoinput">
<button id="photoupbtn">上传</button>
$("#photoinput").on("change", function () {
oFReader = new FileReader();
var pho = document.getElementById("photoinput").files[0];
//html5图片转BASE64
oFReader.readAsDataURL(pho);
//转换结束调用方法
oFReader.onloadend = function(){
//控制台输出Base64编码
console.log(oFReader.result);
var param = {
content: oFReader.result
};
//转json串
var params = JSON.stringify(param); //ajax 请求
$.ajax({
type: "post",
url: "uploadphoto",
contentType: "application/json",
data: params,
dataType: "json",
success: function (result)
{
alert("success");
},
error: function (result)
{
alert("failed");
}
});
}; });

readAsDataURL方法会使用base-64进行编码,编码的资料由data字串开始,后面跟随的是MIME type,然后再加上base64字串,逗号之后就是编码过的图像文件的内容。

eg.  data:image/jpg;base64,/9j/4AAQSkZJRgABAQEACgAKAAD/2wBDAAEBAQEBAQE........

Base64 在CSS中的使用

.demoImg{ background-image: url("data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...."); }

Base64 在HTML中的使用

<img width="40" height="30" src="data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...." />

JAVA

//base64 编码图片数据
public void savePic(String base64Content){
try {
//Base64解码
byte[] picContent = new BASE64Decoder().decodeBuffer(base64Content); //本地保存照片测试
InputStream in = new ByteArrayInputStream(picContent);
File file=new File("E:/a.jpg");//可以是任何图片格式.jpg,.png等
FileOutputStream fos=new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = in.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}