gpt4 book ai didi

Java Server Faces 从数组加载图像

转载 作者:行者123 更新时间:2023-12-01 15:28:48 26 4
gpt4 key购买 nike

我有一个 ImageBean 类,我想用它从数组加载图像。我已经在数组中预加载了图像(总共 9 个),并且希望每次刷新浏览器时连续显示一张图像。这些图像被命名为“1.jpg、2.jpg”等(即图像“1”点击刷新,图像“2”点击刷新,...图像“9”)。任何帮助将不胜感激。谢谢。

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import javax.imageio.ImageIO;

@ManagedBean(name="ImageBean")
@SessionScoped
public class ImageBean implements Serializable
{
private static final long serialVersionUID = 1L;
ArrayList<Image> myArr = new ArrayList<Image>();
BufferedImage img = null;

public ImageBean()
{
for(int i = 1; i < 10; i++)
{
try
{
img = ImageIO.read(new File(i + ".jpg"));
}
catch (IOException ex) {}

myArr.add(img);
}
}

public BufferedImage getImage(int i)
{
return (BufferedImage) myArr.get(i);
}
}

编辑1

我稍微编辑了代码,所以我使用 BufferedImage 数组而不是 ArrayList。现在我没有收到错误,但图像未在浏览器中显示。

public class ImageBean implements Serializable 
{
private static final long serialVersionUID = 1L;
BufferedImage[] myArr = new BufferedImage[9];

public ImageBean()
{
for(int i = 0; i < 9; i++)
{
try
{
myArr[i] = (ImageIO.read(new File(i+1 + ".jpg")));
}
catch (IOException ex) {}
}
}

public BufferedImage getImage(int i)
{
return (BufferedImage) myArr[i];
}
}

最佳答案

一个简单的解决方案是添加一个变量来保存当前图像并获取下一个图像...(只需记住重置最后一个图像)

@SessionScoped
public class ImageBean implements Serializable
{
private static final long serialVersionUID = 1L;
ArrayList<Image> myArr = new ArrayList<Image>();
BufferedImage img = null;

private int currImgId = 1;

public ImageBean()
{
for(int i = 1; i < 10; i++)
{
try
{
img = ImageIO.read(new File(i + ".jpg"));
}
catch (IOException ex) {}

myArr.add(img);
}
}

public BufferedImage getImage()
{
// Reset logic would go here...probably best with array.size...
return (BufferedImage) myArr.get(currImgId++);
}

}

关于Java Server Faces 从数组加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825994/

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