[javascript] 클라이언트 측에서 JavaScript의 JPEG EXIF ​​회전 데이터에 액세스

JPEG EXIF ​​이미지 데이터에서 카메라가 설정 한 원래 회전을 기준으로 사진을 회전하고 싶습니다. 트릭은이 모든 것이 브라우저에서 자바 스크립트와<canvas> .

JavaScript는 로컬 파일 API 객체 인 JPEG에 어떻게 액세스 할 수 있습니까? <img> 또는 원격 <img>EXIF 데이터에 액세스하여 회전 정보를 읽을 수 있습니까?

서버 측 답변은 좋지 않습니다. 클라이언트 측 솔루션을 찾고 있습니다.



답변

방향 태그 만 원하고 다른 것은 원치 않고 다른 거대한 자바 스크립트 라이브러리를 포함하고 싶지 않다면 가능한 한 빨리 방향 태그를 추출하는 작은 코드를 작성했습니다 (DataView readAsArrayBuffer를 사용하며 IE10 +에서 사용할 수 있지만 작성할 수 있습니다. 이전 브라우저 용 데이터 리더) :

function getOrientation(file, callback) {
    var reader = new FileReader();
    reader.onload = function(e) {

        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8)
        {
            return callback(-2);
        }
        var length = view.byteLength, offset = 2;
        while (offset < length)
        {
            if (view.getUint16(offset+2, false) <= 8) return callback(-1);
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1)
            {
                if (view.getUint32(offset += 2, false) != 0x45786966)
                {
                    return callback(-1);
                }

                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++)
                {
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)
                    {
                        return callback(view.getUint16(offset + (i * 12) + 8, little));
                    }
                }
            }
            else if ((marker & 0xFF00) != 0xFF00)
            {
                break;
            }
            else
            {
                offset += view.getUint16(offset, false);
            }
        }
        return callback(-1);
    };
    reader.readAsArrayBuffer(file);
}

// usage:
var input = document.getElementById('input');
input.onchange = function(e) {
    getOrientation(input.files[0], function(orientation) {
        alert('orientation: ' + orientation);
    });
}
<input id='input' type='file' />

값 :

-2: not jpeg
-1: not defined

여기에 이미지 설명 입력

Typescript를 사용하는 경우 다음 코드를 사용할 수 있습니다.

export const getOrientation = (file: File, callback: Function) => {
  var reader = new FileReader();

  reader.onload = (event: ProgressEvent) => {

    if (! event.target) {
      return;
    }

    const file = event.target as FileReader;
    const view = new DataView(file.result as ArrayBuffer);

    if (view.getUint16(0, false) != 0xFFD8) {
        return callback(-2);
    }

    const length = view.byteLength
    let offset = 2;

    while (offset < length)
    {
        if (view.getUint16(offset+2, false) <= 8) return callback(-1);
        let marker = view.getUint16(offset, false);
        offset += 2;

        if (marker == 0xFFE1) {
          if (view.getUint32(offset += 2, false) != 0x45786966) {
            return callback(-1);
          }

          let little = view.getUint16(offset += 6, false) == 0x4949;
          offset += view.getUint32(offset + 4, little);
          let tags = view.getUint16(offset, little);
          offset += 2;
          for (let i = 0; i < tags; i++) {
            if (view.getUint16(offset + (i * 12), little) == 0x0112) {
              return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
          }
        } else if ((marker & 0xFF00) != 0xFF00) {
            break;
        }
        else {
            offset += view.getUint16(offset, false);
        }
    }
    return callback(-1);
  };

  reader.readAsArrayBuffer(file);
}


답변

HTML5 파일 API ( http://jsfiddle.net/xQnMd/1/) 와 함께 exif-js 라이브러리를 사용할 수 있습니다 .

$("input").change(function() {
    var file = this.files[0];  // file
        fr   = new FileReader; // to read file contents

    fr.onloadend = function() {
        // get EXIF data
        var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));

        // alert a value
        alert(exif.Make);
    };

    fr.readAsBinaryString(file); // read the file
});


답변

Firefox 26 지원 image-orientation: from-image: EXIF ​​데이터에 따라 이미지가 세로 또는 가로로 표시됩니다. ( sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation 참조 )

Chrome에서이를 구현하는 버그 도 있습니다 .

이 속성은 Firefox에서만 지원되며 더 이상 사용되지 않을 수 있습니다 .


답변

