Web

JavaScript로 이미지 파일 데이터 다루기

헤일 2023. 8. 31. 23:05

브라우저에서 이미지를 비롯한 바이너리 파일을 다룰 일이 종종 생긴다. 작업할때마다 매번 찾아보게 되는 것들이 있어서 이참에 정리해보려고 한다. 

이미지 MIME type

다음과 같이 이미지 File 객체의 type으로 판단할 수 있다. Blob 객체의 readonly attribute로서 존재한다. 

filepicker.addEventListener("change", (event) => {
  const files = event.target.files;

  for (const file of files) {
    console.log(file.type)
    // 해당 파일이 webp 형식의 이미지인지 확인하려면?
    console.log(file.type === 'image/webp')
  }
});

이미지 용량

다음과 같이 File 객체의 size로 판단할 수 있다. MIME type과 마찬가지로  Blob 객체의 readonly attribute로서 존재한다. 기본적으로 바이트(bytes) 단위의 용량을 반환한다. 따라서 kb, mb 단위로 바꿔 쓰려면 1024로 나누는 추가 작업을 해줘야 한다. 

input.addEventListener("change", (event) => {

  for (const file of event.target.files) {
    console.log(`${file.name} 파일의 용량은 ${file.size} 바이트입니다.`);
    console.log(`${file.name} 파일의 용량은 ${file.size / 1024} kb입니다.`);
  }
});

이미지 가로/세로 크기

기본적으로 Image object에는 width, height라는 프로퍼티가 존재한다. 그러나 Blob 파일을 다루는 상황에서는 이미지 객체가 존재할 리 없다. 따라서 새로운 Image 객체를 생성한 뒤, onload 이벤트가 들어가는 시점에야 비동기로 이미지 파일의 width와 height를 구할 수 있다. 

또한 createObjectURL을 통해 Blob 객체 url을 생성하고 이미지를 나타낼 수 있다. 이를 통해 생성된 window의 document에서만 접근 가능한 url이 생성된다. 이때 같은 객체를 사용하더라도, createObjectURL()을 매번 호출할 때마다 새로운 객체 URL을 생성하게 된다. 따라서 url이 더 이상 필요없어질 때, revokeObjectURL을 사용해 하나씩 해제해주는 식으로 메모리 관리가 필요하다. 

const image = new Image()
image.src = URL.createObjectURL(file)
image.onload = () => {
	console.log(`이미지 너비: ${image.naturalWidth}, 높이: ${image.naturalHeight}`)
	URL.revokeObjectURL(image.src)
}
image.onerror = () => {
	console.error(`이미지를 처리할 수 없습니다.`)
	URL.revokeObjectURL(image.src)
}

Reference

https://w3c.github.io/FileAPI/#dfn-type 

 

File API

Conformance Document conventions Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD N

w3c.github.io

https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#choosing_an_image_format

https://developer.mozilla.org/en-US/docs/Web/API/Blob/size

 

Image file type and format guide - Web media technologies | MDN

In this guide, we'll cover the image file types generally supported by web browsers, and provide insights that will help you select the most appropriate formats to use for your site's imagery.

developer.mozilla.org