꾸준히 공부하는 개발자

[JS] Canvas image edit from s3 본문

Javascript

[JS] Canvas image edit from s3

kauboy 2020. 2. 18. 19:56

 

S3의 이미지를 가져와 blob 으로 변경 후 canvas에 그려야 작동한다.
또한 s3의 이미지를 encoding한 값을 넣으면 cors 문제로 받아와 지지 않는다고 에러가 났다.

 

그리고 마지막은 다시 s3로 편집한 이미지를 올리는 장면이다.

 

이러한 순서로 진행된다

s3 -> canvas -> s3

const imageEdit = async bool => {
      axios.get(decodeURIComponent(file.src), {responseType: 'blob'}).then( async blob => {

        const objectURL = URL.createObjectURL(blob.data);
        const res = await dataProvider('IMAGE', 'translations', {imagePath: file.path, from: 'zh'})
        const image = await loadImage(objectURL)

        const canvas = document.createElement("canvas");
        canvas.width = image.width
        canvas.height = image.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height);
        for (let i = 0; i < res.data.length; i++) {
          const v = res.data[i].location;
          ctx.fillStyle = 'white';
          ctx.fillRect(v.x0 - 5, v.y0 + 1, (image.width + (image.width * 0.03)) - (image.width - ((v.x1 - v.x0) + v.x0)) - v.x0, ((v.y1 - v.y0) + ((v.y1 - v.y0) * 0.2)) - 4);
          ctx.stroke();
        }

        if (bool === true) {
          for (let j = 0; j < res.data.length; j++) {
            const v = res.data[j].word;
            ctx.font = 'bold 16px Arial'
            ctx.fillStyle = "#000000";
            ctx.fillText(v.text, v.loc.x, v.loc.y + 18)
          }
        }

        const {data: {url, path}} = await dataProvider('UPLOAD', 'files', {
          data: {
            type: 'images',
            category: 'products',
            mimeType: 'image/jpg'
          }
        })

        canvas.toBlob(async blob => {
          await axios.put(url, blob, {headers: {'Content-Type': 'image/jpg'}})
          form.form.change(form.type, [...form.formData[form.type], {src: convertImagePath(path), path: path}])
        }, 'image/jpg')
      })
    }
Comments