-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.html
More file actions
92 lines (80 loc) · 2.9 KB
/
test.html
File metadata and controls
92 lines (80 loc) · 2.9 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<title>OPFS Worker Image Demo</title>
</head>
<body>
<button onclick="handleImageSave()">Save Image to OPFS</button>
<button onclick="handleImageLoad()">Load Image from OPFS</button>
<div id="image-container"></div>
<script>
const worker = new Worker('worker.js');
const FILE_ID = 'stored-image';
let currentExtension = '';
worker.onmessage = (e) => {
const { action } = e.data;
switch (action) {
case 'encoded':
console.log('File saved to OPFS:', e.data);
break;
case 'decoded':
handleDecodedImage(e.data);
break;
case 'error':
console.error('Worker error:', e.data);
break;
}
};
async function handleImageSave() {
try {
const [fileHandle] = await window.showOpenFilePicker({
types: [{
description: 'Images',
accept: {'image/*': ['.png', '.jpg', '.jpeg', '.gif']}
}]
});
const file = await fileHandle.getFile();
currentExtension = file.name.split('.').pop();
const buffer = await file.arrayBuffer();
worker.postMessage({
action: 'encode',
id: FILE_ID,
data: new Uint8Array(buffer),
extension: currentExtension
}, [buffer]);
} catch (error) {
if (error.name !== 'AbortError') {
console.error('File selection error:', error);
}
}
}
function handleImageLoad() {
worker.postMessage({
action: 'decode',
id: FILE_ID,
extension: currentExtension
});
}
function handleDecodedImage({ data, extension }) {
const container = document.getElementById('image-container');
container.innerHTML = '';
const blob = new Blob([data], { type: getMimeType(extension) });
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
img.alt = 'OPFS Image';
img.style.maxWidth = '100%';
img.onload = () => URL.revokeObjectURL(url);
container.appendChild(img);
}
function getMimeType(extension) {
return {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif'
}[extension.toLowerCase()] || 'application/octet-stream';
}
</script>
</body>
</html>