Javascript - get extension from base64 image

后端 未结 8 1599

I have a base64 encoded image returned from a service and it looks like this:

/9j/4AAQSkZJRgABAQEASABIAAD/4Yp2aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWN         


        
8条回答
  •  有刺的猬
    2021-01-01 10:28

    By the way you provided invalid Base64 string. correct syntax of base64 encoded image string is like this

    "data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789......"
    

    You can parse that string and can get the information out of it

    const base64str = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
    let mimeType = base64str.profilepic.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0];
    

    You can see demo here

    and if you want to get only extensions you can use following code to get that one. using regex to parse base64 string and get the extension.

    const body2 = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
    let mimeType2 = body2.profilepic.match(/[^:/]\w+(?=;|,)/)[0];
    

    check online working Demo here

提交回复
热议问题