javascript image resize and preview before upload to server

Tony·2021년 8월 17일
0

javascript

목록 보기
20/61
// resize.js
/**
 *
 * @param {{file: inputFileImage.files[0], maxSize: 200}} settings
 */
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'); // input file image/*
const imgPreview = document.querySelector('#imgPreview'); // img for preview

async function postUploadLogo(imageFile) {
  let formData = new FormData();
  // formData.append key('Files')는 서버 API에 따라 달라 질 수 있음
  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() {
  // console.log('before resizing', inputImage.files[0]);
  const config = {
    file: inputImage.files[0],
    maxSize: 200, // resize 할 이미지의 width
  };
  try {
    const resizedImage = await resizeImage(config);

    // blob to file
    const fileFromBlob = new File([resizedImage], inputImage.files[0].name, {
      lastModified: inputImage.files[0].lastModified,
    });

    // upload resized image
    await postUploadLogo(fileFromBlob);

    // preview에 등록
    imgPreview.src = URL.createObjectURL(resizedImage);
    imgPreview.onload = function () {
      URL.revokeObjectURL(imgPreview.src); // free memory
    };
  } catch (error) {
    console.error(error);
  }
}

inputImage.addEventListener('change', resizeImageOnChange);

참고 문헌

profile
움직이는 만큼 행복해진다

0개의 댓글