java插入图片
㈠ java编辑WORD文件插入图片
试试这个代码,需要添加spire.doc jar依赖
importcom.spire.doc.Document;
importcom.spire.doc.FileFormat;
importcom.spire.doc.Section;
importcom.spire.doc.documents.*;
importcom.spire.doc.fields.DocPicture;
publicclassInsertImage{
publicstaticvoidmain(String[]args){
//实例化Document对象
薯碧Documentdoc=newDocument();
//加载文档
doc.loadFromFile("C:\Users\Administrator\Desktop\test.docx");
//获取第一个section
Sectionsection=doc.getSections().get(0);
//添加一个段落
Paragraphpara=section.addParagraph();
//添加图片到段落
昌滚DocPicturepicture=para.appendPicture("C:\Users\Administrator\Desktop\Cartoon.png");
//设数迅举置文字环绕方式(居于文字上方)
picture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text);
//指定图片的相对位置
picture.setHorizontalOrigin(HorizontalOrigin.Page);
picture.setHorizontalPosition(250f);
picture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
picture.setVerticalPosition(150f);
//设置图片大小
picture.setWidth(80f);
picture.setHeight(80f);
//保存到文档
doc.saveToFile("output/InsertImage.docx",FileFormat.Docx);
}
}
生成的Word:
㈡ 濡备綍鍦╦ava绐椾綋涓鎻掑叆GIF锲
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ImageViewer
{
public static void main(String[] args)
{
JFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
setTitle("ImageViewer");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
label = new JLabel();
Container contentPane = getContentPane();
contentPane.add(label);
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
int r = chooser.showOpenDialog(null);
if(r == JFileChooser.APPROVE_OPTION)
{
String name
= chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
});
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
}
private JLabel label;
private JFileChooser chooser;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400;
}