forked from cory/tildefriends
Convert images to webp when uploading.
git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@4012 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
@ -59,16 +59,39 @@ class TfComposeElement extends LitElement {
|
||||
preview.innerHTML = tfutils.markdown(text);
|
||||
}
|
||||
|
||||
convert_to_webp(buffer, type) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
let img = new Image();
|
||||
img.onload = function() {
|
||||
let canvas = document.createElement('canvas');
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
let context = canvas.getContext('2d');
|
||||
context.drawImage(img, 0, 0);
|
||||
let data_url = canvas.toDataURL('image/webp');
|
||||
let result = atob(data_url.split(',')[1]).split('').map(x => x.charCodeAt(0));
|
||||
resolve(result);
|
||||
}
|
||||
img.onerror = function(event) {
|
||||
reject(new Error('Failed to load image.'));
|
||||
};
|
||||
let raw = Array.from(new Uint8Array(buffer)).map(b => String.fromCharCode(b)).join('');
|
||||
let original = `data:${type};base64,${btoa(raw)}`;
|
||||
img.src = original;
|
||||
});
|
||||
}
|
||||
|
||||
add_file(file) {
|
||||
let self = this;
|
||||
file.arrayBuffer().then(function(buffer) {
|
||||
let bin = Array.from(new Uint8Array(buffer));
|
||||
return self.convert_to_webp(buffer, file.type);
|
||||
}).then(function(bin) {
|
||||
return Promise.all([tfrpc.rpc.store_blob(bin), bin]);
|
||||
}).then(function([id, bin]) {
|
||||
self.mentions[id] = {
|
||||
link: id,
|
||||
name: file.name,
|
||||
type: file.type,
|
||||
type: 'image/webp',
|
||||
size: bin.length,
|
||||
};
|
||||
self.mentions = Object.assign({}, self.mentions);
|
||||
@ -76,13 +99,13 @@ class TfComposeElement extends LitElement {
|
||||
edit.value += `\n`;
|
||||
self.changed();
|
||||
}).catch(function(e) {
|
||||
alert(e.message);
|
||||
alert(e?.message);
|
||||
});
|
||||
}
|
||||
|
||||
paste(event) {
|
||||
let self = this;
|
||||
for(let item of event.clipboardData.items) {
|
||||
for (let item of event.clipboardData.items) {
|
||||
if (item.type?.startsWith('image/')) {
|
||||
let file = item.getAsFile();
|
||||
if (!file) {
|
||||
|
Reference in New Issue
Block a user