(❀╹◡╹)
[JS + PHP] 이미지 업로드 시 자동 회전되는 문제 해결 본문
1. JS로 생성된 cavas 객체를 blob로 생성하여 업로드하는 방법
2. JS로는 미리보기 출력단만 제어, 실제 업로드는 PHP로 처리하는 방법
[JS]
load image 플러그인 사용 > 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
<script src="/static/js/jquery-1.12.4.min.js"></script>
<script src="/static/plugin/load_image/js/load-image.js"></script>
<script src="/static/plugin/load_image/js/load-image-scale.js"></script>
<script src="/static/plugin/load_image/js/load-image-meta.js"></script>
<script src="/static/plugin/load_image/js/load-image-orientation.js"></script>
<script src="/static/plugin/load_image/js/load-image-exif.js"></script>
<script type="text/javascript">
$(function() {
$("#file").on("change", function() {
var file_path = $(this).val().toLowerCase();
var reg = /(.*?)\.(jpg|jpeg|png)$/;
// 허용되지 않은 확장자일 경우
if (file_path != "" && (file_path.match(reg) == null || reg.test(file_path) == false)) {
$("#default_img").attr("src", "/static/images/icon/icon_profile.png");
file_reset($(this));
alert("이미지 파일만 업로드 가능합니다. (jpg, jpeg, png)");
} else {
var input = this;
if (input.files && input.files[0]) {
loadImage(
input.files[0],
function (img) {
$("#default_img").attr("src", img.toDataURL());
},
{maxWidth: 100, orientation:true} // Options
);
}
}
});
});
[PHP]
exif_read_data로 원본 파일의 exif 속성을 읽어옴
orientation 값에 따라 imagerotate 처리 후 해당 파일을 저장하여 처리
// 원본 파일(경로포함), 저장될 경로 및 파일명
function auto_rotation_save($source_file, $dst_dir) {
$imgsize = getimagesize($source_file);
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = 'imagecreatefromgif';
$image = 'imagegif';
break;
case 'image/png':
$image_create = 'imagecreatefrompng';
$image = 'imagepng';
break;
case 'image/jpeg':
$image_create = 'imagecreatefromjpeg';
$image = 'imagejpeg';
break;
default:
return false;
break;
}
$im = $image_create($source_file);
$exif = exif_read_data($source_file);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$im = imagerotate($im, 90, 0);
break;
case 3:
$im = imagerotate($im, 180, 0);
break;
case 6:
$im = imagerotate($im, -90, 0);
break;
}
}
$image($im, $dst_dir, 95);
if($im)imagedestroy($im);
}
'Programing > WEB' 카테고리의 다른 글
[Oracle] MySql Limit 와 같이 데이터 조회하기 (0) | 2020.03.26 |
---|---|
[PHP] preg_match_all 에러 (0) | 2020.02.04 |
[JS] safari에서 animate scrollTop 이 작동하지 않을 경우 (0) | 2020.01.16 |
[JS] safari에서 iframe scroll이 작동하지 않는 경우 (0) | 2020.01.16 |
[JS] safari에서 click 이벤트가 작동하지 않는 경우 (0) | 2020.01.16 |