JSFiddle - React, Tailwind, and code Playground
UTIF.js Demo with Web Worker, Offscreen Canvas, and Image Scaling
by skibulk
HTML
<input id="browse" type="file">
JavaScript
/* To-Do:
Use Queue
see terminate() to stop workers
Compare rgb arrays: https://stackoverflow.com/a/21554107/6465140
Multi-Page TIFF Example File:
https://www.nightprogrammer.org/development/multipage-tiff-example-download-test-image-file/
Bug:
https://github.com/photopea/UTIF.js/issues/42
*/
console.clear();
// Instantiate fileConverter as a web worker
var myWorker = toWorker(imageReader);
// Receive image data and add to canvas
myWorker.onmessage = function(event) {
var bitmap = event.data;
console.log("Received Image Data at Root", bitmap);
// Create Canvas element
var myCanvas = document.createElement("canvas");
myCanvas.width = bitmap.width;
myCanvas.height = bitmap.height;
// Add image to canvas and canvas to DOM
var context = myCanvas.getContext("bitmaprenderer");
context.transferFromImageBitmap(bitmap);
document.body.appendChild(myCanvas);
};
// Handle user file selection
var browse = document.getElementById("browse");
browse.onchange = function(event) {
// Pass local file to the handlePDF worker
var file = event.target.files[0];
console.log(file);
myWorker.postMessage(file);
}
// Convert a class or function into a web worker
function toWorker(fn) {
// Web Workers require a file URL to instantiate
// Create a blob file / url to satisfy the web worker
var url = URL.createObjectURL(
new Blob([
'(' + fn.toString() + ')();'
], {
type: 'application/javascript'
})
);
// Initialize the web worker and release the blob file / url from memory
var w = new Worker(url);
URL.revokeObjectURL(url);
url = null;
return w;
}
// Read and Convert a file into a binary array
function imageReader() {
importScripts("https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.10/pako.js");
importScripts("https://cdn.jsdelivr.net/gh/photopea/UTIF.js/UTIF.js");
// Receive the file
onmessage = function(event) {
// console.log("imageReader Received a File", event);
// Read the file
var...