programing tip

img 태그가 잘못된 방향을 표시합니다

itbloger 2020. 8. 2. 17:39
반응형

img 태그가 잘못된 방향을 표시합니다


이 링크에 이미지가 있습니다 : http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg

보시다시피, 이것은 올바른 방향의 정상적인 이미지입니다. 그러나이 링크를 이미지 태그의 src 속성으로 설정하면 이미지가 거꾸로됩니다. http://jsfiddle.net/7j5xJ/

<img src="http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg" width="200"/>

무슨 일이 일어나고 있는지 아십니까?


해결책의 일부를 찾았습니다. 이미지에는 이제 사진의 방향을 지정하는 메타 데이터가 있습니다. 에 대한 새로운 CSS 사양이image-orientation 있습니다.

CSS에 이것을 추가하십시오.

img {
    image-orientation: from-image;
}

2016 년 1 월 25 일의 사양에 따르면 Firefox 및 iOS Safari (접두사 뒤에 있음)가이를 지원하는 유일한 브라우저입니다. Safari 및 Chrome에 여전히 문제가 있습니다. 그러나 모바일 Safari는 기본적으로 CSS 태그가없는 방향을 지원하는 것 같습니다.

브라우저가 지원을 시작할지 기다려야한다고 가정 image-orientation합니다.


이미지가 실제로 거꾸로되어 있습니다. 그러나 메타 속성 "Orientation"은 시청자에게 180도 회전해야 함을 알려줍니다. 일부 장치 / 뷰어는이 규칙을 따르지 않습니다.

Chrome에서 열기 : 올바른 방법 FF로 열기 : 올바른 방법 IE에서 열기 : 거꾸로

그림판에서 열기 : 거꾸로 Photoshop에서 열기 : 올바른 방법. 기타


여기에 내 답변을 추가하는 것을 잊었습니다. Ruby on Rails를 사용했기 때문에 PHP 또는 다른 프레임 워크의 프로젝트에는 적용되지 않을 수 있습니다. 제 경우에는 이미지 업로드에 Carrierwave gem을 사용하고있었습니다. 내 솔루션은 파일을 저장하기 전에 EXIF ​​문제를 해결하기 위해 업 로더 클래스에 다음 코드를 추가하는 것이 었습니다.

process :fix_exif_rotation
def fix_exif_rotation
  manipulate! do |img|
    img.auto_orient!
    img = yield(img) if block_given?
    img
  end
end

이 답변은 Exif-JS 사용하여 bsap의 답변을 기반으로 하지만 jQuery에 의존하지 않으며 이전 브라우저와도 상당히 호환됩니다. 다음은 예제 html 및 js 파일입니다.

rotate.html :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
  <html>
  <head>
    <style>
      .rotate90 {
       -webkit-transform: rotate(90deg);
       -moz-transform: rotate(90deg);
       -o-transform: rotate(90deg);
       -ms-transform: rotate(90deg);
       transform: rotate(90deg);
      }
      .rotate180 {
       -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
       -o-transform: rotate(180deg);
       -ms-transform: rotate(180deg);
       transform: rotate(180deg);
      }
      .rotate270 {
       -webkit-transform: rotate(270deg);
       -moz-transform: rotate(270deg);
       -o-transform: rotate(270deg);
       -ms-transform: rotate(270deg);
       transform: rotate(270deg);
      }
    </style>
  </head>
  <body>
    <img src="pic/pic03.jpg" width="200" alt="Cat 1" id="campic" class="camview">
    <script type="text/javascript" src="exif.js"></script>
    <script type="text/javascript" src="rotate.js"></script>
  </body>
  </html>

rotate.js :

window.onload=getExif;
var newimg = document.getElementById('campic');
function getExif() {
    EXIF.getData(newimg, function() {
            var orientation = EXIF.getTag(this, "Orientation");
            if(orientation == 6) {
                newimg.className = "camview rotate90";
            } else if(orientation == 8) {
                newimg.className = "camview rotate270";
            } else if(orientation == 3) {
                newimg.className = "camview rotate180";
            }
        });
};

