이미지 서버 업로드전 썸네일작성
트래픽 감소를 위한 프론트에서 업로드 전 썸네일 작성로직입니다.
실제 사용은 이것 + 서버단의 썸네일 로직과 병행하여 사용하고 있습니다.
작동로직 순서
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 | ||
| 2424 | 1년 전 | 1143 | ||
| 2423 | 1년 전 | 1162 | ||
| 2422 |
|
1년 전 | 1838 | |
| 2421 | 1년 전 | 1064 | ||
| 2420 |
|
1년 전 | 1845 | |
| 2419 | 1년 전 | 1154 | ||
| 2418 | 1년 전 | 1142 | ||
| 2417 | 1년 전 | 927 | ||
| 2416 | 1년 전 | 1226 | ||
| 2415 | 1년 전 | 1109 | ||
| 2414 | 1년 전 | 996 | ||
| 2413 | 1년 전 | 1400 | ||
| 2412 |
|
1년 전 | 2004 | |
| 2411 | 1년 전 | 994 | ||
| 2410 | 1년 전 | 1861 | ||
| 2409 | 1년 전 | 1695 | ||
| 2408 | 1년 전 | 1192 | ||
| 2407 | 1년 전 | 1159 | ||
| 2406 | 1년 전 | 833 | ||
| 2405 | 1년 전 | 2044 | ||
| 2404 |
와칸다포에버
|
1년 전 | 1049 | |
| 2403 | 1년 전 | 1125 | ||
| 2402 |
뽕엄능브라
|
1년 전 | 2055 | |
| 2401 | 1년 전 | 1161 | ||
| 2400 | 1년 전 | 1262 | ||
| 2399 | 1년 전 | 1849 | ||
| 2398 | 1년 전 | 1578 | ||
| 2397 | 1년 전 | 1895 | ||
| 2396 | 1년 전 | 1260 | ||
| 2395 | 1년 전 | 1081 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기