これはうまくいくはずです。ここでは、画像ファイルの元の向きを取得し、適切な回転補正を使用してキャンバスを作成します。次に、正しく回転した画像をプレビューとして設定します。
function imagePreview(input,elm) {
// image file
var file = input.files[0];
if (!file.type.match('image/jpeg.*')) {
// image is not a jpeg, do something?
}
var reader = new FileReader();
reader.onload = function(e) {
var exif = piexif.load(e.target.result);
var image = new Image();
image.onload = function () {
//get original orientation of the uploaded image
var orientation = exif["0th"][piexif.ImageIFD.Orientation];
// Build a temperory canvas to manipulate image to required orientation
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
var x = 0;
var y = 0;
ctx.save();
if (orientation == 2) {
x = -canvas.width;
ctx.scale(-1, 1);
} else if (orientation == 3) {
x = -canvas.width;
y = -canvas.height;
ctx.scale(-1, -1);
} else if (orientation == 4) {
y = -canvas.height;
ctx.scale(1, -1);
} else if (orientation == 5) {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width, canvas.height / canvas.width);
ctx.rotate(Math.PI / 2);
y = -canvas.width;
ctx.scale(1, -1);
} else if (orientation == 6) {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width, canvas.height / canvas.width);
ctx.rotate(Math.PI / 2);
} else if (orientation == 7) {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width, canvas.height / canvas.width);
ctx.rotate(Math.PI / 2);
x = -canvas.height;
ctx.scale(-1, 1);
} else if (orientation == 8) {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width, canvas.height / canvas.width);
ctx.rotate(Math.PI / 2);
x = -canvas.height;
y = -canvas.width;
ctx.scale(-1, -1);
}
ctx.drawImage(image, x, y);
ctx.restore();
var dataURL = canvas.toDataURL("image/jpeg", 1.0);
// set the preview image to your element
$(elm).css("background-image","url('"+dataURL+"')");
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
}
$("#settings_img").on("change",function(){
imagePreview(this,"#settings_img_elm");
});
最初にこのライブラリを必ず含めて ください:https : //github.com/hMatoba/piexifjs
ドキュメントから助けを得ました: https ://readthedocs.org/projects/piexif/downloads/pdf/latest/