Why convert image to HTML in JavaScript?
How to convert image into HTML?
- Install Aspose.Words for Node.js via .NET.
- Add a library reference (import the library) to your JavaScript project.
- Open the source image file in JavaScript.
- Call the save() method, passing an output filename with HTML extension.
- Get the result of image conversion as HTML.
What is the maximum file size for image to HTML conversion supported by Aspose.Words for Node.js via .NET?
Convert your image src https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg into Base64 ULR format and than convert Base64 URL into javaScript File Object.
***Here is the code for converting "image source" (url) to "Base64".***
let url = 'https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg'
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
***Here is code for converting "Base64" to javascript "File Object".***
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
*** Calling both function ***
toDataURL(url)
.then(dataUrl => {
console.log('Here is Base64 Url', dataUrl)
var fileData = dataURLtoFile(dataUrl, "imageName.jpg");
console.log("Here is JavaScript File Object",fileData)
fileArr.push(fileData)
})
I'm assuming you want to run this in a browser environment.
You can use the native fetch() method, read the response as Blob and convert it to a File object.
contentType should be based on the type of the actual image downloaded.
You can read more about several approaches and browser support to convert a Blob to File here:
Convert blob to file
How to convert Blob to File in JavaScript
const url = 'https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg?v=1572867553'
const fileName = 'myFile.jpg'
fetch(url)
.then(async response => {
const contentType = response.headers.get('content-type')
const blob = await response.blob()
const file = new File([blob], fileName, { contentType })
// access file here
})
The simplest way is to use a canvas element and then invoke a download action allowing the user to select where to save the image.
You mention that the image is large, but not how much - be aware that with canvas you will also run into restrictions when the image source starts to touch around the 8k area in pixel size.
A simplified example (IE will require a polyfill for toBlob()).:
- Load image source via input
- Use File blob directly as image source via
URL.createObjectURL() - When loaded, create a temporary canvas, set canvas size = image size and draw in image
- Use
toBlob()(more efficient on memory and performance and require no transcoding to/from Base64) to obtain aBlob. - We'll convert the
BlobtoFile(a subset object and it will reference the same memory) so we can also give a filename as well as (important!) a binary mime-type.
Since the mime-type for the final step is binary the browser will invoke a Save as dialog.
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.
<label>Select image to convert: <input type=file></label>
Update: If you just are after a string (base-64 encoded) version of the newly created JPEG simply use toDataURL() instead of 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)
}
<label>Select image to convert: <input type=file></label>
JavaScript on the client side can not save files. You have multiple options:
- Render the image on an
<canvas>element. This way it can be saved with right click -> save image - Inset the image as
<img>element. This way it can be saved with right click -> save image - Send the image data as base64 string to the server. Do the processing there
- Use a server side language like PHP or Node.js to save the file
Long story short, you have to use some server side logic to save the file on disk
ยป npm install image-conversion