Sph*_*ech 1 javascript image imagejpeg
所以,我有一个用于上传图片的用户输入。这是一个简单的例子:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
console.log (img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="handleImage(event)"><br>Run Code Online (Sandbox Code Playgroud)
如您所见,我Image ()在console. 我想将其转换Image为 jpg 文件。
我知道如何获取图片的像素,但是将它发送到服务器完全是疯狂的:它太大了!
我还尝试访问存储在计算机中的 jpg 文件,但我没有实现任何目标。
我发现的唯一方法是form像这样发送它:
<form action="anything.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
Run Code Online (Sandbox Code Playgroud)
在 PHP 中:
$_FILES["fileToUpload"]["tmp_name"]
Run Code Online (Sandbox Code Playgroud)
为什么不使用 JS?
我的最终目标是使用 AJAX 发送 jpg 文件。
如果您有任何问题,请告诉我。
小智 5
最简单的方法是使用画布元素,然后调用下载操作,允许用户选择保存图像的位置。
您提到图像很大,但没有提到多大 - 请注意,使用画布时,当图像源开始触及像素大小的 8k 区域时,您也会遇到限制。
一个简化的例子(IE 将需要一个 polyfill toBlob()):
URL.createObjectURL()toBlob()(在内存和性能上更有效,并且不需要转码到 Base64 或从 Base64 转码)获得Blob.Blob为File(一个子集对象,它将引用相同的内存),因此我们还可以提供文件名以及(重要!)二进制 mime-type。由于最后一步的 MIME 类型是二进制的,浏览器将调用另存为对话框。
document.querySelector("input").onchange = function() {
var img = new Image;
img.onload = convert;
img.src = URL.createObjectURL(this.files[0]);
};
function convert() {
URL.revokeObjectURL(this.src); // free up memory
var c = document.createElement("canvas"), // create a temp. canvas
ctx = c.getContext("2d");
c.width = this.width; // set size = image, draw
c.height = this.height;
ctx.drawImage(this, 0, 0);
// convert to File object, NOTE: we're using binary mime-type for the final Blob/File
c.toBlob(function(blob) {
var file = new File([blob], "MyJPEG.jpg", {type: "application/octet-stream"});
window.location = URL.createObjectURL(file);
}, "image/jpeg", 0.75); // mime=JPEG, quality=0.75
}
// NOTE: toBlob() is not supported in IE, use a polyfill for IE.Run Code Online (Sandbox Code Playgroud)
<label>Select image to convert: <input type=file></label>Run Code Online (Sandbox Code Playgroud)
更新:如果您只是在新创建的 JPEG 的字符串(base-64 编码)版本之后,只需使用toDataURL()而不是toBlob():
document.querySelector("input").onchange = function() {
var img = new Image;
img.onload = convert;
img.src = URL.createObjectURL(this.files[0]);
};
function convert() {
URL.revokeObjectURL(this.src); // free up memory
var c = document.createElement("canvas"), // create a temp. canvas
ctx = c.getContext("2d");
c.width = this.width; // set size = image, draw
c.height = this.height;
ctx.drawImage(this, 0, 0);
// convert to File object, NOTE: we're using binary mime-type for the final Blob/File
var jpeg = c.toDataURL("image/jpeg", 0.75); // mime=JPEG, quality=0.75
console.log(jpeg.length)
}Run Code Online (Sandbox Code Playgroud)
<label>Select image to convert: <input type=file></label>Run Code Online (Sandbox Code Playgroud)