本文介绍了如何将捕获的图像写入/粘贴到doc文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个场景,我需要捕获图像并将它们一个接一个地写入word文件。我写了下面的代码,但似乎没有工作。请帮助
I have a scenario where i need to capture image and write them to a word file one after the other. I have written the below code but doesn't seem to be working. Please help
Robot robot;
try {
robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(screenShot, "JPG", new File("C:\\xxx\\Gaurav\\NEW1.JPG"));
InputStream is = new ByteArrayInputStream(baos.toByteArray());
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText(resulttext);
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "new", 300, 300);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Blank Document
}
推荐答案
使用 ImageIO.write(screenShot,JPG,baos);
图像在那里,但它有点小,因为测量单位不是像素,而是EMU(英制公制单位)。有一个 org.apache.poi.util.Units
可以将像素转换为EMU。
Using ImageIO.write(screenShot, "JPG", baos);
the image is there but it is a little bit small because the measurement unit is not pixel but EMU (English Metric Unit). There is a org.apache.poi.util.Units
which can convert pixels to EMUs.
以下是为我工作:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class CreateWordPictureScreenshot {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
String resulttext = "The Screenshot:";
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//ImageIO.write(screenShot, "JPG", new File("NEW1.JPG"));
ImageIO.write(screenShot, "JPG", baos);
baos.flush();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
baos.close();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText(resulttext);
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "new", Units.toEMU(72*6), Units.toEMU(72*6/16*9));
is.close();
document.write(new FileOutputStream("CreateWordPictureScreenshot.docx"));
document.close();
}
}
这篇关于如何将捕获的图像写入/粘贴到doc文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!