Search code examples
rofficer

Officer: How to insert picture with it's original width and height


Just like in title: I'd like to add several external images to my .docx document. But when using body_add_img I need to specify width and height. Is there a way to set them to width and height of original image to be added?

Why I need that? My images (about 50 of them) have all different widths and heights, so it would be painful to manually put their widths and heights in (about 50) body_add_img calls.


Solution

  • If your image is a png you can png::readPNG to get the width and height in pixels, and divide by your DPI to get the dimensions in inches. (Replace 300 with your DPI)

    dpi <- 300
    img_size <- dim(png::readPNG('image/path/here.png'))/dpi
    

    Edit: If you want the dpi in the doc to be the same as the dpi in the image natively (assuming your png has the dpi stored, I think not all do), use dpi <- attr(readPNG('image.png', info=T), 'info')$dpi