我使用javascript读取大图并附加到文档,图像是垂直的,大小为3024 * 4032:
这是我的代码:
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
并且图像显示为水平:
有人见过这个吗?我该如何解决?谢谢!
答案 0 :(得分: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'

答案 1 :(得分:0)
您可以更改图片的元信息,以便浏览器以正确的方向显示它,或使用CSS transform
旋转图像。
img{
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
显然你应该给图像一个类,这样它就不会旋转页面上的每个图像。
答案 2 :(得分: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
}
)
它正在工作: