gpt4 book ai didi

Java : Get image as a BufferedImage from classpath

转载 作者:行者123 更新时间:2023-12-01 10:34:59 24 4
gpt4 key购买 nike

我正在开发一个 JavaFX 项目,在该项目中我必须打印一些我有路径的图像。现在的问题是,我想将图像获取为 BufferedImage,然后调用我拥有的打印函数。我怎样才能做到这一点。任何帮助都会很好。

代码:

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

编辑:

更新打印功能:

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

图像位于类路径中。请告诉我。谢谢。 :-)

最佳答案

我不太确定参数包含什么,但基本思想是

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

这假设 localPath 包含定义的资源名称 here ,或者相对于当前类(但请注意,路径的所有组成部分都必须是有效的 Java 标识符,因此没有 .. 等),或者绝对(即相对于类路径),如果它开始 /.

由于您正在编写 JavaFX 项目,因此使用 JavaFX API 来实现此目的肯定更有意义。另请注意,无需在 FX 应用程序线程上进行打印,而且建议不要这样做。所以你可以这样做

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

关于Java : Get image as a BufferedImage from classpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com