【发布时间】:2015-01-30 10:46:50
【问题描述】:
这个小项目的目的是将图像(在本例中为旗帜)分解成像拼图一样的片段,并将每个片段存储在 2D 数组的一部分中。然后,我希望能够单独查看每件作品,以便我知道它有效。
我创建了一个加载和存储图像的对象类。我在主类中创建了该对象,然后将其传递给我的splitImage 方法,该方法将图像分成块并存储在数组中。我希望能够查看数组的一部分以检查 splitImage 方法是否正常工作。但是从长远来看,我确实需要查看数组,因为我将确定每个图像片段中像素的颜色并计算图像中每种颜色的数量。当我运行当前代码时,我在控制台中得到以下信息,
Exception in thread "main" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at sample.ImageFrame.splitImage(ImageFrame.java:28)
at sample.ImageFrame.main(ImageFrame.java:59)
28 是行 - BufferedImage image = (BufferedImage)((Image) icon.getImage());
59 是 - ImageFrame.splitImage(imageSwing.label);
我已经玩了一段时间了,改变了位置尝试了其他选项,但都没有成功。非常感谢您的帮助。 代码如下,提前致谢。
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing()
{
super("Test Image Array");
setLayout(new FlowLayout());
Icon flag = new ImageIcon(getClass().getResource("Italy_flag.jpg"));
label = new JLabel(flag);
label.setToolTipText("Italian Flag");
add(label);
}//main
}//class
public class ImageFrame
{
//public ImageSwing imageSwing = new ImageSwing();
//ImageSwing imageSwing = new ImageSwing();
public static BufferedImage splitImage(JLabel i) throws IOException
{
//Holds the dimensions of image
int rows = 4;
int cols = 4;
ImageIcon icon = (ImageIcon)i.getIcon();
BufferedImage image = (BufferedImage)((Image) icon.getImage());
int chunks = rows * cols; //Total amount of image pieces
int partWidth = i.getWidth() / cols; // determines the piece width
int partHeight = i.getHeight() / rows; //determines the piece height
int count = 0;
BufferedImage[][] flagArray = new BufferedImage[rows][cols]; //2D Array to hold each image piece
for (int x = 0; x < rows; x++)
{
for (int y = 0; y < cols; y++)
{
//Initialize the image array with image chunks
flagArray[x][y] = new BufferedImage(partWidth, partHeight, image.getType());
// draws the image chunk
Graphics2D gr = flagArray[x][y].createGraphics();
gr.drawImage(image, 0, 0, partWidth, partHeight, partWidth * y, partHeight * x, partWidth * y + partWidth, partHeight * x + partHeight, null);
gr.dispose();
}
}
return flagArray[rows][cols];
}
public static void main(String[] args)
{
ImageSwing imageSwing = new ImageSwing();
try
{
ImageFrame.splitImage(imageSwing.label);
} catch (IOException e)
{
e.printStackTrace();
}
imageSwing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
imageSwing.setSize(260,180);
imageSwing.setVisible(true);
}//main
}//class
【问题讨论】:
标签: java image jlabel multidimensional-array bufferedimage