简体   繁体   中英

Java : Get image as a BufferedImage from classpath

I am working on a JavaFX project in which I have to print a few images for which I have the path. Now the problem is, I want to get the image as a BufferedImage and then call the print function which I have. How can I achieve this. Any help would be nice.

Code :

public void printThis(String localPath){

       // What should I do here? 

    System.out.println("Lets print this. ");
}


private void printImage(BufferedImage image) {
    java.awt.print.PrinterJob printJob = java.awt.print.PrinterJob.getPrinterJob();
    printJob.setPrintable(new Printable() {
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            // Get the upper left corner that it printable
            int x = (int) Math.ceil(pageFormat.getImageableX());
            int y = (int) Math.ceil(pageFormat.getImageableY());
            if (pageIndex != 0) {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
            return PAGE_EXISTS;
        }
    });

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                printJob.print();
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    });
}

Edit :

Updated print function :

public void printImage(ImageView image) {
        Printer printer = Printer.getDefaultPrinter();
        PrinterJob printJob = PrinterJob.createPrinterJob(printer);
        PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
        if (printJob != null) {
            boolean success = printJob.printPage(image);
            if (success) {
                printJob.endJob();
            }
        }
    }

The images are in classpath. Kindly let me know. Thank you. :-)

I'm not quite sure what the parameter contains, but the basic idea is

public void printThis(String localPath) {
    try {
        InputStream in = getClass().getResourceAsStream(localPath);
        BufferedImage image = ImageIO.read(in);
        printImage(image);
    } catch (Exception exc) {
        exc.printStackTrace();
        // handle elegantly...
    }
}

This assumes localPath contains the name of the resource as defined here , either relative to the current class (but note that all components of the path must be valid Java identifiers, so no .. , etc), or absolute (ie relative to the classpath) if it begins / .

Since you are writing a JavaFX project, though, it surely makes more sense to use JavaFX APIs for this instead. Also note there's no need to do the printing on the FX Application Thread, and it's probably advisable not to. So you could do

public void printThis(String localPath) {

    // note you can use overloaded forms of the Image constructor
    // if you want to scale, etc
    Image image = new Image(getClass().getResource(localPath).toExternalForm());
    new Thread(() -> printImage(image)).start();
}

public void printImage(Image image) {
    ImageView imageView = new ImageView(image);
    PrinterJob printJob = PrinterJob.createPrinterJob();
    if (printJob != null) {
        // scale image if necessary by using imageView.setPreserveRatio(true)
        // along with imageView.setFitWidth(...) and imageView.setFitHeight(...)
        boolean success = printJob.printPage(imageView);
        if (success) {
            printJob.endJob();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM