Javascript / jQuery - How to convert Media and Image data into binary text format

后端 未结 2 1850
情话喂你
情话喂你 2021-01-27 14:14

I need to send a image/media through json, for that conversion needs to be done into text format. How can I achieve that through jQuery/ Javascript?

2条回答
  •  天涯浪人
    2021-01-27 14:23

    You can find your answer in this post get image data in javascript

    function getBase64Image(img) {
        // Create an empty canvas element
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
    
        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
    
        // Get the data-URL formatted image
        // Firefox supports PNG and JPEG. You could check img.src to guess the
        // original format, but be aware the using "image/jpg" will re-encode the image.
        var dataURL = canvas.toDataURL("image/png");
    
        return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    }
    

    You need to pass the img tag to this function. For further details see Convert an image into binary data in javascript

提交回复
热议问题