Convert blob to image file

倾然丶 夕夏残阳落幕 提交于 2020-02-02 13:32:15

问题


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

        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?


回答1:


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

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.id = "extractFileCanvas";  // Give the canvas an id
canvas.width  = width;  // Set the width of the Canvas
canvas.height = height;  // Set the height of the Canvas
canvas.style.display   = "none";  // Make sure your Canvas is hidden
document.body.appendChild(canvas);  // Insert the canvas into your page


var c=document.getElementById("extractFileCanvas");  // Get canvas from page
var ctx=c.getContext("2d");  // Get the "CTX" 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 = c.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:

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

You can either put that variable to be an image source and it will display your image, or you can upload the Base64 encoded string to the server.

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

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

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

Now send the "jpegBlob" with ajax

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

oReq.send(jpegBlob);



回答2:


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:

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

a.click();


来源:https://stackoverflow.com/questions/50537735/convert-blob-to-image-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!