天天看點

Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志

java_baidu_ocr

Java調用百度OCR文字識别API實作圖檔文字識别軟體

這是一款小巧友善,強大的文字識别軟體,由Java編寫,配上了視窗界面

調用了百度ocr文字識别API 識别精度高。

完整項目放在GitHub:https://github.com/Ymy214/java_baidu_ocr

更新日志

新的改變 OcrViewer 2.0 更新于 2019.1.18

我對OcrViewer進行了一些功能拓展與界面美化,除了标準的本地圖檔識别功能,我增加了如下幾點新功能,幫助你更友善使用本工具,進而更好地識别圖像中的文字:

    1. 全新的界面設計,将會帶來全新的使用體驗;
    1. 在創作中心設定你喜愛的代碼高亮樣式,Markdown 将代碼片顯示選擇的高亮樣式 進行展示;
    1. 增加了 截圖識别 功能,你可以通過截取圖檔直接直接進行識别;
    1. 增加了圖檔預覽功能,更加友善進行圖文對比,減少容錯;
    1. 增加了 清除圖檔預覽 功能,可以清清除覽的圖檔;
    1. 增加了 重新識别 等功能,如果不确定可以多次識别提高識别精确率;

下面是功能以及新界面展示

  • 識别出師表.png
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 截圖出師表 .png識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 識别代碼.png
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 代碼.png識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 識騰訊新聞彈窗.png
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 騰訊新聞彈窗.png識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 軟體界面
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志

Java源代碼:

  • 主視窗類 FileChooserOCR2.java
package baiduOcr;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.json.JSONArray;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;

@SuppressWarnings("serial")
public class FileChooserOCR2 extends JFrame implements ActionListener
{
	// 設定APPID/AK/SK
	public static final String appId = "15289864";
	public static final String apiKey = "j0pj5Y7HVElkLnmn2LEXKeyO";
	public static final String secretKey = "FKVbH7EBcGy4DIaqPnXcqE47eACzn2W7";

	AipOcr client = new AipOcr(appId, apiKey, secretKey);
	JButton open, re0, copy, screen, reset, reocr, b6;
	JPanel ocrPanel, pNorth, pSouth, pWest, pEast, pCenter, pCenterLeft, pCenterRight;
	JTextArea ocrText;
	JLabel previewLabel, printLabel;
	ImageIcon defaultPreviewImg;
	JScrollPane areaScroll;
	String filePath = "./img/preview.jpg";
	BufferedImage screenImage;// 用與子窗體給父窗體傳值
	// 構造方法

	public FileChooserOCR2()
	{
		// 主面闆
		ocrPanel = new JPanel();
		ocrPanel.setLayout(new BorderLayout());

		// 各個按鈕
		open = new JButton("[選擇圖檔>>>文字識别]");
		re0 = new JButton("清空");
		copy = new JButton("複制");
		screen = new JButton("[截圖識别]");
		reset = new JButton("清除");
		reocr = new JButton("重識");
		b6 = new JButton("b6");
		// 設定各按鈕字型
		open.setFont(new Font("宋體", Font.BOLD, 18));
		screen.setFont(new Font("宋體", Font.BOLD, 18));
		copy.setFont(new Font("宋體", Font.BOLD, 18));
		re0.setFont(new Font("宋體", Font.BOLD, 18));
		reset.setFont(new Font("宋體", Font.BOLD, 18));
		reocr.setFont(new Font("宋體", Font.BOLD, 18));
		b6.setFont(new Font("宋體", Font.BOLD, 18));
		// 圖檔預覽标簽以及狀态提示标簽
		defaultPreviewImg = new ImageIcon("./img/preview.jpg");
		previewLabel = new JLabel(defaultPreviewImg);
		printLabel = new JLabel("輸出:");
		// 文本域
		ocrText = new JTextArea("輸出内容。。。");
		ocrText.setEditable(true);
		ocrText.setVisible(true);
		ocrText.setFont(new Font("宋體", Font.BOLD, 18));
		// 各方位分面闆
		pWest = new JPanel(new GridLayout(2, 0));
		pEast = new JPanel(new GridLayout(2, 2));
		pSouth = new JPanel(new GridLayout(0, 2));
		pCenter = new JPanel(new GridLayout(0, 2));
		pCenterLeft = new JPanel(new CardLayout());
		pCenterRight = new JPanel(new CardLayout());

		// 預設預覽圖檔是否伸縮
		// previewImg.setImage(previewImg.getImage().getScaledInstance(340,
		// 466,Image.SCALE_DEFAULT));
		// previewLabel.setIcon(previewImg);
		//

		// 文本域的滾動條
		areaScroll = new JScrollPane(ocrText);
		// 設定橫向滾動條始終開啟
		// areaScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		// 設定垂直滾動條始終開啟
		// areaScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		// 設定橫向滾動條自動(有需要時)開啟
		areaScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		// 設定垂直滾動條自動(有需要時)開啟
		areaScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

		// 添加監聽
		open.addActionListener(this);
		re0.addActionListener(this);
		copy.addActionListener(this);
		screen.addActionListener(this);
		reset.addActionListener(this);
		reocr.addActionListener(this);

		// 各元件依次加入相應方位面闆
		pCenterLeft.add(previewLabel);
		// pCenterRight.add(ocrText);
		pCenterRight.add(areaScroll);

		pWest.add(reocr);
		pWest.add(reset);

		pSouth.add(screen);
		pSouth.add(printLabel);
		pCenter.add(pCenterLeft);
		pCenter.add(pCenterRight);
		pEast.add(copy);
		pEast.add(re0);

		// 各方位面闆加入主面闆
		ocrPanel.add(open, BorderLayout.NORTH);
		ocrPanel.add(pWest, BorderLayout.WEST);
		ocrPanel.add(pEast, BorderLayout.EAST);
		ocrPanel.add(pCenter, BorderLayout.CENTER);
		ocrPanel.add(pSouth, BorderLayout.SOUTH);

		ocrPanel.setSize(300, 300);
		this.add(ocrPanel);
		this.setBounds(400, 200, 900, 600);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	@Override
	public void actionPerformed(ActionEvent e)
	{

		if (e.getSource() == re0)
		{
			ocrText.setText("已清空内容。。。");
			printLabel.setText("輸出:已清空内容。。。");
		}
		if (e.getSource() == copy)
		{
			String jianqieban = ocrText.getText();
			setSysClipboardText(jianqieban);
			printLabel.setText("輸出:已複制到剪貼闆。。。");
		}
		if (e.getSource() == screen)
		{
			new ScreenShotTest(this);
			// 現已實作為截屏功能, 截屏功能已經封裝到一個類檔案中,參考的代碼
		}
		if (e.getSource() == reocr)
		{
			ocrText.setText(imgOcr(filePath));
			printLabel.setText("輸出:已重新識别。。。");
		}
		if (e.getSource() == reset)
		{
			previewLabel.setIcon(defaultPreviewImg);
			filePath = "./img/preview.jpg";
			printLabel.setText("輸出:已清除預覽。。。");
		}
		if (e.getSource() == open)
		{
			printLabel.setText("輸出:選擇檔案。。。");
			System.out.println(e.getSource());
			// TODO Auto-generated method stub
			JFileChooser jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			jfc.showDialog(new JLabel(), "選擇");
			File file = jfc.getSelectedFile();
			if (file.isDirectory())
			{
				System.out.println("(選擇目錄) $ " + file.getAbsolutePath());
				System.out.println("請選擇圖檔。。。");
			} else if (file.isFile())
			{
				filePath = file.getAbsolutePath();
				ImageIcon ocrImg = new ImageIcon(filePath);
				System.out.println("(選擇檔案) $ " + filePath);
				ocrText.setText("正在識别。。。");
				// 縮放後的圖檔,用到了一個圖檔縮放算法
				ocrImg.setImage(ocrImg.getImage().getScaledInstance(340, 470, Image.SCALE_DEFAULT));
				previewLabel.setIcon(ocrImg);
				String ocrStr = imgOcr(filePath);
				printLabel.setText("輸出:正在識别。。。");
				ocrText.setText(ocrStr);
				printLabel.setText("輸出:識别完畢!!!。。。");

			}
			System.out.println("正在識别>>>" + jfc.getSelectedFile().getName());
		}

	}

	// 複制到剪貼闆的方法
	public static void setSysClipboardText(String writeMe)
	{
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		clip.setContents(tText, null);
	}

	// 主方法
	public static void main(String[] args)
	{
		FileChooserOCR2 ocrWin = new FileChooserOCR2();
		ocrWin.setVisible(true);
	}

	/*
	 * 文字識别方法
	 */
	public String imgOcr(String imgpath)
	{
		// 傳入可選參數調用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("language_type", "CHN_ENG");
		options.put("detect_direction", "true");
		options.put("detect_language", "true");
		options.put("probability", "true");

		// 參數為本地路徑
		JSONObject res = client.basicGeneral(imgpath, options);
		// 解析json-------------
		JSONArray wordsResult = (JSONArray) res.get("words_result");
		String ocrStr = "\n";
		for (Object obj : wordsResult)
		{
			JSONObject jo = (JSONObject) obj;
			ocrStr += jo.getString("words") + "\n";
		}

		// 解析json-------------
		return ocrStr;
		// return res.toString(2);

	}

	/*
	 * 文字識别方法(方法的重載)
	 */
	public String imgOcr(byte[] imgInbyte)
	{
		// 傳入可選參數調用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("language_type", "CHN_ENG");
		options.put("detect_direction", "true");
		options.put("detect_language", "true");
		options.put("probability", "true");

		// 參數為二進制數組
		JSONObject res = client.basicGeneral(imgInbyte, options);
		// 解析json-------------
		JSONArray wordsResult = (JSONArray) res.get("words_result");
		String ocrStr = "\n";
		for (Object obj : wordsResult)
		{
			JSONObject jo = (JSONObject) obj;
			ocrStr += jo.getString("words") + "\n";
		}

		// 解析json-------------
		return ocrStr;
		// return res.toString(2);

	}

}






           
  • 截圖視窗類 ScreenShotTest.java(參考自:https://www.jb51.net/article/48968.htm)
package baiduOcr;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JToolBar;
import javax.swing.JWindow;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

public class ScreenShotTest
{
	private FileChooserOCR2 superWindow;

	public ScreenShotTest(FileChooserOCR2 superWimdow)
	{
		this.superWindow = superWimdow;
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run()
			{
				try
				{
					new ScreenShotWindow(superWindow);
				} catch (AWTException e)
				{
					e.printStackTrace();
				}
			}
		});
	}

}

/*
 * 截圖視窗
 */
class ScreenShotWindow extends JWindow
{

	private int orgx, orgy, endx, endy;
	private BufferedImage image = null;
	private BufferedImage tempImage = null;
	private BufferedImage saveImage = null;

	private ToolsWindow tools = null;

	private FileChooserOCR2 superWin;

	public ScreenShotWindow(FileChooserOCR2 superWindow) throws AWTException
	{
		this.superWin = superWindow;

		// 擷取螢幕尺寸
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		this.setBounds(0, 0, d.width, d.height);

		// 截取螢幕
		Robot robot = new Robot();
		image = robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));

		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e)
			{
				// 滑鼠松開時記錄結束點坐标,并隐藏操作視窗
				orgx = e.getX();
				orgy = e.getY();

				if (tools != null)
				{
					tools.setVisible(false);
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				// 滑鼠松開時,顯示操作視窗
				if (tools == null)
				{
					tools = new ToolsWindow(ScreenShotWindow.this, e.getX(), e.getY());
				} else
				{
					tools.setLocation(e.getX(), e.getY());
				}
				tools.setVisible(true);
				tools.toFront();
			}
		});

		this.addMouseMotionListener(new MouseMotionAdapter() {

			@Override
			public void mouseDragged(MouseEvent e)
			{
				// 滑鼠拖動時,記錄坐标并重繪視窗
				endx = e.getX();
				endy = e.getY();

				// 臨時圖像,用于緩沖螢幕區域放置螢幕閃爍
				Image tempImage2 = createImage(ScreenShotWindow.this.getWidth(), ScreenShotWindow.this.getHeight());
				Graphics g = tempImage2.getGraphics();
				g.drawImage(tempImage, 0, 0, null);
				int x = Math.min(orgx, endx);
				int y = Math.min(orgy, endy);
				int width = Math.abs(endx - orgx) + 1;
				int height = Math.abs(endy - orgy) + 1;
				// 加上1防止width或height0
				g.setColor(Color.BLUE);
				g.drawRect(x - 1, y - 1, width + 1, height + 1);
				// 減1加1都了防止圖檔矩形框覆寫掉
				saveImage = image.getSubimage(x, y, width, height);
				g.drawImage(saveImage, x, y, null);

				ScreenShotWindow.this.getGraphics().drawImage(tempImage2, 0, 0, ScreenShotWindow.this);
			}
		});

		this.setVisible(true);
	}

	@Override
	public void paint(Graphics g)
	{
		RescaleOp ro = new RescaleOp(0.8f, 0, null);
		tempImage = ro.filter(image, null);
		g.drawImage(tempImage, 0, 0, this);
	}

	// 儲存圖像到檔案
	public void saveImage() throws IOException
	{
		// 先隐藏視窗背景執行,顯得程式執行很快
		this.setVisible(false);
		tools.setVisible(false);

		JFileChooser jfc = new JFileChooser();
		jfc.setDialogTitle("儲存");

		// 檔案過濾器,使用者過濾可選擇檔案
		FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");
		jfc.setFileFilter(filter);

		// 初始化一個預設檔案(此檔案會生成到桌面上)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
		String fileName = sdf.format(new Date());
		File filePath = FileSystemView.getFileSystemView().getHomeDirectory();
		File defaultFile = new File(filePath + File.separator + fileName + ".jpg");
		jfc.setSelectedFile(defaultFile);

		int flag = jfc.showSaveDialog(this);
		if (flag == JFileChooser.APPROVE_OPTION)
		{
			File file = jfc.getSelectedFile();
			String path = file.getPath();
			// 檢查檔案字尾,放置使用者忘記輸入字尾或者輸入不正确的字尾
			if (!(path.endsWith(".jpg") || path.endsWith(".JPG")))
			{
				path += ".jpg";
			}
			// 寫入檔案
			superWin.printLabel.setText("輸出:已儲存截圖!!!");
			ImageIO.write(saveImage, "jpg", new File(path));

			dispose();
		}
	}

	// 傳回截取的圖檔
	public void okImage()
	{
		
		this.setVisible(false);
		tools.setVisible(false);
		superWin.printLabel.setText("輸出:識别截圖成功!!!");
		ByteArrayOutputStream baos = null;
		try
		{
			baos = new ByteArrayOutputStream();
			ImageIO.write(saveImage, "jpg", baos);
			byte[] imageInByte = baos.toByteArray();// 使用toByteArray()方法轉換成位元組數組
			superWin.ocrText.setText(superWin.imgOcr(imageInByte));
			baos.flush();// 會産生IOException異常

		} catch (IOException e1)
		{
			e1.printStackTrace();
		} finally
		{
			try
			{
				if (baos != null)
				{
					baos.close();
				}
			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}

		dispose();
	}

	/*
	 * 文字識别方法(方法的重載) 用父視窗類的
	 */

	/*
	 * 文字識别方法
	 */

}

