How does Java store pictures in word according to the original size scale


Java pictures are stored in word according to the original size scale

You can use POI to insert pictures into word

Xwpfparagraph. Insertnewrun (I). Addpicture (InputStream picturedata, int picturetype, string filename, int width, int height) method

However, in order to make the pictures inserted into word scale equally according to the size of the original drawing, we must obtain the size of the original drawing. The common method is to

The (InputStream input) method reads image information, which involves two image reads and writes. In order to reduce unnecessary network communication,

We can optimize in the following ways:

URL url = new URL(runText);
  byte[] bytes = IOUtils.toByteArray(url.openStream());
  ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
  BufferedImage img =;
  int width = img.getWidth();
  int height = img.getHeight();
  //The following is the same scale as the actual size of the picture
  int picHeight = 300;
  int picWidth = picHeight * width/height;
  //The next time you read the bytearrayinputstream, you must call reset to reset it, so that you can read all the data of the picture
          XWPFDocument.PICTURE_TYPE_JPEG, url.getFile(), Units.toEMU(picWidth), Units.toEMU(picHeight));

Well, the above is to reduce the number of network communications through bytearrayinputstream.

The addpicture method of xwpfrun in POI export word sets the picture width and height

XWPFRun run = paragraph.createRun();
InputStream is = getClass().getClassLoader().getResourceAsStream("images/abc.gif");
//Because FileInputStream does not override reset (), all will flow into byte array
byte[] bs = IOUtils.toByteArray(is);
BufferedImage image = ByteArrayInputStream(bs));
//int width = MyUnits.pxToEMU(image.getWidth());
//int height = MyUnits.pxToEMU(image.getHeight());
//EMU (Imperial metric units). 1 EMU = 1 / 914400 inch = 1 / 36000 mm
run.addPicture(new ByteArrayInputStream(bs), Document.PICTURE_TYPE_GIF, "", 685800, 685800);

If you do not know the size of the picture settings of the referenced word template, you can double-click the picture in the word template and view the width and height

The width and height in the addpicture method are EMU (Imperial metric unit), which can be converted according to 1 EMU = 1 / 914400 inch = 1 / 36000 mm.

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer.

Recommended Today

Detailed steps for installing Perl and Komodo IDE for windows

Perl official website: document: address: The installation package of Perl Windows version is divided into activestate Perl and strawberry Perl. For the difference between the two, see: Note: the download speed of activestate Perl is slow. You may need KX to surf the Internet I have uploaded all the versions of […]