简体   繁体   English

如何从非方形图像文件创建非方形 BufferedImage?

[英]How can I create a non-square BufferedImage from a non-square image file?

I'm trying to create a BufferedImage from an arbitrary image file and then center that image in the background of a JPanel.我正在尝试从任意图像文件创建一个 BufferedImage,然后将该图像置于 JPanel 的背景中。 I don't have any problems with square images, but I can't figure out how to handle non-square images.我对方形图像没有任何问题,但我不知道如何处理非方形图像。

Some debugging indicates that the (immediate) problem is that when I use ImageIO to create a BufferedImage from a rectangular input file, say one that's 256x128, BufferedImage.getHeight() returns 256 rather than 128.一些调试表明(直接的)问题是,当我使用 ImageIO 从矩形输入文件创建 BufferedImage 时,比如 256x128,BufferedImage.getHeight() 返回 256 而不是 128。

Here's a snippet approximating my code:这是一个近似于我的代码的片段:

class ExtendedPanel extends JPanel {

    static final int WIDTH = 400;
    static final int HEIGHT = 400;

    BufferedImage image;

    public ExtendedPanel(File f) {
       super();
       setPreferredSize(new Dimension(WIDTH,HEIGHT));
       image = ImageIO.read(f);
    }

    @Override
    public void paintComponent(Graphics g) {
        int x = (WIDTH - image.getWidth())/2;
        int y = (HEIGHT - image.getHeight())/2;
        Graphics2D g2d = (Graphics2d)g;
        g2d.drawRenderedImage(image,AffineTransform.getTranslateInstance(x,y));
    }

}

As I said, this is fine for square image files.正如我所说,这适用于方形图像文件。 But with rectangular images that are wider than they are tall, the image is displayed higher than it should be.但是对于宽度大于高度的矩形图像,图像显示得比应有的高。 I haven't tried it yet with images taller than they are wide but I'm afraid that it that case the image would be displayed too far to the left.我还没有尝试过使用比宽度高的图像,但我担心在这种情况下图像会向左显示太远。 What can I do?我能做什么?

It is more a problem of (understanding) the right calculation.这更像是(理解)正确计算的问题。

public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2d)g;

    // How to scale the image:
    double xscale = ((double)WIDTH) / image.getWidth();
    double yscale = ((double)HEIGHT) / image.getHeight());

    // When scaling proportionally:
    double scale = Math.min(xscale, yscale); // max for covering entire panel.
    xscale = scale;
    yscale = scale;

    double w = scalex * image.getWidth();
    double h = scaley * image.getHeight();
    double x = (getWidth() - w) / 2;
    double y = (getHeight() - h) / 2;
    g.drawImage(img, (int)x, (int)y, (int)w, (int)h, Color.BLACK, null);
    //g2d.translate(x, y);
    //g2d.scale(xscale, yscale);
    //g2d.draw...;
}

Using the simple (scaling) version of drawImage what is needed is entirely clear.使用简单(缩放)版本的drawImage需要什么是完全清楚的。

To be considered is proportionally scaling, filling entirely (loss of image part) or upto maximal size (seeing background).要考虑的是按比例缩放、完全填充(图像部分丢失)或达到最大尺寸(查看背景)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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