如何在webview中通过鼠标事件选择图像的特定区域,并使用空格按键事件进行裁剪?

时间:2017-10-10 06:37:04

标签: java javafx mouseevent keyevent

我已经尝试过这个选择并且运行正常,但我的要求仅适用于一个盒子并选择完整的场景。

   package verticalseperator;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author biznis
 */
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author biznis
 */

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.scene.effect.Light.Point;
import javafx.scene.image.PixelReader;


/**
 *
 * Created on: 20.03.2012
 *
 * @author Sebastian Damm
 */
public class HV extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

          StackPane root = new StackPane();

        HBox hbox = new HBox(30); // create a HBox to hold 2 vboxes        

        // create a vbox with a textarea that grows vertically
        VBox vbox = new VBox(10);
        //Label label1 = new Label("");

        final WebView img = new WebView();
        final WebEngine Img = img.getEngine();


         final Rectangle selection = new Rectangle();
       final Point anchor = new Point();

      img. setOnMousePressed((MouseEvent event) ->{
     anchor.setX(event.getX());
            anchor.setY(event.getY());
            selection.setX(event.getX());
            selection.setY(event.getY());
            selection.setFill(null); // transparent 
            selection.setStroke(Color.BLACK); // border
         root.getChildren().add(selection);
                  });
       img. setOnMouseDragged((MouseEvent event) ->
            { 
          selection.setWidth(Math.abs(event.getX() - anchor.getX()));
            selection.setHeight(Math.abs(event.getY() - anchor.getY()));
            selection.setX(Math.min(anchor.getX(), event.getX()));
            selection.setY(Math.min(anchor.getY(), event.getY()));
            }); 
        img. setOnMouseReleased((MouseEvent event) ->{

              System.out.printf("X: %.2f, Y: %.2f, Width: %.2f, Height: %.2f%n", 
                    selection.getX(), selection.getY(), selection.getWidth(), selection.getHeight());
            root.getChildren().remove(selection);
            selection.setWidth(0);
            selection.setHeight(0);
        });

        img.addEventFilter(KeyEvent.KEY_RELEASED, (KeyEvent e) -> {
            if (e.getCode() == KeyCode.SPACE ) {
            PixelReader reader = img.getPixelReader();
    WritableImage newImage = new WritableImage(reader, X, Y, Width,Height);
            }
            });
        img.addEventFilter(KeyEvent.KEY_RELEASED, (KeyEvent e) -> {
            if (e.getCode() == KeyCode.ADD || e.getCode() == KeyCode.EQUALS || e.getCode() == KeyCode.PLUS) {
                System.out.println("YES");
                img.setZoom(img.getZoom() * 1.1);
            } else if (e.getCode() == KeyCode.SUBTRACT || e.getCode() == KeyCode.MINUS) {
                System.out.println("YES");
                img.setZoom(img.getZoom() / 1.1);
            }
        });
        vbox.getChildren().addAll(img);
        // create a vbox that grows horizontally inside the hbox
        VBox vbox2 = new VBox();
        final WebView browser = new WebView();
        final WebEngine wb2 = browser.getEngine();
        final WebView browser1 = new WebView();
        final WebEngine wb1 = browser1.getEngine();
        wb1.getLoadWorker().stateProperty()
                .addListener(new ChangeListener<Worker.State>() {
                    @Override
                    public void changed(ObservableValue ov, State oldState, State newState) {
                        if (newState == Worker.State.SCHEDULED) {
                            primaryStage.setTitle(wb1.getLocation());
                            String trgurl = wb1.getLocation();
                            System.out.println(trgurl);
                            Platform.runLater(() -> {
                                final WebEngine wb1 = browser1.getEngine();
                                if (wb1.getLocation().contains("img")) {
                                    System.out.println("BrowserPane.ChangeListener cancelling " + wb1.getLocation());
                                    wb1.getLoadWorker().cancel();
                                    if (trgurl.matches("(.*)img=(.*)")) {
                                        int n = trgurl.indexOf("img=");
                                        //String str1 = Integer.toString(n);
                                        System.out.println(n + 4);
                                        int len = trgurl.length();
                                        System.out.println("string length is: " + trgurl.length());
                                        System.out.println(trgurl.substring(n + 4, len));
                                        String find = "file:" + trgurl.substring(n + 4, len);
                                        System.out.println(find);
                                        Img.load(find);


                                        if (trgurl.matches("(.*)target=wb2(.*)")) {
                                            int n1 = trgurl.indexOf("target=wb2");
                                            String str1 = Integer.toString(n1 + 10);
                                            System.out.println(n1 + 10);
                                            System.out.println(trgurl.substring(0, n1 + 10));
                                            String find1 = "" + trgurl.substring(0, n1 + 10);
                                            System.out.println(find1);
                                            // boolean cancel();
                                            wb2.load(find1);

                                        }
                                    }

                                }
                            });
                        }

                        if (browser1.getEngine().getLoadWorker().getState() == Worker.State.SUCCEEDED) {
                            if (wb1.getLocation().contains("noob=1&noshell=1&ini=")) {
                                JOptionPane.showMessageDialog(null, "got " + wb1.getLocation());
                                int n4 = wb1.getLocation().indexOf("ini=");
                                String str4 = Integer.toString(n4 + 4);
                                System.out.println(n4 + 4);
                                int n5 = wb1.getLocation().indexOf("&output_format=html");
                                String str5 = Integer.toString(n5 + 19);
                                System.out.println(n5 + 19);
                                String find4 = wb1.getLocation().substring(n4 + 4, n5);
                                System.out.println(find4);
                                String html = (String) wb1.executeScript("document.documentElement.innerText");
                                try {
                                    System.out.write(html.getBytes(StandardCharsets.UTF_8));
                                } catch (IOException ex) {
                                    Logger.getLogger(HV.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                String html1 = html.replace('|', '\n');
                                System.out.println(html1);
                                String h1 = html1.replaceAll("\n", "\r\n");
                                // System.out.println(html1);
                                String Path = "C:/temp";
                                Path = Path + "/";
                                File newFile = new File(Path + find4 + ".ini");

                                try {
                                    newFile.createNewFile();
                                    if (newFile.exists()) {
                                        newFile.delete();

                                    }
                                    try (FileWriter writer = new FileWriter(newFile, true)) {
                                        writer.write(h1);
                                        writer.flush();
                                        writer.close();
                                    } catch (IOException ex) {
                                        Logger.getLogger(HV.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                } catch (IOException ex) {
                                    Logger.getLogger(HV.class.getName()).log(Level.SEVERE, null, ex);
                                }

                                if (html.contains("date_data_path=")) {
                                    int n6 = html.indexOf("date_data_path=");
                                    String str6 = Integer.toString(n6 + 15);
                                    System.out.println(n6 + 15);
                                    int len1 = html.length();
                                    System.out.println("string length is: " + html.length());
                                    String find2 = html.substring(n6 + 15, len1 - 1);
                                    System.out.println(find2);
                                    String pathname = "C:";
                                    String cuts = "cuts";
                                    pathname += find2 + "/" + cuts;
                                    System.out.println(pathname);
                                    File directory = new File(pathname);
                                    if (!directory.exists()) {
                                        directory.mkdirs();
                                    }
                                    String pathname1 = "C:";
                                    String db = "db";
                                    pathname1 += find2 + "/" + db;
                                    System.out.println(pathname1);
                                    File directory1 = new File(pathname1);
                                    if (!directory1.exists()) {
                                        directory1.mkdirs();
                                    }
                                    String pathname2 = "C:";
                                    String ocr = "ocr";
                                    pathname2 += find2 + "/" + ocr;
                                    System.out.println(pathname2);
                                    File directory2 = new File(pathname2);
                                    if (!directory2.exists()) {
                                        directory2.mkdirs();
                                    }
                                    String pathname3 = "C:";
                                    String output = "output";
                                    pathname3 += find2 + "/" + output;
                                    System.out.println(pathname3);
                                    File directory3 = new File(pathname3);
                                    if (!directory3.exists()) {
                                        directory3.mkdirs();
                                    }
                                    String pathname4 = "C:";
                                    String scans = "scans";
                                    pathname4 += find2 + "/" + scans;
                                    System.out.println(pathname4);
                                    File directory4 = new File(pathname4);
                                    if (!directory4.exists()) {
                                        directory4.mkdirs();
                                    }
                                    /*  img.setOnKeyPressed((KeyEvent event) -> {
             if (event.getCode() == KeyCode.F5) {
                 System.out.println("F5 PRESSED");
             File f = new File("pathname:\\Output.jpg");
                // RenderedImage image = null;
                 try {
                     ImageIO.write(f);
                 } catch (IOException ex) {
                     Logger.getLogger(HV.class.getName()).log(Level.SEVERE, null, ex);
                 }
             }
        });*/
                                }
                            }

                        }

                    }

                });

        wb1.load("http://192.168.2.18/a3/host/pmms.ankiti.com/");
        // String url = "https://eclipse.org";
        // Load a page from remote url.
        //  webEngine.load(url);

        vbox2.setPadding(new Insets(3));
        vbox2.setSpacing(3);
        vbox2.getChildren().addAll(browser1, browser);

        HBox.setHgrow(vbox2, Priority.ALWAYS);

        hbox.setPadding(new Insets(20));
//        StackPane.setMargin(hbox, new Insets(20));

        hbox.getChildren().addAll(vbox, vbox2);
        root.getChildren().add(hbox);
        Scene scene = new Scene(root, 300, 200); // the stack pane is the root node
        //scene.setCursor(Cursor.CROSSHAIR);

        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        Application.launch(args);

    }
}

并且它正常运行,但问题是选择完整的场景我只想在一个盒子上的vbox我该怎么办呢错误日志

 run:
    http://192.168.2.18/a3/host/pmms.ankiti.com/
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=login&do=login
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-workdate
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-workdate
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-ini&noob=1&noshell=1&ini=rajveersingh&output_format=html
    83
    114
    rajveersingh
    |[server]||[app]|host_name=pmms.ankiti.com|ns=|session_name=pmms_ankiti_com|lang=en||[portal]|host_name=mms.ankiti.com|ns=|locale=en|domain=pmms.ankiti.com|ent_id=|app=mm-pmms|sec_ns=ankiti|sec_conf=sec-staff-lgc|sec_permissions=mms.ankiti.com|locales=mmstech|email=service@pressmonitor.com|email_name=Press Monitor|email_cc=news@ankiti.com||[shell]|id=wssoj75f2|host_name=pmms.ankiti.com|domain=ankiti.com|ent_id=|locale=|head= |header_bar=

    MMS Print

    |header_brand=|header_menu=|footer_bar=|footer_brand=|footer_menu=|change_at=2017-07-04 03:38:25||[user]|id=7f701032821e1e4d69cfcf7ee|ns=ankiti|ent_id=ank-1|code=mm-dc-rajveer|name=Rajveer verma|user_id=rajveersingh.kumar5@gmail.com|password=$2y$10$b8SLaZYPW/XAZWHWgaVg0.aL4L6sxgmpEnZrOLsGiC3hQu/22xR/m|password_old=*AAD9BAB0626ADA4743CC7582CC20E992C509D43|phone=9990367022|status=|status_remark=|permissions=mms.ankiti.com|created_at=2016-08-14 04:47:47|login_at=2017-10-25 11:00:02|change_at=2017-06-07 14:23:13|logout=`sec_loggedinas Rajveer verma `sec_logout||[pm]|work_date=2017-10-25|work_till=2017-10-25 23:59:59|work_from=2017-10-25 00:00:00|ns=pmin|centre=delhi|ymd=20171025|bar=PM Workdate: 2017-10-25 NS: pmin From: 2017-10-25 00:00:00 Till: 2017-10-25 23:59:59||[pml]|work_date_long=Wednesday, 25th October 2017|work_date=2017-10-25|year_data_dir=//192.168.2.18/pm8/data/pmin/2017|month_data_dir=//192.168.2.18/pm8/data/pmin/2017/201710|date_data_dir=//192.168.2.18/pm8/data/pmin/2017/201710/20171025|date_data_path=/sata1/pm8/data/pmin/2017/201710/20171025|
    [server]

    [app]
    host_name=pmms.ankiti.com
    ns=
    session_name=pmms_ankiti_com
    lang=en

    [portal]
    host_name=mms.ankiti.com
    ns=
    locale=en
    domain=pmms.ankiti.com
    ent_id=
    app=mm-pmms
    sec_ns=ankiti
    sec_conf=sec-staff-lgc
    sec_permissions=mms.ankiti.com
    locales=mmstech
    email=service@pressmonitor.com
    email_name=Press Monitor
    email_cc=news@ankiti.com

    [shell]
    id=wssoj75f2
    host_name=pmms.ankiti.com
    domain=ankiti.com
    ent_id=
    locale=
    head= 
    header_bar=

    MMS Print


    header_brand=
    header_menu=
    footer_bar=
    footer_brand=
    footer_menu=
    change_at=2017-07-04 03:38:25

    [user]
    id=7f701032821e1e4d69cfcf7ee
    ns=ankiti
    ent_id=ank-1
    code=mm-dc-rajveer
    name=Rajveer verma
    user_id=rajveersingh.kumar5@gmail.com
    password=$2y$10$b8SLaZYPW/XAZWHWgaVg0.aL4L6sxgmpEnZrOLsGiC3hQu/22xR/m
    password_old=*AAD9BAB0626ADA4743CC7582CC20E992C509D43
    phone=9990367022
    status=
    status_remark=
    permissions=mms.ankiti.com
    created_at=2016-08-14 04:47:47
    login_at=2017-10-25 11:00:02
    change_at=2017-06-07 14:23:13
    logout=`sec_loggedinas Rajveer verma `sec_logout

    [pm]
    work_date=2017-10-25
    work_till=2017-10-25 23:59:59
    work_from=2017-10-25 00:00:00
    ns=pmin
    centre=delhi
    ymd=20171025
    bar=PM Workdate: 2017-10-25 NS: pmin From: 2017-10-25 00:00:00 Till: 2017-10-25 23:59:59

    [pml]
    work_date_long=Wednesday, 25th October 2017
    work_date=2017-10-25
    year_data_dir=//192.168.2.18/pm8/data/pmin/2017
    month_data_dir=//192.168.2.18/pm8/data/pmin/2017/201710
    date_data_dir=//192.168.2.18/pm8/data/pmin/2017/201710/20171025
    date_data_path=/sata1/pm8/data/pmin/2017/201710/20171025

    1482
    string length is: 1524
    /sata1/pm8/data/pmin/2017/201710/20171025
    C:/sata1/pm8/data/pmin/2017/201710/20171025/cuts
    C:/sata1/pm8/data/pmin/2017/201710/20171025/db
    C:/sata1/pm8/data/pmin/2017/201710/20171025/ocr
    C:/sata1/pm8/data/pmin/2017/201710/20171025/output
    C:/sata1/pm8/data/pmin/2017/201710/20171025/scans
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=home&ini=rajveersingh
    http://192.168.2.18/a3/host/pmms.ankiti.com/?win=IBB&module=mm-pm-headlines
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-headlines&do=subject&subject_uid=Z10
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-edit&clip_id=11.2017-10-25.122&target=wb2&notb=1&img=//192.168.2.18/pm8/data/pmin/2017/201710/20171025/cuts/1318.jpg
    BrowserPane.ChangeListener cancelling http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-edit&clip_id=11.2017-10-25.122&target=wb2&notb=1&img=//192.168.2.18/pm8/data/pmin/2017/201710/20171025/cuts/1318.jpg
    111
    string length is: 174
    //192.168.2.18/pm8/data/pmin/2017/201710/20171025/cuts/1318.jpg
    file://192.168.2.18/pm8/data/pmin/2017/201710/20171025/cuts/1318.jpg
    99
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-edit&clip_id=11.2017-10-25.122&target=wb2
    http://192.168.2.18/a3/host/pmms.ankiti.com/?module=mm-pm-edit&clip_id=11.2017-10-25.122&target=wb2
    Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = StackPane@3e238241[styleClass=root]
    X: 171.00, Y: 125.00, Width: 242.00, Height: 134.00
    X: 409.00, Y: 259.00, Width: 0.00, Height: 0.00
 at javafx.scene.Parent$2.onProposedChange(Parent.java:454)
at com.sun.javafx.collections.VetoableListDecorator.add(VetoableListDecorator.java:206)
at verticalseperator.HV.lambda$start$0(HV.java:94)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)

这是我在选择时遇到的错误。

2 个答案:

答案 0 :(得分:0)

您确定要正确设置事件处理程序吗?如果您查看setOnMousePressedhere)的方法签名,您将看到您没有指定输入事件类型。

通常应该像这样添加事件处理程序:

img.setOnMousePressed(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        System.out.println("X: " + event.getX() + " Y: " + event.getY());
    }
});

答案 1 :(得分:0)

通过此

获取坐标
    private int x,y,w,h;

    public void getCordinates() {
        img.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                x = (int) event.getX();
                y = (int) event.getY();
            }
        });

        img.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                w = (int) (event.getX() - x);
                h = (int) (event.getY() - y);
            }
        });
    }

然后通过将此行添加到空格键操作侦听器

来获取裁剪后的图像
    PixelReader reader = srcImage.getPixelReader();
    WritableImage newImage = new WritableImage(reader, x, y, w, h);

此处srcImage是您要从中选择区域的图像,因此请将其替换为您在代码中加载的图像。而newImage是裁剪后的图像