[php] 이미지 파일 미리보기 (preview local image file) > 팁앤테크

본문 바로가기
사이트 내 전체검색

팁앤테크

[php] 이미지 파일 미리보기 (preview local image file)

페이지 정보

본문

html 상의 input:file에서 선택한 이미지 파일을 서버에 업로드하지 않고 미리보기하는 방법은 크게 2가지임.
하나는 FileReader를 이용하는 방법이고, 하나는 IE 전용 filter를 이용하는 방법.

FileReader의 경우 왠만한 최신 브라우저는 다 지원함.

http://caniuse.com/#feat=filereader <- 지원하는 브라우저는 여기서 확인가능.
IE의 경우 IE10부터 FileReader가 있고 그 하위버전은 filter를 이용해야 함.


개인적으로 로컬 이미지 파일 미리보기를 테스트해서 성공한 브라우저는 다음과 같음.

Chrome 37.0.2062.124

FireFox 32.0.3

Opera 24.0.1558.64

IE11 (10,9,8,7은 에뮬레이션 모드로 테스트)

아이폰 Safari


Safari5 의 경우 FileReader도 없고 filter도 없어서 미리보기가 불가능했음. (Safari6 부터는 FileReader 있음)


아래는 jQuery용으로 만든 로컬 이미지 미리보기.

소스만 긁어서 바로 테스트할 수 있도록 html 파일 전체 소스를 올림.


<!doctype html>
 
 
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
 
<script>
$.fn.setPreview = function(opt){
    "use strict"
    var defaultOpt = {
        inputFile: $(this),
        img: null,
        w: 200,
        h: 200
    };
    $.extend(defaultOpt, opt);
 
    var previewImage = function(){
        if (!defaultOpt.inputFile || !defaultOpt.img) return;
 
        var inputFile = defaultOpt.inputFile.get(0);
        var img       = defaultOpt.img.get(0);
 
        // FileReader
        if (window.FileReader) {
            // image 파일만
            if (!inputFile.files[0].type.match(/image\//)) return;
 
            // preview
            try {
                var reader = new FileReader();
                reader.onload = function(e){
                    img.src = e.target.result;
                    img.style.width  = defaultOpt.w+'px';
                    img.style.height = defaultOpt.h+'px';
                    img.style.display = '';
                }
                reader.readAsDataURL(inputFile.files[0]);
            } catch (e) {
                // exception...
            }
        // img.filters (MSIE)
        } else if (img.filters) {
            inputFile.select();
            inputFile.blur();
            var imgSrc = document.selection.createRange().text;
 
            img.style.width  = defaultOpt.w+'px';
            img.style.height = defaultOpt.h+'px';
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enable='true',sizingMethod='scale',src=\""+imgSrc+"\")";          
            img.style.display = '';
        // no support
        } else {
            // Safari5, ...
        }
    };
 
    // onchange
    $(this).change(function(){
        previewImage();
    });
};
 
 
$(document).ready(function(){
    var opt = {
        img: $('#img_preview'),
        w: 200,
        h: 200
    };
 
    $('#input_file').setPreview(opt);
});
</script>
</head>
 
 
<body>
<input type="file" id="input_file" />
<br />
<img id="img_preview" style="display:none;"/>
 
</body>
</html>

 

좋은 정보가 있어서 담아 왔습니다.  

***************************************

높이값을 자동으로 하려면

 

h: 200 를 h: 'auto'로 바꾸시고

img.style.height = defaultOpt.h+'px'; 에서

px단위를 지워주시면 됩니다.

 

셈플소스

*******************************************

 
<!doctype html>
 
 
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
 
<script>
$.fn.setPreview = function(opt){
    "use strict"
    var defaultOpt = {
        inputFile: $(this),
        img: null,
        w: 200,
        h: 'auto'
    };
    $.extend(defaultOpt, opt);
 
    var previewImage = function(){
        if (!defaultOpt.inputFile || !defaultOpt.img) return;
 
        var inputFile = defaultOpt.inputFile.get(0);
        var img       = defaultOpt.img.get(0);
 
        // FileReader
        if (window.FileReader) {
            // image 파일만
            if (!inputFile.files[0].type.match(/image\//)) return;
 
            // preview
            try {
                var reader = new FileReader();
                reader.onload = function(e){
                    img.src = e.target.result;
                    img.style.width  = defaultOpt.w+'px';
                    img.style.height = defaultOpt.h;
                    img.style.display = '';
                }
                reader.readAsDataURL(inputFile.files[0]);
            } catch (e) {
                // exception...
            }
        // img.filters (MSIE)
        } else if (img.filters) {
            inputFile.select();
            inputFile.blur();
            var imgSrc = document.selection.createRange().text;
 
            img.style.width  = defaultOpt.w+'px';
            img.style.height = defaultOpt.h;
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enable='true',sizingMethod='scale',src=\""+imgSrc+"\")";          
            img.style.display = '';
        // no support
        } else {
            // Safari5, ...
        }
    };
 
    // onchange
    $(this).change(function(){
        previewImage();
    });
};
 
 
$(document).ready(function(){
    var opt = {
        img: $('#img_preview'),
        w: 200,
        h: 'auto'
    };
 
    $('#input_file').setPreview(opt);
});
</script>
</head>
 
 
<body>
<input type="file" id="input_file" />
<br />
<img id="img_preview" style="display:none;"/>
 
</body>
</html> 

추천0

댓글목록

등록된 댓글이 없습니다.

Total 825건 7 페이지
  • RSS
팁앤테크 목록
번호 제목 글쓴이 조회 추천 날짜
675 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 22251 0 07-23
674 메빅맨쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 14296 0 09-19
673 메빅맨쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13198 0 09-19
672 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 15267 0 10-10
671 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13226 0 12-31
670 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13482 0 12-26
669 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13555 0 12-05
668 명예쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13722 0 12-16
667 월드컵쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 26889 0 12-22
666 귀여운현호쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 12604 0 10-24
665 귀여운현호쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 15661 0 10-24
664 귀여운현호쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 12464 0 10-24
663 디란도쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13069 0 10-26
662 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 17056 0 11-01
661 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 12943 0 11-01
660 미믹스쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13002 0 10-26
659 백작쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13645 0 11-03
658 디란도쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13467 0 11-08
657 오타짱쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 14482 0 03-22
656 연후아빠쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 17908 0 03-27
655 연후아빠쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 12546 0 05-29
654 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 13747 0 07-31
653 제로쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 15380 0 10-22
652 귀여운현호쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 12017 0 10-23
651 힘쓰쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 14277 0 01-03

검색

회원로그인

회원가입

사이트 정보

株式会社YHPLUS / 대표 : ZERO
〒140-0011 東京都品川区東大井2-5-9-203
050-5539-7787
오픈카카오톡 (YHPLUS) :
https://open.kakao.com/o/slfDj15d

접속자집계

오늘
5,579
어제
4,969
최대
7,259
전체
1,289,713
Copyright (c) 株式会社YHPLUS. All rights reserved.