1. 程式人生 > >【eclipse】外掛開發——用於驗證碼識別的JMeter外掛

【eclipse】外掛開發——用於驗證碼識別的JMeter外掛

目錄

一、eclipse開發外掛專案

(1)eclipse開發外掛專案全部目錄:

(2)完成外掛直接在eclipse執行測試:

二、lib目錄jar包準備

參考我的另一篇博文:【jmeter】實現驗證碼登入

博文地址:

三、src目錄程式碼準備

(1)ImageIOHelper類:

主要包含兩大部分,一部分就是降噪邏輯,通過建立降噪規則對背景圖片畫素點進行逐個掃描過濾,加大識別成功率;

另一部分是將圖片格式轉換為tiff格式以更好地進行識別,程式碼參考如下:

package com.test.gss;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam;

public class ImageIOHelper{
	
	//將圖片格式轉換為tif格式以更好地進行識別
    public static File createImage(File imageFile, String imageFormat) {

        File tempFile = null;
        ImageInputStream iis = null;
        ImageOutputStream ios = null;
        ImageReader reader = null;
        ImageWriter writer = null;

        try {
            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
            reader = readers.next();

            iis = ImageIO.createImageInputStream(imageFile);
            reader.setInput(iis);

            IIOMetadata streamMetadata = reader.getStreamMetadata();
                        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
            tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
            writer = writers.next();

            BufferedImage bi = removeBackgroud(reader.read(0));
            IIOImage image = new IIOImage(bi,null,reader.getImageMetadata(0));
            tempFile = tempImageFile(imageFile);

            ios = ImageIO.createImageOutputStream(tempFile);
            writer.setOutput(ios);
            writer.write(streamMetadata, image, tiffWriteParam);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(iis != null){
                try {
                    iis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(ios != null){
                try {
                    ios.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(writer != null){
                writer.dispose();
            }
            if(reader != null){
                reader.dispose();
            }

        }
        return tempFile;
    }

    private static File tempImageFile(File imageFile) {
        String path = imageFile.getPath();
        StringBuffer strB = new StringBuffer(path);
        return new File(strB.toString().replaceFirst("jpg", "tif"));
    }
    
    
    //給圖片降噪,建立如下降噪規則和方法,提高識別度
    public static int isFilter(int colorInt) {  
        Color color = new Color(colorInt);
        if ((color.getRed() > 85 && color.getRed() < 255) 
                && (color.getGreen() > 85 && color.getGreen() < 255) 
                && (color.getBlue() > 85 && color.getBlue() < 255)) {  
            return 1;  
        }  
        return 0;
    }
    
    public static BufferedImage removeBackgroud(BufferedImage img)  
            throws Exception {  
        int width = img.getWidth();  
        int height = img.getHeight();  
        for (int x = 0; x < width; ++x) {  
            for (int y = 0; y < height; ++y) {  
                if (isFilter(img.getRGB(x, y)) == 1) {  
                   img.setRGB(x, y, Color.WHITE.getRGB());  
                }
            }  
        }  
        return img;
    } 
    
}

(2)OCR類:

通過Process呼叫已經安裝的Tesseract程式,呼叫命令基本形式為tesseract xxx.tif 1 -l eng,參考如下程式碼:

package com.test.gss;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class OCR {
    private final String LANG_OPTION = "-l";
    private final String EOL = System.getProperty("line.separator");
    //第三方圖形影象識別工具tesseract-OCR的安裝目錄
    private String tessPath = "G://Tesseract-ocr//tesserract//Tesseract-ORC//Tesseract-OCR";

    public String recognizeText(File imageFile,String imageFormat) {
        File tempImage = ImageIOHelper.createImage(imageFile,imageFormat);
        File outputFile = new File(imageFile.getParentFile(),"output" + imageFile.getName());
        StringBuffer sb = new StringBuffer();
        List<String> cmd = new ArrayList<String>();

        cmd.add(tessPath+"//tesseract");
        cmd.add("");
        cmd.add(outputFile.getName());
        cmd.add(LANG_OPTION);
        cmd.add("eng");     
        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(imageFile.getParentFile());

        cmd.set(1, tempImage.getName());
        pb.command(cmd);
        pb.redirectErrorStream(true);

        Process process = null;
        BufferedReader in = null;
        int wait;
        try {
            process = pb.start();
            //通過Process呼叫已經安裝的Tesseract程式,呼叫命令基本形式為:tesseract xxx.tif 1 -l eng
            wait = process.waitFor();
            if(wait == 0){
                in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()+".txt"),"UTF-8"));
                String str;
                while((str = in.readLine())!=null){
                    sb.append(str).append(EOL);
                }
                in.close();

            }else{

                tempImage.delete();
            }
            new File(outputFile.getAbsolutePath()+".txt").delete();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        tempImage.delete();
        return sb.toString();
    }
}

(3)VcodeExtractor類:

繼承AbstractScopedTestElement抽象類,實現PostProcessor介面的process方法,來處理利用OCR讀取驗證碼資訊的邏輯控制,參考程式碼如下:

package com.test.gss;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;

import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractScopedTestElement;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VcodeExtractor extends AbstractScopedTestElement implements PostProcessor, Serializable{
    private static final long serialVersionUID = 1L;   
    private static final Logger log = LoggerFactory.getLogger(VcodeExtractor.class);
    
    @Override
    public void process() {

        // TODO Auto-generated method stub
        JMeterContext context = getThreadContext();
        SampleResult previousResult = context.getPreviousResult();
        if (previousResult == null) {
            return;
        }
        log.debug("VcodeExtractor processing result");

        String status = previousResult.getResponseCode();
        int id = context.getThreadNum();
        //String imageName = id + ".jpg";
        String path = "E://" + id + ".jpg";

        if(status.equals("200")){
            byte[] buffer = previousResult.getResponseData();
            FileOutputStream out = null;
            File file = null;
            try {
                file = new File(path);
                out = new FileOutputStream(file);
                out.write(buffer);
                out.flush();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if(out != null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

              try {   
                String vcode = new OCR().recognizeText(file, "jpeg"); 
                vcode = vcode.replace(" ", "").trim();
                
                JMeterVariables var = context.getVariables();
                var.put("vcode", vcode);
                var.put("vuser", String.valueOf(id));
                } catch (Exception e) {
                    e.printStackTrace();
                }    
        }

    }

}

(4)VcodeExtractorGUI類:

單純實現一個視覺化的介面用於在測試計劃Tree中進行操作,參照程式碼如下:

package com.test.gss;
import org.apache.jmeter.processor.gui.AbstractPostProcessorGui;
import org.apache.jmeter.testelement.TestElement;

public class VcodeExtractorGUI extends AbstractPostProcessorGui{
    private static final long serialVersionUID = 1L;
    
    @Override
    public TestElement createTestElement() {
        // TODO Auto-generated method stub
        VcodeExtractor extractor = new VcodeExtractor();
        modifyTestElement(extractor);
        return extractor;
    }

    @Override
    public String getLabelResource() {
        // TODO Auto-generated method stub
        return this.getClass().getName();
    }

    @Override
    public String getStaticLabel() {
    	//設定顯示名稱
        // TODO Auto-generated method stub
        return "VcodeExtractor";
    }

    @Override
    public void modifyTestElement(TestElement extractor) {
        // TODO Auto-generated method stub
        super.configureTestElement(extractor);

    }
}

(5)TestOCR類:

方便設定main程式啟動入口:

package com.test.gss;

import java.io.File; 

public class TestOCR {
	
	 public static void main(String[] args) {  
	        String path = "E://100.jpg";       
	        System.out.println("ORC Test Begin......");  
	        try {       
	            String valCode = new OCR().recognizeText(new File(path), "jpeg");       
	            System.out.println(valCode);       
	        } catch (Exception e) {    
	            e.printStackTrace();    
	        }         
	        System.out.println("ORC Test End......");  
	    }    
	  
	}  

四、匯出為jar包

五、外掛下載

目前我開發好的外掛,可到我的資源下載:點選前往下載