export const resizeImage = function (settings) {
const file = settings.file;
const maxSize = settings.maxSize;
const reader = new FileReader();
const image = new Image();
const canvas = document.createElement('canvas');
const dataURItoBlob = function (dataURI) {
const bytes =
dataURI.split(',')[0].indexOf('base64') >= 0
? atob(dataURI.split(',')[1])
: unescape(dataURI.split(',')[1]);
const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
const max = bytes.length;
const ia = new Uint8Array(max);
for (let i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
const resize = function () {
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
const dataUrl = canvas.toDataURL('image/png');
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error('Not an image'));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () {
return ok(resize());
};
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
import { resizeImage } from './resize.js';
const inputImage = document.querySelector('#inputImage');
const imgPreview = document.querySelector('#imgPreview');
async function postUploadLogo(imageFile) {
let formData = new FormData();
formData.append('Files', imageFile);
console.log('formData', formData);
try {
const result = await axios.post(
'/URL?Act=Save',
formData,
);
console.log('postUploadLogo result', result);
} catch (error) {
alert('로고가 업로드 되지 않았습니다.');
console.error(error);
}
}
async function resizeImageOnChange() {
const config = {
file: inputImage.files[0],
maxSize: 200,
};
try {
const resizedImage = await resizeImage(config);
const fileFromBlob = new File([resizedImage], inputImage.files[0].name, {
lastModified: inputImage.files[0].lastModified,
});
await postUploadLogo(fileFromBlob);
imgPreview.src = URL.createObjectURL(resizedImage);
imgPreview.onload = function () {
URL.revokeObjectURL(imgPreview.src);
};
} catch (error) {
console.error(error);
}
}
inputImage.addEventListener('change', resizeImageOnChange);
참고 문헌