이미지 파일 사이즈 알아내기
페이지 정보
작성자 서방님 댓글 0건 조회 113회 작성일 06-09-12 13:38본문
업로드 시 자바 스크립트로 이미지 파일 사이즈 알아내기
자바 스크립트로 이미지 파일 사이즈 알아내기
이미지 게시판이나 업로드 게시판 만들때 가끔 이미지 사이즈를 디비에 넣어야 할때가 있는데 asp나 jsp 말고 javascript로 업로드 전에 이미지 사이즈를 미리 알아내는 방법입니다. 이미지 사이즈 뿐만아니라 이미지인지 체크하고 파일 크기도 알아낼 수도 있습니다. 여러 가지 방법이 있을텐데 전 이걸로 사용하거든요 ^^;
먼저 <input> 테그를 정의합니다.
<input type="file" name="fileName" onChange="uploadImg_Change( this.value )" >
<input type="hidden" name="imgWidth">
<input type="hidden" name="imgHeight">
여기서 부터 <script> 입니다.
<script>
//파일의 확장자를 가져옮
function getFileExtension( filePath )
{
var lastIndex = -1;
lastIndex = filePath.lastIndexOf('.');
var extension = "";
if ( lastIndex != -1 )
{
extension = filePath.substring( lastIndex+1, filePath.len );
} else {
extension = "";
}
return extension;
}
//파일을 선택 후 포커스 이동시 호출
function uploadImg_Change( value )
{
var src = getFileExtension(value);
if (src == "") {
alert('올바른 파일을 입력하세요');
return;
} else if ( !((src.toLowerCase() == "gif") || (src.toLowerCase() == "jpg") || (src.toLowerCase() == "jpeg")) ) {
alert('gif 와 jpg 파일만 지원합니다.');
return;
}
LoadImg( value);
}
function LoadImg(value)
{
var imgInfo = new Image();
imgInfo.onload = img_Load;
imgInfo.src = value;
}
function img_Load()
{
var imgSrc, imgWidth, imgHeight, imgFileSize;
var maxFileSize;
maxFileSize = 5000;
imgSrc = this.src;
imgWidth = this.width;
imgHeight = this.height;
imgFileSize = this.fileSize;
if (imgSrc == "" || imgWidth <= 0 || imgHeight <= 0)
{
alert('그림파일을 가져올 수 없습니다.');
return;
}
if (imgFileSize > maxFileSize)
{
alert('선택하신 그림 파일은 허용 최대크기인 ' + maxFileSize/1024 + ' KB 를 초과하였습니다.');
return;
}
//이미지 사이즈 저장
document.all.imgWidth.value = imgWidth;
document.all.imgHeight.value = imgHeight;
}
</script>
댓글목록
등록된 댓글이 없습니다.