Exif-JS를 사용 하여 이미지의 "방향"속성을 확인할 수 있습니다 . 그런 다음 필요에 따라 CSS 변환을 적용하십시오.

EXIF.getData(imageElement, function() {
                var orientation = EXIF.getTag(this, "Orientation");

                if(orientation == 6)
                    $(imageElement).css('transform', 'rotate(90deg)')
});  

삼성 전화가 통합 한 EXIF ​​데이터입니다.


png로 저장하면 문제가 해결되었습니다.


이 문제는 나를 미치게했다. 서버 측에서 PHP를 사용하고 있었기 때문에 @The Lazy Log (ruby) & @deweydb (python) 솔루션을 사용할 수 없었습니다. 그러나 그것은 올바른 방향으로 나를 가리 켰습니다. Imagick의 getImageOrientation ()을 사용하여 백업 파일에 고정했습니다.

<?php 
// Note: $image is an Imagick object, not a filename! See example use below. 
function autoRotateImage($image) { 
    $orientation = $image->getImageOrientation(); 

    switch($orientation) { 
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees 
        break; 

        case imagick::ORIENTATION_RIGHTTOP: 
            $image->rotateimage("#000", 90); // rotate 90 degrees CW 
        break; 

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW 
        break; 
    } 

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! 
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); 
} 
?> 

Here is the link if you want to read more. http://php.net/manual/en/imagick.getimageorientation.php


Until CSS: image-orientation:from-image; is more universally supported we are doing a server side solution with python. Here's the gist of it. You check the exif data for orientation, then rotate the image accordingly and resave.

We prefer this solution over client side solutions as it does not require loading extra libraries client side, and this operation only has to happen one time on file upload.

if fileType == "image":
    exifToolCommand = "exiftool -j '%s'" % filePath
    exif = json.loads(subprocess.check_output(shlex.split(exifToolCommand), stderr=subprocess.PIPE))
    if 'Orientation' in exif[0]:
        findDegrees, = re.compile("([0-9]+)").search(exif[0]['Orientation']).groups()
        if findDegrees:
            rotateDegrees = int(findDegrees)
            if 'CW' in exif[0]['Orientation'] and 'CCW' not in exif[0]['Orientation']:
                rotateDegrees = rotateDegrees * -1
            # rotate image
            img = Image.open(filePath)
            img2 = img.rotate(rotateDegrees)
            img2.save(filePath)

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.


An easy way to the fix the problem, sans coding, is to use Photoshop's Save for Web export function. In the dialog box one can chose to remove all or most of an image's EXIF data. I usually just keep copyright and contact info. Also, since images coming directly from a digital camera are greatly oversized for web display it is a good idea to downsize them via Save for the Web anyway. For those that are not Photoshop savvy, I have no doubt that there are online resources for resizing an image and stripping it of any unnecessary EXIF data.


I think there are some issues in browser auto fix image orientation, for example, if I visit the picture directly, it shows the right orientation, but show wrong orientation in some exits html page.


It happens since original orientation of image is not as we see in image viewer. In such cases image is displayed vertical to us in image viewer but it is horizontal in actual.

To resolve this do following:

  1. Open image in image editor like paint ( in windows ) or ImageMagick ( in linux).

  2. Rotate image left/right.

  3. Save the image.

This should resolve the issue permanently.


Use external styling. in the html sheet give the class name to the tag. in the style sheet use dot operator preceeded by class name and then write the following code

.rotate180 {
 -webkit-transform: rotate(180deg);
 -moz-transform: rotate(180deg);
 -o-transform: rotate(180deg);
 -ms-transform: rotate(180deg);
 transform: rotate(180deg);
 }

참고URL : https://stackoverflow.com/questions/24658365/img-tag-displays-wrong-orientation

반응형