【问题标题】:Convert blob to image file将 blob 转换为图像文件
【发布时间】:2018-05-25 22:48:57
【问题描述】:

我正在尝试转换从输入 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);
        }

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

【问题讨论】:

  • 您说的图像在图像文件中正确显示。为什么不直接将其绘制到画布上并将其保存为画布元素之外的 png 或 jpg 呢?调整大小基本上是为您完成的。
  • 如果您需要完整的示例代码,请告诉我,我会将其作为答案发布。
  • 感谢您的回复。我将不胜感激您有关如何获取 jpg 图像的示例代码。

标签: javascript file-upload blob


【解决方案1】:

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

我注释了每一行代码,以便您了解我在做什么。

// 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.

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

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

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

编辑:如何将文件转换为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});
}

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

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

现在用 ajax 发送“jpegBlob”

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

oReq.send(jpegBlob);

【讨论】:

  • 感谢您的代码。如果我想将它上传到服务器,我该如何命名并访问 jpegFile?是 'myimage.src' 还是我需要创建另一个图像文件?
  • @Dave 我编辑了我的问题以解释如何保存图像文件。但是,如果您的服务器无法使用 base64 编码,请告诉我,我将包含如何将其转换为 blob(二进制编码)的代码。您可以通过简单的 ajax 调用将其上传到您的服务器,如果您需要帮助也可以告诉我。
  • 我需要将编码后的图像上传到服务器。如何使用文件名引用图像?我需要引用某种名称,不是吗?我计划使用 Ajax 或 C# 上传文件进行上传。
  • 我将使用 C# 处理服务器上的文件,因为我将在我的 msSQL 数据库中存储文件路径。因此,您在这种情况下可以提供的任何内容都会非常有帮助。
  • @Dave 我刚刚编辑了我的答案,希望对您有所帮助。当您提到在数据库中存储“文件路径”时,我有点困惑。要将图像的路径而不是实际图像本身上传到服务器吗?
【解决方案2】:

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

为此,请将您的 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();

【讨论】:

  • 这真的很酷!我使用了你的代码,它下载到我的下载目录。但是,这是一个正在通过移动设备处理的网页,我不知道文件在移动设备上的位置。有关如何从移动设备获取文件的任何建议?
  • 或者我可以将“下载”更改为上传并指向服务器位置吗?
  • 关于移动设备支持,根据caniuse.com/#feat=downloadAndroid设备应该支持。但不确定它会在哪里下载。
  • 我可以将 Ajax 调用放在下载代码之后,但我不知道是否可以确定文件在移动设备上的位置。进入灰色地带。
  • 你为什么需要这个?
猜你喜欢
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
相关资源
最近更新 更多