0

我正在尝试调整上传图像的大小,在提交之前将其设置回输入元素。

  $("#upload_button").click(function(){
            var imgToUpload = document.getElementById('id_picture').files;
            for (var x = 0; x < imgToUpload.length; x ++){
                var getImg = imgToUpload[x];
                console.log(typeof getImg);
                if (! imgToUpload[x].type.match(/image.*/)){
                    alert("not an image");
                    return false;
                }

                var img = document.createElement("img");
                img.src = window.URL.createObjectURL(getImg);

                var canvas = document.createElement("canvas");
                canvas.width  = 20;
                canvas.height = 20; 
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, 20, 20);

                var resizedUrl = canvas.toDataURL("image/jpeg",0.7);
                var byteString = atob(resizedUrl.split(",")[1]);

                var ab = new ArrayBuffer(byteString.length);
                var ia = new Uint8Array(ab);
                for (var index = 0; index < byteString.length; index++){
                    ia[index] = byteString.charCodeAt(index);
                }

                var bob =  new Blob([ab], {"type": getImg.type});

                var p = document.getElementById('id_picture');
                p.value = bob;

                $("#upload_form").submit();

            }
        });

当我到达时p.value = bob,我会遇到提到的问题。我做错了吗?

(我读到我可以简单地使用canvas.toDataURL并将其设置为另一个隐藏输入,但我正在尝试看看这是否可能)

4

1 回答 1

0

您可以使用 toDataURL

var canvas  = document.getElementById("ex1");
var dataUrl = canvas.toDataURL();

客户端示例: http ://tutorials.jenkov.com/html5-canvas/todataurl.html

服务器(PHP)示例http://html5stars.com/?p=99

于 2013-01-01T19:23:55.797 回答