https://github.com/blueimp/JavaScript-Load-Image 는 exif 방향 플래그를 추출 할 수있을뿐만 아니라 클라이언트 측에서 JPEG 이미지를 올바르게 미러링 / 회전 할 수도있는 최신 자바 스크립트 라이브러리입니다.

이 라이브러리에서 동일한 문제를 해결했습니다. JS Client-Side Exif Orientation : Rotate and Mirror JPEG Images


답변

크로스 브라우저를 원한다면 가장 좋은 방법은 서버에서하는 것입니다. 파일 URL을 가져와 EXIF ​​데이터를 반환하는 API를 가질 수 있습니다. PHP에는이를위한 모듈이 있습니다.

이것은 Ajax를 사용하여 수행 할 수 있으므로 사용자에게 원활하게 작동합니다. 브라우저 간 호환성에 관심이없고 HTML5 파일 기능 에 의존 할 수 있다면 네이티브 JavaScript에서 해당 데이터를 가져올 수 있는 라이브러리 JsJPEGmeta 를 살펴보십시오 .


답변

exif 방향을 CSS 변환으로 변환하는 내가 작성한 모듈 (브라우저에서 사용할 수 있음)을 확인하십시오 . https://github.com/Sobesednik/exif2css

모든 방향으로 JPEG 픽스쳐를 생성하는이 노드 프로그램도 있습니다 : https://github.com/Sobesednik/generate-exif-fixtures


답변

특히 너비가 높이보다 넓은 img 태그의 경우 오른쪽 회전이있는 일부 img 태그에서 정상적으로 html의 Android 카메라로 사진을 표시하는 확장 코드 업로드 합니다. 이 코드가 추악하다는 것을 알고 있지만 다른 패키지를 설치할 필요가 없습니다. (exif 회전 값을 얻기 위해 위의 코드를 사용했습니다. 감사합니다.)

function getOrientation(file, callback) {
  var reader = new FileReader();
  reader.onload = function(e) {

    var view = new DataView(e.target.result);
    if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
    var length = view.byteLength, offset = 2;
    while (offset < length) {
      var marker = view.getUint16(offset, false);
      offset += 2;
      if (marker == 0xFFE1) {
        if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
        var little = view.getUint16(offset += 6, false) == 0x4949;
        offset += view.getUint32(offset + 4, little);
        var tags = view.getUint16(offset, little);
        offset += 2;
        for (var i = 0; i < tags; i++)
          if (view.getUint16(offset + (i * 12), little) == 0x0112)
            return callback(view.getUint16(offset + (i * 12) + 8, little));
      }
      else if ((marker & 0xFF00) != 0xFF00) break;
      else offset += view.getUint16(offset, false);
    }
    return callback(-1);
  };
  reader.readAsArrayBuffer(file);
}

var isChanged = false;
function rotate(elem, orientation) {
    if (isIPhone()) return;

    var degree = 0;
    switch (orientation) {
        case 1:
            degree = 0;
            break;
        case 2:
            degree = 0;
            break;
        case 3:
            degree = 180;
            break;
        case 4:
            degree = 180;
            break;
        case 5:
            degree = 90;
            break;
        case 6:
            degree = 90;
            break;
        case 7:
            degree = 270;
            break;
        case 8:
            degree = 270;
            break;
    }
    $(elem).css('transform', 'rotate('+ degree +'deg)')
    if(degree == 90 || degree == 270) {
        if (!isChanged) {
            changeWidthAndHeight(elem)
            isChanged = true
        }
    } else if ($(elem).css('height') > $(elem).css('width')) {
        if (!isChanged) {
            changeWidthAndHeightWithOutMargin(elem)
            isChanged = true
        } else if(degree == 180 || degree == 0) {
            changeWidthAndHeightWithOutMargin(elem)
            if (!isChanged)
                isChanged = true
            else
                isChanged = false
        }
    }
}


function changeWidthAndHeight(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', ((getPxInt(height) - getPxInt(width))/2).toString() + 'px')
    e.css('margin-left', ((getPxInt(width) - getPxInt(height))/2).toString() + 'px')
}

function changeWidthAndHeightWithOutMargin(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', '0')
    e.css('margin-left', '0')
}

function getPxInt(pxValue) {
    return parseInt(pxValue.trim("px"))
}

function isIPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

다음과 같은 사용

$("#banner-img").change(function () {
    var reader = new FileReader();
    getOrientation(this.files[0], function(orientation) {
        rotate($('#banner-img-preview'), orientation, 1)
    });

    reader.onload = function (e) {
        $('#banner-img-preview').attr('src', e.target.result)
        $('#banner-img-preview').css('display', 'inherit')

    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);

});