티스토리 뷰
앱에서 웹으로 이미지 업로드 할 경우 이미지 정보(exif)에 따라 회전하는 이슈가 있어서
저장 후 exif 이미지 정보를 읽어 orientation 값에 따라서 회전을 해줘야하는 경우가 있다.
이런 작업을 하지 않기 위해
업로드 중간에 exif 파일 정보에서 orientation 값을 읽어 파일을 정상적으로 회전해주고
file을 blob로 변환 후 업로드해주자.
1. orientation 값에 따라 이미지 자동으로 돌려서 img 파일에 넣기
https://github.com/blueimp/JavaScript-Load-Image
blueimp/JavaScript-Load-Image
JavaScript Load Image is a library to load images provided as File or Blob objects or via URL. It returns an optionally scaled and/or cropped HTML img or canvas element. It also provides methods to...
github.com
document.getElementById('file-input').onchange = function (e) {
loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 600, orientation:true} // Options
);
};
2. img 이미지 정보 (blob)를 가지고 와서 업로드하기
Blob은 일련의 데이터를 처리하거나 간접 참조하는 객체다.
var reader = new FileReader();
reader.addEventListener("load", function () {
loadImage(
reader.result,
function (img) {
dataUrl = img.toDataURL("image/jpeg");
var imgtype = dataUrl.split(';');
// 이미지의 컨텐츠 유형을 얻는다.
var contentType = imgtype[0].split(':')[1];
preview.attr('src', dataUrl);
var blob = dataURItoBlob(dataUrl);
var _formData = new FormData();
_formData.append("uploadfile", blob, "blobfile"); <= blobfile 파일 이름 명시하지 않아도 디폴드 값이지만 명시 안하는 경우 에러 나는 경우 있음.
_formData.append("Type", contentType);
var picUrl = "";
$.ajax({
url:_url,
contentType : false,
type:"POST",
dataType: "json",
data:_formData,
cache: false,
processData: false,
error : function(jqXHR, textStatus, errorThrown) {
//alert("error" + textStatus)
},
success:function(data, jqXHR, textStatus){
$.each(data.list, function(key, value){
//alert(result);
//성공
});
}
});
},
{
orientation: true,
maxHeight: 300,
canvas: true
}
);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
function dataURItoBlob(dataURI)
{
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++)
{
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], { "type": mimeString });
return bb;
}