이미지 서버 업로드전 썸네일작성
트래픽 감소를 위한 프론트에서 업로드 전 썸네일 작성로직입니다.
실제 사용은 이것 + 서버단의 썸네일 로직과 병행하여 사용하고 있습니다.
작동로직 순서
1. 업로드 전 이미지 파일(바이너리)를 프론트에서 읽는다
2. 읽은파일의 넓이를 계산하여 설정 넓이(인자 width)보다 넓은경우
3. base64를 이용하여 canvas로 그린후
4. 다시 base64를 파일로 변환하여 리턴한다.
사용시예시 입니다.
let file_tmp = file[0].files[0];
if(!thumb_width) thumb_width = 1920;
switch( file_tmp.type){
case 'image/png':
case 'image/jpg':
case 'image/jpeg':
thumbnail(file_tmp, thumb_width, function(file_tmp){
//업로드 로직 작성
}
}
function thumbnail(file_tmp, thumb_width, callback) {
var img = new Image();
var reader = new FileReader();
reader.readAsDataURL(file_tmp);
reader.onload = function () {
img.onload = function() {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
let return_file;
canvas.width = thumb_width;
canvas.height = (this.height / this.width) * thumb_width;
if(this.width <= thumb_width) return_file = file_tmp;
else {
ctx.drawImage(
img,
width > height ? (width - height) / 2 : 0,
height > width ? (height - width) / 2 : 0,
width > height ? height : width,
width > height ? height : width,
0, 0,
canvas.width, canvas.height
);
return_file = base642file(canvas.toDataURL(), file_tmp)
}
callback( return_file );
};
img.src = reader.result;
};
};
function base642file(img, org_file){
// 파일 형식으로 변환
const byteCharacters = atob(img.split(',')[1]);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: org_file.type });
const file = new File([blob], org_file.name, { type: org_file.type });
return file;
}
댓글 2개
감사합니다 ^^
감사합니다.
게시판 목록
그누보드5 팁자료실
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 공지 | 3년 전 | 4402 | ||
| 2304 | 2년 전 | 1250 | ||
| 2303 | 2년 전 | 2429 | ||
| 2302 | 2년 전 | 2280 | ||
| 2301 | 2년 전 | 1814 | ||
| 2300 | 2년 전 | 2506 | ||
| 2299 | 2년 전 | 1704 | ||
| 2298 |
종이인형친구
|
2년 전 | 2072 | |
| 2297 | 2년 전 | 3746 | ||
| 2296 | 2년 전 | 1438 | ||
| 2295 | 2년 전 | 1791 | ||
| 2294 | 2년 전 | 1517 | ||
| 2293 | 2년 전 | 1978 | ||
| 2292 |
swallow
|
2년 전 | 2966 | |
| 2291 | 2년 전 | 2204 | ||
| 2290 | 2년 전 | 2372 | ||
| 2289 | 2년 전 | 1928 | ||
| 2288 | 2년 전 | 2168 | ||
| 2287 | 2년 전 | 2757 | ||
| 2286 | 2년 전 | 1821 | ||
| 2285 | 2년 전 | 2212 | ||
| 2284 | 2년 전 | 1647 | ||
| 2283 |
|
2년 전 | 2222 | |
| 2282 |
디지털홍익인간
|
2년 전 | 3664 | |
| 2281 | 2년 전 | 1747 | ||
| 2280 | 2년 전 | 1900 | ||
| 2279 |
|
2년 전 | 1855 | |
| 2278 | 2년 전 | 2078 | ||
| 2277 | 2년 전 | 4699 | ||
| 2276 |
WEBOLUTION
|
2년 전 | 2030 | |
| 2275 | 2년 전 | 2807 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기