search

Home  >  Q&A  >  body text

javascript - How to determine whether an image is base64 in js

Multiple img tags, the src of each tag is different,

Now we need to do different processing for images whose src is base64 encoded and non-base64 images,

How should javascript distinguish whether the image is base64?

巴扎黑巴扎黑2717 days ago1928

reply all(6)I'll reply

  • 漂亮男人

    漂亮男人2017-07-05 11:07:26

    BASE64 codes always start with the form data:image/xxx;base64,xxxxxx..., so just write a regular expression and test src

    reply
    0
  • 阿神

    阿神2017-07-05 11:07:26

    $('img').each((i,item)=>{
        let src = item.src
        if(src.indexOf('data:image/jpg;base64,')>-1){
            // base64 图片操作
        }else{
            //path 图片操作
        }
    })

    reply
    0
  • 为情所困

    为情所困2017-07-05 11:07:26

    Are non-base64 images all URL addresses?

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-07-05 11:07:26

    Just match according to the beginning of src

    $('img').each((i,item)=>{
        let src = item.src
        if(src.indexOf('data:image')>-1){
            // base64 图片操作
        }else{
            //path 图片操作
        }
    })

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-05 11:07:26

    You need to use startWith, which is more efficient:

    $('img').each((i,item)=>{
        let src = item.src
        if(src.startWith('data:image')){
            // base64 图片操作
        }else{
            //path 图片操作
        }
    })

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 11:07:26

    function validDataUrl(s) {
        return validDataUrl.regex.test(s);
    }
    validDataUrl.regex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i;
    
    module.exports = validDataUrl;
    

    reply
    0
  • Cancelreply