Javascript 将 blob 转换为图像文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50537735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:38:07  来源:igfitidea点击:

Convert blob to image file

javascriptfile-uploadblob

提问by Dave

I am trying to convert an image file captured from an input type=file element without success. Below is my javascript code

我试图转换从 input type=file 元素捕获的图像文件,但没有成功。下面是我的javascript代码

        var img = document.getElementById('myimage');
        var file = document.querySelector('input[type=file]').files[0];
        var reader = new FileReader();
        reader.addEventListener("load", function () {
            var theBlob = reader.result;
            theBlob.lastModifiedDate = new Date();
            theBlob.name = file;
            img.src = theBlob;
            var newfile = new File([theBlob], "c:files/myfile.jpg");

        }, false);

        if (file) {
            reader.readAsDataURL(file);
        }

The image is displayed properly in the img element but the File command does not create the myfile.jpg image file. I am trying to capture the image and then resizing it using javascript before I upload it to the server. Anyone know why the image file is not being created? Better yet, anyone have code on how to resize an image file on the client and then upload it to a server?

图像在 img 元素中正确显示,但 File 命令不会创建 myfile.jpg 图像文件。我正在尝试捕获图像,然后在将其上传到服务器之前使用 javascript 调整其大小。有谁知道为什么没有创建图像文件?更好的是,任何人都有关于如何在客户端上调整图像文件大小然后将其上传到服务器的代码?

回答by YAHsaves

This is how you can get a resized jpeg file from your "myimage" element using Canvas.

这是使用 Canvas 从“myimage”元素获取调整大小的 jpeg 文件的方法。

I commented every line of code so you could understand what I was doing.

我注释了每一行代码,这样你就可以理解我在做什么。

// Set the Width and Height you want your resized image to be
var width = 1920; 
var height = 1080; 


var canvas = document.createElement('canvas');  // Dynamically Create a Canvas Element
canvas.width  = width;  // Set the width of the Canvas
canvas.height = height;  // Set the height of the Canvas
var ctx = canvas.getContext("2d");  // Get the "context" of the canvas 
var img = document.getElementById("myimage");  // The id of your image container
ctx.drawImage(img,0,0,width,height);  // Draw your image to the canvas


var jpegFile = canvas.toDataURL("image/jpeg"); // This will save your image as a 
                                               //jpeg file in the base64 format.

The javascript variable "jpegFile" now contains your image encoded into a URL://Base64 format. Which looks something like this:

javascript 变量“jpegFile”现在包含编码为 URL://Base64 格式的图像。看起来像这样:

// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"

You can put that variable as an image source in HTML code and it will display your image in the browser, or you can upload the Base64 encoded string to the server.

您可以将该变量作为 HTML 代码中的图像源,它会在浏览器中显示您的图像,或者您可以将 Base64 编码的字符串上传到服务器。

Edit: How to convert the file to a blob (binary file) and upload it to the server

编辑:如何将文件转换为 blob(二进制文件)并将其上传到服务器

// This function is used to convert base64 encoding to mime type (blob)
function base64ToBlob(base64, mime) 
{
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];

    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: mime});
}

Now clean the base64 up and then pass it into the function above:

现在清理 base64,然后将其传递给上面的函数:

var jpegFile64 = jpegFile.replace(/^data:image\/(png|jpeg);base64,/, "");
var jpegBlob = base64ToBlob(jpegFile64, 'image/jpeg');  

Now send the "jpegBlob" with ajax

现在用ajax发送“jpegBlob”

var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
  // Uploaded.
};

oReq.send(jpegBlob);

回答by user3210641

You can't manipulate hard drive directly from the browser. What you can do though is create a link that can be downloaded.

您不能直接从浏览器操作硬盘。您可以做的是创建一个可以下载的链接。

To do this change your var newfile = new File([theBlob], "c:files/myfile.jpg");into:

为此,请将您的更改var newfile = new File([theBlob], "c:files/myfile.jpg");为:

const a = document.createElement('a');
a.setAttribute('download', "some image name");
a.setAttribute('href', theBlob);

a.click();