(() => {
async function compressImage(imgUrl, maxSize) {
const response = await fetch(imgUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const imgBlob = await response.blob();
const imgSize = (imgBlob.size / 1024).toFixed();
if (imgSize < maxSize)
return;
const compressedUrl = await compressBlob(imgBlob, maxSize);
return compressedUrl;
}
async function compressBlob(blob, maxSize) {
const image = new Image();
image.src = URL.createObjectURL(blob);
await new Promise((resolve) => image.onload = resolve);
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
let quality = 0.9;
let compressedBlob;
do {
compressedBlob = await new Promise(
(resolve) => canvas.toBlob(resolve, "image/jpeg", quality)
);
quality -= 0.1;
} while (compressedBlob.size > maxSize * 1024 && quality > 0.1);
URL.revokeObjectURL(image.src);
const dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(compressedBlob);
});
return dataUrl;
}
var plugin = {
constants: {},
noteOption: {
"Optimize note": {
check: async function() {
return true;
},
run: async function(app, noteUUID) {
let maxSizeKB = Number(
await app.prompt("Enter max size in KB. (e.g. 500, 100, 200)")
);
if (!Number.isInteger(maxSizeKB) || maxSizeKB <= 0)
return;
const noteHandle = { uuid: noteUUID };
const images = await app.getNoteImages(noteHandle);
for (const image of images) {
const corsURL = `https://amplenote-plugins-cors-anywhere.onrender.com/${image.src}`;
const compressedUrl = await compressImage(corsURL, maxSizeKB);
if (!compressedUrl)
return;
const fileURL = await app.attachNoteMedia(noteHandle, compressedUrl);
if (!fileURL)
return;
await app.updateNoteImage(noteHandle, image, { src: fileURL });
}
}
}
}
};
var plugin_default = plugin;
return plugin
})