如何修复图像预览上的图像旋转

时间:2019-04-19 02:43:22

标签: image image-rotation exif-js

当我选择图像时,某些图像在图像预览上旋转。我用来显示选择图像的初始javascript代码是:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#_nc_image_default')
                .attr('src', e.target.result)

        };

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

我正在尝试使用EXIF,但由于图像仍在旋转,所以我做错了。我没有正确调用我的EXIF函数,或者我没有正确返回它。任何帮助将是感激的。

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();


              EXIF.getData(input.files[0], function() {
        // Fetch image tag
        // Create canvas
        var canvas = document.createElement("canvas");
        var img = document.createElement("IMG");
        img.setAttribute('src', e.target.result);

        // run orientation on img in canvas
        orientation(img, canvas);
      });

        reader.onload = function (e) {
            $('#_nc_image_default')
                .attr('src', e.target.result)

        };

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

// END UPLOAD IMAGE PREVIEW

function orientation(img, canvas) {
  // Set variables
  var ctx = canvas.getContext("2d");
  var exifOrientation = '';

  // Set Width and Height
  var width = img.width;
  var height = img.height;

  var MAX_WIDTH = 600;
  if (width > MAX_WIDTH) {
    height *= MAX_WIDTH / width;
    width = MAX_WIDTH;
  }

  console.log(width);
  console.log(height);

  // Check orientation in EXIF metadatas
  EXIF.getData(img, function() {
    var allMetaData = EXIF.getAllTags(this);
    exifOrientation = allMetaData.Orientation;
    console.log('Exif orientation: ' + exifOrientation);
  });

  // set proper canvas dimensions before transform & export
  if (jQuery.inArray(exifOrientation, [5, 6, 7, 8]) > -1) {
    canvas.width = height;
    canvas.height = width;
  } else {
    canvas.width = width;
    canvas.height = height;
  }

  // transform context before drawing image
  switch (exifOrientation) {
    case 2:
      ctx.transform(-1, 0, 0, 1, width, 0);
      break;
    case 3:
      ctx.transform(-1, 0, 0, -1, width, height);
      break;
    case 4:
      ctx.transform(1, 0, 0, -1, 0, height);
      break;
    case 5:
      ctx.transform(0, 1, 1, 0, 0, 0);
      break;
    case 6:
      ctx.transform(0, 1, -1, 0, height, 0);
      break;
    case 7:
      ctx.transform(0, -1, -1, 0, height, width);
      break;
    case 8:
      ctx.transform(0, -1, 1, 0, 0, width);
      break;
    default:
      ctx.transform(1, 0, 0, 1, 0, 0);
  }

  // Draw img into canvas
  ctx.drawImage(img, 0, 0, width, height);
  console.log(canvas.toDataURL());
  var DataURL = canvas.toDataURL();

  UploadFile(DataURL);
}

0 个答案:

没有答案