如何告诉 docx.js 使用图像的自然高度和宽度?



我正在获取图像的二进制数据作为ArrayBuffer,并使用docx.js:将其插入文档中

getImageBinaryDataAsArrayBuffer().then(function (imageBuffer) {
var doc = new docx.Document();
var image = docx.Media.addImage(doc, imageBuffer);
doc.addSection({
children: [
new docx.Paragraph({
children: [image],
alignment: docx.AlignmentType.CENTER
}),
]
});
docx.Packer.toBlob(doc).then(function (blob) {
// save the doc somewhere
})
}).catch(function (err) {
console.log(err);
});

这是有效的,但图像大小似乎默认为100x100,并且没有保留纵横比。在Images的docx.js文档中,当您将图像添加到文档时,似乎可以指定高度和宽度:

Media.addImage(doc, [IMAGE_BUFFER], [WIDTH], [HEIGHT], [POSITION_OPTIONS]);

但我不知道图像的自然高度和宽度,因为我所使用的只是ArrayBuffer。(你能从ArrayBuffer数据中确定图像的高度和宽度吗?我的直觉说不行…(

有没有办法告诉docx.js使用图像的自然高度和宽度?或者至少是为了保持纵横比?

您也可以从二进制格式中获取图像维度。这是我的代码,当你需要将图像调整到特定的宽度/高度时,它会保留纵横比

import imageSize from 'image-size'; // https://www.npmjs.com/package/image-size

function fitImage(doc, image, targetWidth?, targetHeight?) {

const originalSize = imageSize(image);
const originalAspectRatio = originalSize.width / originalSize.height;
let width: number;
let height: number;
if (!targetWidth) {
// fixed height, calc width
height = targetHeight;
width = height * originalAspectRatio;
} else if (!targetHeight) {
// fixed width, calc height
width = targetWidth;
height = width / originalAspectRatio;
} else {
const targetRatio = targetWidth / targetHeight;
if (targetRatio > originalAspectRatio) {
// fill height, calc width
height = targetHeight;
width = height * originalAspectRatio;
} else {
// fill width, calc height
width = targetWidth;
height = width / originalAspectRatio;
}
}
console.log(originalSize, originalAspectRatio, width, height);
return Media.addImage(doc, image, width, height);
}
const image = fitImage(doc, imageBuffer, 100); // set width to 100px calc height
const image = fitImage(doc, imageBuffer, null, height); // set height to 100px calc width
const image = fitImage(doc, imageBuffer, 100, 100); // fit image inside a 100x100 box

最新更新