简体   繁体   中英

How to Convert image URL from server (API / ImageURL) to Base64 in Vue.Js

A lot of reference I see about this problem is about upload file and convert to base64 but in my case I want to convert an Image URL from server and convert it to base64 but I still failed to do it, right now I tried it like this, but it still failed since it doesn't show anything

this is my html:

<div v-if="questionData">
    <img class="img-preview-download" :src="questionData.image_url? getBase64Image(questionData.image_url) : 'https://via.placeholder.com/640x360'" alt="img-preview">
</div>

this is my method:

getBase64Image(img) {
    console.log("cek base64 : ", btoa(img));
    return `data:image/jpeg;base64,${btoa(img)}`;
},

I read some using file reader but isn't it only for file when you upload a data using input ? can someone help me to solve this? I'm using Vue.Js for the framework

when I used this method I got result like this:

图像崩溃,如您所见

So this is my answer for my future self, who might be forget and stumble again in this problem!

You can solve it by making a new image and inside that image file, you can add your src so the image can be process when still loading or onload .

Remember!

Since it is you, You might be remove the last image.src = url to get a clean code, but this is important, if you remove that line, image.onload will not be trigger because it will search for the image source. and if you try to use image.srcObject to put it with mediaStream it will give you Resolution Overloaded since you still not find the answer for this problem, it is okay, you can use the image first since your step is to achieve how to get file from Image URL . so this is the method you use to solve this problem:

downloadPreview() {
    const el = this.$refs.printMe;
    const options = {
        type: 'dataURL'
    };

    this.$html2canvas(el, options).then(data => {
        this.output = data;

        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = data;

        // this is just optional function to download your file
        a.download = `name.jpeg`;
        document.body.appendChild(a);
        a.click();
    });
},

convertImgUrlToBase64(url) {
    let self = this;
    var image = new Image();
    image.setAttribute('crossOrigin', 'anonymous'); // use it if you try in a different origin of your web

    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;

        canvas.getContext('2d').drawImage(this, 0, 0);

        canvas.toBlob(
            function(source) {
                var newImg = document.createElement("img"),
                url = URL.createObjectURL(source);

                newImg.onload = function() {
                // no longer need to read the blob so it's revoked
                URL.revokeObjectURL(url);
                };

                newImg.src = url;
            },
            "image/jpeg",
            1
        );

        // If you ever stumble at 18 DOM Exception, just use this code to fix it
        // let dataUrl = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
        let dataUrl = canvas.toDataURL("image/jpeg");
        console.log("cek inside url : ", url);

        if(url === backgroundImg) {
            self.assignImageBase64Background(dataUrl);
        } else {
            self.assignImageBase64(dataUrl);
        }
    };
    image.src = url;
},

assignImageBase64(img) {
    this.imgBase64 = img;
},

just for information, I use this library to change the div into image file: vue-html2canvas

Notes:

If you ever wondering why I give self.assignImageBase64(dataUrl); this function in the end, this is because I still wondering how onload works, and how to return Base64 url to the parent thats why I just assign it again in another function since it easier to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM