Skip to content

Instantly share code, notes, and snippets.

@xl1
Last active November 27, 2019 04:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xl1/55aa630747d7eb4fa97361baa80bab63 to your computer and use it in GitHub Desktop.
Save xl1/55aa630747d7eb4fa97361baa80bab63 to your computer and use it in GitHub Desktop.
<img> で EXIF の回転情報を考慮して表示したい

<img> で EXIF の回転情報を考慮して表示したい

環境

Windows 10

  • Chrome 55
  • Firefox 50
  • IE 11
  • Edge EdgeHTML 14

現状

デジタルカメラや携帯電話のカメラで撮影した画像や、画像加工ソフトウェアで回転させた画像は、EXIF 情報に orientation の情報が含まれており、 一般的な画像ビューアなどは、これを考慮して画像を回転させて表示するようになっている

ところが、HTML ページ上で <img> 要素で表示する際には、この orientation 情報は考慮されないことが多い

  • iOS の Safari では考慮して回転されるらしい(未確認) iOS の Chrome や Firefox などでもそうだと思われる
  • Firefox は image-orientation CSS property をサポートしており、 この値を from-image とすると、orientation に基づいて画像を回転することができる。 このプロパティは Firefox 以外ではサポートされていない (http://caniuse.com/#feat=css-image-orientation)

<img> ではなくブラウザで直接画像ファイルを開いた場合、 Chrome と Firefox では orientation は考慮される。 <iframe src="***.jpg"> として inline frame に直接表示した場合、Chrome では考慮されたがその他のブラウザではだめだった

Chrome Firefox IE Edge Mac Safari iOS
<img> x x x x x o
image-orientation x o x x x x
直接表示 o o x x o? o?
<iframe> o x x x ? ?

結論

今のところは回転して orientation=1 に初期化したファイルをサーバー側で適宜用意しておくのがよさそう

クライアント側で画像データを fetch して EXIF 情報を読んで回転させるようなことはできなくはないが、 クロスオリジンだとだめだし、画像 2 回読むことになるのでブラウザにやってほしい……

blueimp/JavaScript-Load-Image などを使うと簡単にできる

const xhr = new XMLHttpRequest();
xhr.open("GET", "path/to/image.jpg", true);
xhr.responseType = "blob";
xhr.onload = () =>
  loadImage(xhr.response, (img => parentNode.appendChild(img)), { orientation: true });
xhr.send();
@xl1
Copy link
Author

xl1 commented Apr 8, 2017

blueimp/JavaScript-Load-Image@ee0e0db?w=1 URL 指定するだけで blob として fetch してくれるようになったらしい ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment