https://tool.oschina.net/encrypt?type=4
<img class="logo" v-show="false" src="@/assets/images/logo-share.png"/>
let imgBase64 = document.querySelector(".logo").src;
获取的src 就是 base64后的 发现太大的图片可能不成功
var img = "imgurl";//imgurl 就是你的图片路径
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var image = new Image();
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
js直接设置img的src属性为 图片的base64数据即可
document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0 DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );<br>如下:<br><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0 DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">
/**
* Base64字符串转换成图片
*/
public static Bitmap stringToBitmap(String string) {
Bitmap bitmap = null;
try {
byte[] bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
;//输出测试,bitmap始终为NUll
但是,每次得到的bitmap都是null,这是为什么?
于是,我试着将字符串前面的“data:image/jpeg;base64,”取掉,然后,它居然就成功!!!
int size = din.readInt();//读取服务器端传来的图片数据
byte[] bs = new byte[size];
din.read(bs);
YuvImage yuvimage=new YuvImage(bs, ImageFormat.NV21, 20,20, null);//20、20分别是图的宽度与高度
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0,20, 20), 80, baos);//80--JPG图片的质量[0-100],100最高
byte[] jdata = baos.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
测试:bmp不为空,放入控件中可正常显示。
private byte[] base64ToByte(String str) throws IOException {
Log.i("encription", str);
byte[] returnbyteArray = Base64.decode(str, Base64.URL_SAFE);
return returnbyteArray;
}
用Base64.URL_SAFE就不报错了 其实应该还是 有 前面的“data:image/jpeg;base64,”导致的