/*
 * 操作視窗
 */
class ToolsWindow extends JWindow implements ActionListener
{
	private ScreenShotWindow parent;

	JButton saveButton, closeButton, okButton;

	public ToolsWindow(ScreenShotWindow parent, int x, int y)
	{
		this.parent = parent;
		this.setLayout(new BorderLayout());
		JToolBar toolBar = new JToolBar("Java 截圖");

		// 儲存按鈕
		saveButton = new JButton("◰");
		// 關閉按鈕
		closeButton = new JButton("✘");
		// 標明按鈕
		okButton = new JButton("✔");

		saveButton.addActionListener(this);
		closeButton.addActionListener(this);
		okButton.addActionListener(this);

		toolBar.add(saveButton);
		toolBar.add(closeButton);
		toolBar.add(okButton);

		this.add(toolBar, BorderLayout.NORTH);

		this.setLocation(x, y);
		this.pack();
		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		// TODO Auto-generated method stub
		if (e.getSource() == saveButton)
		{
			try
			{
				parent.saveImage();
				dispose();
			} catch (IOException e1)
			{
				e1.printStackTrace();
			}
		}
		if (e.getSource() == closeButton)
		{
			parent.dispose();
			dispose();
			// System.exit(0);
		}
		if (e.getSource() == okButton)
		{
			// 傳回標明的圖檔
			parent.okImage();
			dispose();
		}
	}

}


           

↑↑↑↑↑↑↑↑↑↑↑↑以上為2019.1.18日OcrViewer2.0第二代↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

↓↓↓↓↓↓↓↓↓↓↓↓以下為2019.1.12日OcrViewer1.0第一代↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

  • 打包生成了jar可執行程式
  • 完整項目GitHub位址 新人有幫助有用的話請給個star謝謝了!
  • https://github.com/Ymy214/java_baidu_ocr
  • 識别圖一
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 圖一識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 識别圖二
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 圖二識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 識别圖三
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 圖三識别結果
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志
  • 軟體界面
    Java調用百度OCR文字識别API實作圖檔文字識别軟體java_baidu_ocr更新日志

Java源代碼:

package baiduOcr;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.json.JSONArray;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;

@SuppressWarnings("serial")
public class FileChooserOCR extends JFrame implements ActionListener
{
	// 設定APPID/AK/SK
	public static final String appId = "15289864";
	public static final String apiKey = "j0pj5Y7HVElkLnmn2LEXKeyO";
	public static final String secretKey = "FKVbH7EBcGy4DIaqPnXcqE47eACzn2W7";
	
