1. var img =
    2. "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=508387608,2848974022&fm=26&gp=0.jpg"; //imgurl 就是你的图片路径
    3. function getBase64Image(img) {
    4. var canvas = document.createElement("canvas");
    5. canvas.width = img.width;
    6. canvas.height = img.height;
    7. var ctx = canvas.getContext("2d");
    8. ctx.drawImage(img, 0, 0, img.width, img.height);
    9. var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    10. var dataURL = canvas.toDataURL("image/" + ext);
    11. return dataURL;
    12. }
    13. var image = new Image();
    14. image.src = img;
    15. image.setAttribute("crossOrigin", "Anonymous");
    16. image.onload = function() {
    17. var base64 = getBase64Image(image);
    18. console.log(base64);
    19. document.getElementById("img").src = base64;
    20. var formData = new FormData();
    21. //转换base64到file
    22. var file = btof(base64, "test");
    23. formData.append("imageName", file);
    24. };
    25. function btof(data, fileName) {
    26. const dataArr = data.split(",");
    27. const byteString = atob(dataArr[1]);
    28. const options = {
    29. type: "image/jpeg",
    30. endings: "native"
    31. };
    32. const u8Arr = new Uint8Array(byteString.length);
    33. for (let i = 0; i < byteString.length; i++) {
    34. u8Arr[i] = byteString.charCodeAt(i);
    35. }
    36. return new File([u8Arr], fileName + ".jpg", options);
    37. }