java设置图像的分辨率和打印尺寸

发布于 2024-09-06 14:30:26 字数 591 浏览 3 评论 0原文

我编写了一个程序,生成一个 BufferedImage 以显示在屏幕上,然后打印。图像的一部分包括 1 像素宽的网格线。即,一行为1个像素,行与行之间大约有10个像素。由于屏幕分辨率的原因,图像显示得比这大得多,每行有几个像素。我想将其绘制得更小,但是当我缩放图像(通过使用 Image.getScaledInstance 或 Graphics2D.scale)时,我会丢失大量细节。

我也想打印图像,并且正在处理同样的问题。在这种情况下,我使用此代码来设置分辨率:

HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
PrinterResolution pr = new PrinterResolution(250, 250, ResolutionSyntax.DPI);
set.add(pr);
job.print(set);

这可以使图像变小而不丢失细节。但问题是图像在同一边界处被切断,就好像我没有设置分辨率一样。我也很困惑,因为我期望更大的 DPI 来制作更小的图像,但它却以相反的方式工作。

我在 Windows 7 上使用 java 1.6 和 eclipse。

I wrote a program that generates a BufferedImage to be displayed on the screen and then printed. Part of the image includes grid lines that are 1 pixel wide. That is, the line is 1 pixel, with about 10 pixels between lines. Because of screen resolution, the image is displayed much bigger than that, with several pixels for each line. I'd like to draw it smaller, but when I scale the image (either by using Image.getScaledInstance or Graphics2D.scale), I lose significant amounts of detail.

I'd like to print the image as well, and am dealing with the same problem. In that case, I am using this code to set the resolution:

HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
PrinterResolution pr = new PrinterResolution(250, 250, ResolutionSyntax.DPI);
set.add(pr);
job.print(set);

which works to make the image smaller without losing detail. But the problem is that the image is cut off at the same boundary as if I hadn't set the resolution. I'm also confused because I expected a larger number of DPI to make a smaller image, but it's working the other way.

I'm using java 1.6 on Windows 7 with eclipse.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一个人的旅程 2024-09-13 14:30:27

关于图像在页面边界被剪切的问题,您检查过图形的剪切区域吗?我的意思是尝试:

System.out.println(graphics.getClipBounds());

并确保它设置正确。

Regarding the image being cut-off on the page boundary, have you checked the clip region of the graphics? I mean try :

System.out.println(graphics.getClipBounds());

and make sure it is correctly set.

☆獨立☆ 2024-09-13 14:30:27

我也有同样的问题。这是我的解决方案。

首先更改打印作业的分辨率...

    PrinterJob job = PrinterJob.getPrinterJob();
    // Create the paper size of our preference
    double cmPx300 = 300.0 / 2.54;
    Paper paper = new Paper();
    paper.setSize(21.3 * cmPx300, 29.7 * cmPx300);
    paper.setImageableArea(0, 0, 21.3 * cmPx300, 29.7 * cmPx300);
    PageFormat format = new PageFormat();
    format.setPaper(paper);
    // Assign a new print renderer and the paper size of our choice !
    job.setPrintable(new PrintReport(), format);

    if (job.printDialog()) {
        try {
            HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
            PrinterResolution pr = new PrinterResolution((int) (dpi), (int) (dpi), ResolutionSyntax.DPI);
            set.add(pr);
            job.setJobName("Jobname");
            job.print(set);
        } catch (PrinterException e) {
        }
    }