	AipOcr client = new AipOcr(appId, apiKey, secretKey);
	JButton open, b1, b2, b3;
	JPanel ocrPanel;
	JTextArea ocrText;
	JScrollPane areaScroll;
	
	// 構造方法
	public FileChooserOCR()
	{
		ocrPanel = new JPanel();
		ocrPanel.setLayout(new BorderLayout());
		open = new JButton("選擇圖檔>>>文字識别");
		b1 = new JButton("清空");
		b2 = new JButton("複制");
		b3 = new JButton("配置");
		open.setFont(new Font("宋體", Font.BOLD, 18));
		b3.setFont(new Font("宋體", Font.BOLD, 18));
		b2.setFont(new Font("宋體", Font.BOLD, 18));
		b1.setFont(new Font("宋體", Font.BOLD, 18));
		
		//文本域的滾動條
//		areaScroll = new JScrollPane(ocrText);
//		areaScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//		areaScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		//添加監聽
		open.addActionListener(this);
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		
		ocrText = new JTextArea("輸出内容。。。");
		ocrText.setEditable(true);
		ocrText.setVisible(true);
		ocrText.setFont(new Font("宋體", Font.BOLD, 18));
		ocrPanel.add(open, BorderLayout.NORTH);
		ocrPanel.add(b1, BorderLayout.EAST);
		ocrPanel.add(b2, BorderLayout.WEST);
		ocrPanel.add(b3, BorderLayout.SOUTH);
		ocrPanel.add(ocrText, BorderLayout.CENTER);
//		ocrPanel.add(areaScroll);
		ocrPanel.setSize(300, 300);
		this.add(ocrPanel);
		this.setBounds(400, 200, 900, 600);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==b1)
		{
			ocrText.setText("已清空内容。。。");
		}
		if(e.getSource()==b2)
		{
			String jianqieban = ocrText.getText();
			setSysClipboardText(jianqieban);
		}
		if (e.getSource()==b3)
		{
			//日後實作
		}
		if(e.getSource()==open)
		{
			System.out.println(e.getSource());
			// TODO Auto-generated method stub
			JFileChooser jfc = new JFileChooser();
			jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			jfc.showDialog(new JLabel(), "選擇");
			File file = jfc.getSelectedFile();
			if (file.isDirectory())
			{
				System.out.println("(選擇目錄) $ " + file.getAbsolutePath());
				System.out.println("請選擇圖檔。。。");
			} 
			else if (file.isFile())
			{
				System.out.println("(選擇檔案) $ " + file.getAbsolutePath());
				ocrText.setText("正在識别。。。");
				String ocrStr = this.imgOcr(file.getAbsolutePath());
				ocrText.setText(ocrStr);
			}
			System.out.println("正在識别>>>"+jfc.getSelectedFile().getName());
		}
		

	}

	//複制到剪貼闆
	public static void setSysClipboardText(String writeMe) {  
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();  
        Transferable tText = new StringSelection(writeMe);  
        clip.setContents(tText, null);  
    } 

	// 主方法
	public static void main(String[] args)
	{
		FileChooserOCR ocrWin = new FileChooserOCR();
		ocrWin.setVisible(true);
	}
	/*
	 * 文字識别方法
	 */
	public String imgOcr(String imgpath)
	{
		// 傳入可選參數調用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("language_type", "CHN_ENG");
		options.put("detect_direction", "true");
		options.put("detect_language", "true");
		options.put("probability", "true");

		// 參數為本地路徑
		JSONObject res = client.basicGeneral(imgpath, options);
		//解析json-------------
		JSONArray wordsResult = (JSONArray)res.get("words_result");
		String ocrStr = "\n";
		for(Object obj : wordsResult)
		{
			JSONObject jo = (JSONObject)obj;
			ocrStr += jo.getString("words") + "\n";
		}
		
		//解析json-------------
		return ocrStr;
//        return res.toString(2);
        
        
        
		// 參數為二進制數組
		// byte[] file = readFile("test.jpg");
		// res = client.basicGeneral(file, options);
		// System.out.println(res.toString(2));

		// 通用文字識别, 圖檔參數為遠端url圖檔
		// JSONObject res = client.basicGeneralUrl(url, options);
		// System.out.println(res.toString(2));

	}

}


           

完整項目放在GitHub:https://github.com/Ymy214/java_baidu_ocr