Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions js/image-viewer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const isSameOrigin = (url: string) => {
const imgUrl = new URL(url, window.location.href);
return imgUrl.origin === window.location.origin;
} catch {
return true;
return false;
}
};

Expand All @@ -18,6 +18,16 @@ const directDownload = (imgSrc: string, name: string) => {
a.remove();
};

const fileDownload = (obj: Blob | MediaSource, name: string) => {
const url = URL.createObjectURL(obj);
const a = document.createElement('a');
a.href = url;
a.download = name;
a.click();
a.remove();
URL.revokeObjectURL(url);
};

const canvasDownload = (imgSrc: string, name: string) => {
const image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
Expand All @@ -29,31 +39,18 @@ const canvasDownload = (imgSrc: string, name: string) => {

const context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);

const extension = name.split('.').pop()?.toLowerCase() || 'png';
const mimeType = `image/${extension === 'jpg' ? 'jpeg' : extension}`;

canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.download = name;
a.href = url;
a.click();
a.remove();
URL.revokeObjectURL(url);
});
fileDownload(blob, name);
}, mimeType);
};

image.src = imgSrc;
};

const fileDownload = (file: File, name: string) => {
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.download = name;
a.href = url;
a.click();
a.remove();
URL.revokeObjectURL(url);
};

export const downloadFile = (imgSrc: string | File) => {
export const downloadImage = (imgSrc: string | File) => {
const randomName = Math.random().toString(32).slice(2);

if (imgSrc instanceof File) {
Expand Down