现在您可以将您喜欢的所有内容绘制到新的高分辨率纸张中,如下所示!

    public class PrintReport implements Printable {

    @Override
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
        // Convert pixels to cm to lay yor page easy on the paper...
        double cmPx = dpi / 2.54;
        Graphics2D g2 = (Graphics2D) g;
        int totalPages = 2; // calculate the total pages you have...
        if (page < totalPages) {

            // Draw Page Header
            try {
                BufferedImage image = ImageIO.read(ClassLoader.getSystemResource(imgFolder + "largeImage.png"));
                g2.drawImage(image.getScaledInstance((int) (4.8 * cmPx), -1, BufferedImage.SCALE_SMOOTH), (int) (cmPx),
                        (int) (cmPx), null);
            } catch (IOException e) {
            }
            // Draw your page as you like...
            // End of Page
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

I had the same problem. Here is my solution.

First change the resolution of the print job...

    PrinterJob job = PrinterJob.getPrinterJob();
    // Create the paper size of our preference
    double cmPx300 = 300.0 / 2.54;
    Paper paper = new Paper();
    paper.setSize(21.3 * cmPx300, 29.7 * cmPx300);
    paper.setImageableArea(0, 0, 21.3 * cmPx300, 29.7 * cmPx300);
    PageFormat format = new PageFormat();
    format.setPaper(paper);
    // Assign a new print renderer and the paper size of our choice !
    job.setPrintable(new PrintReport(), format);

    if (job.printDialog()) {
        try {
            HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
            PrinterResolution pr = new PrinterResolution((int) (dpi), (int) (dpi), ResolutionSyntax.DPI);
            set.add(pr);
            job.setJobName("Jobname");
            job.print(set);
        } catch (PrinterException e) {
        }
    }

Now you can draw everything you like into the new high resolution paper like this !

    public class PrintReport implements Printable {

    @Override
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
        // Convert pixels to cm to lay yor page easy on the paper...
        double cmPx = dpi / 2.54;
        Graphics2D g2 = (Graphics2D) g;
        int totalPages = 2; // calculate the total pages you have...
        if (page < totalPages) {

            // Draw Page Header
            try {
                BufferedImage image = ImageIO.read(ClassLoader.getSystemResource(imgFolder + "largeImage.png"));
                g2.drawImage(image.getScaledInstance((int) (4.8 * cmPx), -1, BufferedImage.SCALE_SMOOTH), (int) (cmPx),
                        (int) (cmPx), null);
            } catch (IOException e) {
            }
            // Draw your page as you like...
            // End of Page
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }
俏︾媚 2024-09-13 14:30:27

听起来你的问题是你正在将网格线作为 BufferedImage 的一部分,并且缩放时看起来不太好。为什么不在绘制图像后使用 drawLine() 来生成网格?

It sounds like your problem is that you are making the grid lines part of the BufferedImage and it doesn't look good when scaled. Why not use drawLine() to produce the grid after your image has been drawn?

情释 2024-09-13 14:30:27

使用 Java 转换具有尺寸的图像的代码并打印转换后的图像。

类: ConvertImageWithDimensionsAndPrint.java

package com.test.convert;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ConvertImageWithDimensionsAndPrint {
    private static final int IMAGE_WIDTH = 800;
    private static final int IMAGE_HEIGHT = 1000;

public static void main(String[] args) {
    try {
        String sourceDir = "C:/Images/04-Request-Headers_1.png";
        File sourceFile = new File(sourceDir);
        String destinationDir = "C:/Images/ConvertedImages/";//Converted images save here
        File destinationFile = new File(destinationDir);
        if (!destinationFile.exists()) {
            destinationFile.mkdir();
        }
        if (sourceFile.exists()) {
            String fileName = sourceFile.getName().replace(".png", "");
            BufferedImage bufferedImage = ImageIO.read(sourceFile);
            int type = bufferedImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : bufferedImage.getType();

            BufferedImage resizedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, type);
            Graphics2D graphics2d = resizedImage.createGraphics();
            graphics2d.drawImage(bufferedImage, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);//resize goes here
            graphics2d.dispose();

            ImageIO.write(resizedImage, "png", new File( destinationDir + fileName +".png" ));

            int oldImageWidth = bufferedImage.getWidth();
            int oldImageHeight = bufferedImage.getHeight();
            System.out.println(sourceFile.getName() +" OldFile with Dimensions: "+ oldImageWidth +"x"+ oldImageHeight);
            System.out.println(sourceFile.getName() +" ConvertedFile converted with Dimensions: "+ IMAGE_WIDTH +"x"+ IMAGE_HEIGHT);

            //Print the image file
            PrintActionListener printActionListener = new PrintActionListener(resizedImage);
            printActionListener.run();
        } else {
            System.err.println(destinationFile.getName() +" File not exists");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

PrintActionListener.java 的参考

package com.test.convert;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintActionListener implements Runnable {

private BufferedImage image;

public PrintActionListener(BufferedImage image) {
    this.image = image;
}

@Override
public void run() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(new ImagePrintable(printJob, image));

    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (PrinterException prt) {
            prt.printStackTrace();
        }
    }
}

public class ImagePrintable implements Printable {

    private double x, y, width;

    private int orientation;

    private BufferedImage image;

    public ImagePrintable(PrinterJob printJob, BufferedImage image) {
        PageFormat pageFormat = printJob.defaultPage();
        this.x = pageFormat.getImageableX();
        this.y = pageFormat.getImageableY();
        this.width = pageFormat.getImageableWidth();
        this.orientation = pageFormat.getOrientation();
        this.image = image;
    }

    @Override
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex == 0) {
            int pWidth = 0;
            int pHeight = 0;
            if (orientation == PageFormat.PORTRAIT) {
                pWidth = (int) Math.min(width, (double) image.getWidth());
                pHeight = pWidth * image.getHeight() / image.getWidth();
            } else {
                pHeight = (int) Math.min(width, (double) image.getHeight());
                pWidth = pHeight * image.getWidth() / image.getHeight();
            }
            g.drawImage(image, (int) x, (int) y, pWidth, pHeight, null);
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

}

}

输出:

04-Request-Headers_1.png OldFile with Dimensions: 1224x1584
04-Request-Headers_1.png ConvertedFile converted with Dimensions: 800x1000

图像转换后,将打开打印窗口来打印转换后的图像。该窗口显示如下,从名称下拉列表中选择打印机,然后单击确定按钮。

打印窗口

Code for Convert image with dimensions using Java and print the converted image.

Class: ConvertImageWithDimensionsAndPrint.java

package com.test.convert;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ConvertImageWithDimensionsAndPrint {
    private static final int IMAGE_WIDTH = 800;
    private static final int IMAGE_HEIGHT = 1000;

public static void main(String[] args) {
    try {
        String sourceDir = "C:/Images/04-Request-Headers_1.png";
        File sourceFile = new File(sourceDir);
        String destinationDir = "C:/Images/ConvertedImages/";//Converted images save here
        File destinationFile = new File(destinationDir);
        if (!destinationFile.exists()) {
            destinationFile.mkdir();
        }
        if (sourceFile.exists()) {
            String fileName = sourceFile.getName().replace(".png", "");
            BufferedImage bufferedImage = ImageIO.read(sourceFile);
            int type = bufferedImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : bufferedImage.getType();

            BufferedImage resizedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, type);
            Graphics2D graphics2d = resizedImage.createGraphics();
            graphics2d.drawImage(bufferedImage, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);//resize goes here
            graphics2d.dispose();

            ImageIO.write(resizedImage, "png", new File( destinationDir + fileName +".png" ));

            int oldImageWidth = bufferedImage.getWidth();
            int oldImageHeight = bufferedImage.getHeight();
            System.out.println(sourceFile.getName() +" OldFile with Dimensions: "+ oldImageWidth +"x"+ oldImageHeight);
            System.out.println(sourceFile.getName() +" ConvertedFile converted with Dimensions: "+ IMAGE_WIDTH +"x"+ IMAGE_HEIGHT);

            //Print the image file
            PrintActionListener printActionListener = new PrintActionListener(resizedImage);
            printActionListener.run();
        } else {
            System.err.println(destinationFile.getName() +" File not exists");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Reference of PrintActionListener.java

package com.test.convert;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintActionListener implements Runnable {

private BufferedImage image;

public PrintActionListener(BufferedImage image) {
    this.image = image;
}

@Override
public void run() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(new ImagePrintable(printJob, image));

    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (PrinterException prt) {
            prt.printStackTrace();
        }
    }
}

public class ImagePrintable implements Printable {

    private double x, y, width;

    private int orientation;

    private BufferedImage image;

    public ImagePrintable(PrinterJob printJob, BufferedImage image) {
        PageFormat pageFormat = printJob.defaultPage();
        this.x = pageFormat.getImageableX();
        this.y = pageFormat.getImageableY();
        this.width = pageFormat.getImageableWidth();
        this.orientation = pageFormat.getOrientation();
        this.image = image;
    }

    @Override
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex == 0) {
            int pWidth = 0;
            int pHeight = 0;
            if (orientation == PageFormat.PORTRAIT) {
                pWidth = (int) Math.min(width, (double) image.getWidth());
                pHeight = pWidth * image.getHeight() / image.getWidth();
            } else {
                pHeight = (int) Math.min(width, (double) image.getHeight());
                pWidth = pHeight * image.getWidth() / image.getHeight();
            }
            g.drawImage(image, (int) x, (int) y, pWidth, pHeight, null);
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

}

}

Output:

04-Request-Headers_1.png OldFile with Dimensions: 1224x1584
04-Request-Headers_1.png ConvertedFile converted with Dimensions: 800x1000

After conversion of a image a Print window will be open for printing the converted image. The window displays like below, Select the printer from Name dropdown and Click OK button.

Print Window

倾城泪 2024-09-13 14:30:27

您可以使用以下任一方法来提高缩放质量。我相信 BiCubic 能提供更好的结果,但比 BILINEAR 慢。

g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

我也不会使用 Image.getScaledInstance() 因为它非常慢。我不确定打印,因为我正在努力解决类似的问题。

You can use either of the following to improve the quality of the scaling. I believe BiCubic gives better results but is slower than BILINEAR.

g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

I would also not use Image.getScaledInstance() as it is very slow. I'm not sure about the printing as I'm struggling with similar issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文