gpt4 book ai didi

java - 如何通过文件路径绘制图像

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:06 25 4
gpt4 key购买 nike

我正在尝试通过文件路径显示图像。我的 src 文件夹中有该图像,并且我尝试了大约 5 种不同类型的代码。

忽略注释掉的代码,这些只是我要测试的形状

我已经尝试过文件路径和文件名,但没有任何效果。它没有给我任何错误或任何东西。

public void ImagePanel() {
try {
image = ImageIO.read(new File("BMan.jpg"));
} catch (IOException ex) {
System.out.println(ex);
}
}

public static void main(String[] args) {
JPanel panel = new MyPanel();
}
protected void paintComponent(Graphics g){

super.paintComponent(g);
//g.setColor(Color.RED);
//g.fillOval(CircleX, CircleY, CircleH, CircleW);
//g.setColor(Color.GREEN);
//g.fillRect(SquareX, SquareY, SquareW, SquareH);
g.drawImage(image, 50, 50, this);

}

最佳答案

这是我对该组件的实现:

public class ImageView extends JComponent
implements ComponentListener {
private static final long serialVersionUID = 3761966077344495154L;

private BufferedImage image;
private int imageX;
private int imageY;
private int imageWidth;
private int imageHeight;

/** Creates a new instance of ImageView */
public ImageView() {
addComponentListener(this);
}


public BufferedImage getImage() {
return image;
}

public Rectangle getImageBounds() {
if (image == null) {
return null;
} else {
return new Rectangle(imageX, imageY, imageWidth, imageHeight);
}
}

public void setImage(final BufferedImage newValue) {
image = newValue;
computeBounds();
repaint();
}


@Override
public void paint(Graphics g) {
long tm = System.currentTimeMillis();
if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}

BufferedImage img = image;
if (img != null) {
g.drawImage(img, imageX, imageY, imageWidth, imageHeight, null);
}
tm = System.currentTimeMillis()-tm;
}

public void componentResized(ComponentEvent e) {
computeBounds();
}

public void componentMoved(ComponentEvent e) {
}

public void componentShown(ComponentEvent e) {
computeBounds();
}

public void componentHidden(ComponentEvent e) {
}

private void computeBounds() {
BufferedImage img = image;
if (img != null) {
int width = this.getWidth();
int height = this.getHeight();
int wi = img.getWidth();
int hi = img.getHeight();
imageWidth = width;
imageHeight = height;
imageX = 0;
imageY = 0;
if (wi*height < hi*width) {
imageWidth = wi*height/hi;
imageX = (width-imageWidth)/2;
} else {
imageHeight = hi*width/wi;
imageY = (height-imageHeight)/2;
}
}
}

关于java - 如何通过文件路径绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002275/

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