Attempt to scale using a canvas element

This commit is contained in:
Eric van der Vlist 2023-04-21 18:53:38 +02:00
parent 4df529abb7
commit a91230f614
2 changed files with 51 additions and 1 deletions

View File

@ -21,6 +21,7 @@ import {
} from '@capacitor/filesystem'; } from '@capacitor/filesystem';
import piexif from 'piexifjs'; import piexif from 'piexifjs';
import { getDate, getGps } from '../../lib/exif'; import { getDate, getGps } from '../../lib/exif';
import { resize } from '../../lib/image';
interface Props { interface Props {
file: File; file: File;
@ -110,6 +111,7 @@ const ImportSingleFile: Component<Props> = ({ file: file }) => {
const id = exifObj.Exif[piexif.ExifIFD.ImageUniqueID]; const id = exifObj.Exif[piexif.ExifIFD.ImageUniqueID];
const gps = getGps(exifObj); const gps = getGps(exifObj);
const date = getDate(exifObj); const date = getDate(exifObj);
const thumbnailUrl = await resize(reader.result, 128);
// const gps = tags.gps; // const gps = tags.gps;
// const image = await Image.load(reader.result); // const image = await Image.load(reader.result);
// const thumbnail = image.resize({ // const thumbnail = image.resize({
@ -129,7 +131,7 @@ const ImportSingleFile: Component<Props> = ({ file: file }) => {
result: reader.result, result: reader.result,
exifObj, exifObj,
}); });
setPicture({ id, gps, date, thumbnailUrl: imageUrl }); setPicture({ id, gps, date, thumbnailUrl });
}, },
false false
); );

48
src/lib/image.ts Normal file
View File

@ -0,0 +1,48 @@
export const resize = (imageUrl: string, maxSize: number) => {
let resolver = (resizedImageUrl: any) => {};
const img = document.createElement('img');
img.onload = () => {
const currentMaxSize = Math.max(img.width, img.height);
const ratio = currentMaxSize / maxSize;
const nbStepsReal = Math.log2(ratio);
const nbSteps = Math.floor(nbStepsReal);
const reminder = maxSize - currentMaxSize / 2 ** nbSteps;
const canvas = document.createElement('canvas');
canvas.width = img.width / 2;
canvas.height = img.height / 2;
const canvasCtx = canvas.getContext('2d');
let src: any = img;
let width = img.width;
let height = img.height;
for (let i = 0; i < nbSteps; i++) {
width = width / 2;
height = height / 2;
canvasCtx?.drawImage(src, 0, 0, width, height);
src = canvas;
}
const finalCanvas = document.createElement('canvas');
finalCanvas.height = height;
finalCanvas.width = width;
const finalCanvasCtx = finalCanvas.getContext('2d');
finalCanvasCtx?.drawImage(
canvas,
0,
0,
width * 4,
height * 4,
0,
0,
width,
height
);
resolver(finalCanvas.toDataURL('image/jpeg'));
};
img.src = imageUrl;
return new Promise((resolve, reject) => {
resolver = resolve;
});
};