尝试使用jQuery在客户端修复图像的方向。 [EXIF未定义]

时间:2017-10-28 14:50:34

标签: javascript jquery exif exif-js

我正在尝试检测图像的EXIF数据(方向)并在选中时不显示它而显示它。 对于图像预览,正在使用FileReader API。 我能够修复服务器端方向,但对于前端我遇到了麻烦。

我正在使用this library来获取图片的EXIF数据。

我已将exif.js导入我的项目。

<script src="frontend/js/exif.js">

HTML

<input id="choose-img" accept="image/*" name="image" type="file" onchange="readURLimg(this);">
<img class="img-uploaded" id="img-file">

的jQuery

function readURLimg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
         /* Check Exif and fix orientation of image */
            EXIF.getData([0], function() {
                console.log('Exif=', EXIF.getTag(this, "Orientation"));
                switch(parseInt(EXIF.getTag(this, "Orientation"))) {
                    case 2:
                        $img.addClass('flip'); break;
                    case 3:
                        $img.addClass('rotate-180'); break;
                    case 4:
                        $img.addClass('flip-and-rotate-180'); break;
                    case 5:
                        $img.addClass('flip-and-rotate-270'); break;
                    case 6:
                        $img.addClass('rotate-90'); break;
                    case 7:
                        $img.addClass('flip-and-rotate-90'); break;
                    case 8:
                        $img.addClass('rotate-270'); break;
                }
            });

            $('#img-file').attr('src', e.target.result).width('50%').height('auto');

        reader.readAsDataURL(input.files[0]);
    }
}

在我的控制台中,我收到此错误:

  

未捕获的ReferenceError:未定义EXIF   FileReader.reader.onload

任何建议?

1 个答案:

答案 0 :(得分:2)

这有用吗?

function readURLimg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = $('#img-file')
            img.attr('src', e.target.result).width('50%').height('auto');
            fixExifOrientation(img)
        }
        reader.readAsDataURL(input.files[0]);
    }
}
function fixExifOrientation($img) {
    $img.on('load', function() {
        EXIF.getData($img[0], function() {
            console.log('Exif=', EXIF.getTag(this, "Orientation"));
            switch(parseInt(EXIF.getTag(this, "Orientation"))) {
                case 2:
                    $img.addClass('flip'); break;
                case 3:
                    $img.addClass('rotate-180'); break;
                case 4:
                    $img.addClass('flip-and-rotate-180'); break;
                case 5:
                    $img.addClass('flip-and-rotate-270'); break;
                case 6:
                    $img.addClass('rotate-90'); break;
                case 7:
                    $img.addClass('flip-and-rotate-90'); break;
                case 8:
                    $img.addClass('rotate-270'); break;
            }
        });
    });
}
相关问题