Repository navigation
Expand file tree
/
Copy pathcomb-heic.js
More file actions
26 lines (26 loc) · 2.38 KB
/
Copy pathcomb-heic.js
File metadata and controls
26 lines (26 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. See LICENSE.md. No warranty.
Opens HEIC/HEIF photos in the page using libheif (LGPL-3.0, see libheif-LICENSE.txt), loaded only when a HEIC file is picked.
Everything runs on the device. Returns a canvas that behaves like a loaded image. */
(function(){'use strict';
var loading=null,mod=null;
function isHeic(f,head){var n=(f.name||'').toLowerCase(),t=(f.type||'').toLowerCase();
if(/^image\/hei[cf]/.test(t)||/\.(heic|heif|hif)$/.test(n))return true;
if(head&&head.length>=12&&head[4]===0x66&&head[5]===0x74&&head[6]===0x79&&head[7]===0x70){var b=String.fromCharCode(head[8],head[9],head[10],head[11]);return /^(heic|heix|hevc|hevx|heim|heis|mif1|msf1)$/.test(b)}
return false}
function loadLib(){if(mod)return Promise.resolve(mod);
if(loading)return loading;
loading=new Promise(function(res,rej){var s=document.createElement('script');s.src='libheif-bundle.js';s.async=true;
s.onload=function(){try{var m=typeof window.libheif==='function'?window.libheif():window.libheif;Promise.resolve(m).then(function(x){if(x&&x.HeifDecoder){mod=x;res(x)}else rej(new Error('HEIC support did not start'))},function(){rej(new Error('HEIC support did not start'))})}catch(e){rej(new Error('HEIC support did not start'))}};
s.onerror=function(){loading=null;rej(new Error('HEIC support could not be loaded. Check your connection once, then it works offline.'))};document.head.appendChild(s)});
return loading}
function decode(file){return Promise.all([loadLib(),file.arrayBuffer()]).then(function(r){var lib=r[0],u8=new Uint8Array(r[1]),dec=new lib.HeifDecoder(),imgs;
try{imgs=dec.decode(u8)}catch(e){throw new Error('That HEIC file could not be read.')}
if(!imgs||!imgs.length)throw new Error('That HEIC file has no picture in it.');
var im=imgs[0],w=im.get_width(),h=im.get_height();
return new Promise(function(res,rej){var id=new ImageData(w,h);
im.display({data:id.data,width:w,height:h},function(out){
if(!out){rej(new Error('That HEIC file could not be converted.'));return}
var c=document.createElement('canvas');c.width=w;c.height=h;c.getContext('2d').putImageData(id,0,0);
c.naturalWidth=w;c.naturalHeight=h;try{im.free&&im.free()}catch(_){}res(c)})})})}
window.COMBHEIC={isHeic:isHeic,open:function(file){return file.slice(0,16).arrayBuffer().then(function(b){return isHeic(file,new Uint8Array(b))?decode(file):null})}};
})();