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;
}