2017-06-16 105 views
1

我使用JavaScript来读取大量图像,并追加到文档,图像是垂直的,与3024的尺寸* 4032:JavaScript打造的大尺寸图像原因显示的问题

Here is the original image

这里是我的代码:

var image = new Image() 
image.onload = function() { 
    var width = image.width 
    var height = image.height 
    document.body.appendChild(image) 
    console.log('width: ' + width, 'height: ' + height) 
} 
image.src = 'images/01vertical.jpg' 

但为的console.log输出:

width: 4032 height: 3024 

和图像显示的水平:

Here is the display image

有谁遇到了这个?我该如何解决它?谢谢!

+0

你可以试试这个https://nsulistiyawan.github.io/2016/07/11/Fix-image-orientation-with-Javascript.html – gauravmuk

+0

这不是一个问题与图像大小。图像最有可能包含一些旋转信息 - macOS文件浏览器处理它并旋转图像,而您的代码不会。不知道是否可以用JS读取这个元数据。 –

+0

这可能是EXIF属性影响你的形象。这里有一个类似的问题:谢谢你的答案,它的工作原理是:https://stackoverflow.com/questions/7584794/accessing-jpeg-exif-rotation-data-in-javascript-on-the-client-side – Niklas

回答

0

感谢来自@jonLuci答案,这个库固定我的问题: https://github.com/blueimp/JavaScript-Load-Image

和更新我的代码波纹管:

var imageUrl = 'images/01vertical.jpg' 
loadImage(
    imageUrl, 
    function (img) { 
    if (img.type === 'error') { 
     console.log('Error loading image ' + imageUrl) 
    } else { 
     document.body.appendChild(img) 
    } 
    }, 
    { 
    maxWidth: 300, 
    orientation: true 
    } 
) 

,它的工作:

Look like this

0

您可以更改图像的元信息,以便浏览器以正确的方向显示它,或者使用CSS transform旋转图像。

img{ 
    -webkit-transform: rotate(90deg); 
    -moz-transform: rotate(90deg); 
    -o-transform: rotate(90deg); 
    -ms-transform: rotate(90deg); 
    transform: rotate(90deg); 
} 

显然你应该给图像一个类,这样它不会旋转页面上的每个图像。

+0

谢谢你的答案,我通过使用这个库来解决它:https://github.com/blueimp/JavaScript-Load-Image –

2

可以旋转图像:

let image = new Image() 
 
image.onload = function (e) { 
 
    let width = image.width; 
 
    let height = image.height; 
 
    document.body.appendChild(image); 
 
    let el = e ? e.target : window.event.srcElement; 
 
    el.style.transform = 'rotate(+90deg)'; 
 
    console.log('width: ' + width, 'height: ' + height) 
 
} 
 
image.src = 'https://i.stack.imgur.com/OeGAY.png'

+0

这不会也旋转图片,不需要旋转? (大概他需要他的程序使用不止一张图片) –

+0

感谢您的回答,我使用这个库来修复它:https://github.com/blueimp/JavaScript-Load-Image –