gpt4 book ai didi

java - 如何在以下代码中调整 ImageIcon 数组列表的大小

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

我有 ImageIcon 数组列表,它有多种尺寸的图标,所以我需要将它们设置为特定的(85*100)尺寸。那么我该怎么做呢?我的代码如下:

File file = new File("C://Users/ks/Desktop/DB");

if (file != null) {
File[] files = file.listFiles(new FilenameFilter() {

public boolean accept(File file, String fileName) {

if (fileName.endsWith(".png")) {
return true;
} else {
System.out.println("No jpg files");
return false;

}

}
});

System.out.println("Current dir : " + file.getCanonicalPath());

List<ImageIcon> images = new ArrayList<ImageIcon>();// Array list

for (int fileInList = 0; fileInList < files.length; fileInList++) {
System.out.print(files[fileInList].toString() + " ");
System.out.println("this is forloop" + fileInList);
if (files[fileInList].isFile()) {

images.add(0, new ImageIcon(ImageIO.read(files[fileInList])));// add all imagaes

}
} }

FlowLayout f = new FlowLayout();

JPanel p = new JPanel(f);


f.setAlignment(FlowLayout.LEFT);

p.setSize(700, 100);

for (int x = 0; x < images.size(); x++) {

p.add(new JLabel(images.get(x)));

}

jPanel1.setPreferredSize(p.getSize());
jPanel1.add(p);
jPanel1.revalidate();
jPanel1.repaint();


} else {
System.out.println("No file Found"); // Array index out of bound display insted of this
}

} catch (IOException e) {

e.printStackTrace();
}
System.out.println("Success");

最佳答案

要调整图像大小,您可以使用 Image.getScaledInstance()

List<ImageIcon> images = new ArrayList<ImageIcon>();// Array list

for (int fileInList = 0; fileInList < files.length; fileInList++) {
if (files[fileInList].isFile()) {
Image baseImage = ImageIO.read(files[fileInList]);
Image scaledImage = baseImage.getScaledInstance(85, 100, java.awt.Image.SCALE_SMOOTH);
images.add(0, new ImageIcon(scaledImage));
}
}

或者您可以使用 Graphics.drawImage()

List<ImageIcon> images = new ArrayList<ImageIcon>();// Array list

for (int fileInList = 0; fileInList < files.length; fileInList++) {
if (files[fileInList].isFile()) {
Image baseImage = ImageIO.read(files[fileInList]);
BufferedImage scaledImage = new BufferedImage(85, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D)scaledImage.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(baseImage, 0, 0, 85, 100, null);
images.add(0, new ImageIcon(scaledImage));
}
}

关于java - 如何在以下代码中调整 ImageIcon 数组列表的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18437128/

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