So now you could have your items store a image location or you could make your images have the same ID as your items.
If you item stores a image location you would look up your item by it’s ID and get the image location.
If you save the image with the same ID then you just load the image using the ID as the file name.
Here is a example of loading a image with the ID as the file name.
ImageLoad.java
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
public class ImageLoad {
/**
* Read the item file and load the item image.
*/
public ImageLoad(){
//File name (Location is assuming the file is in the same folder)
String itemFile = "./myitem.txt";
String imageFileName = "";
//Get the file
BufferedReader input = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(itemFile)));
String line;
//Read the file line by line.
try{
while((line = input.readLine()) != null){
imageFileName = line.split(":")[1].trim();
}
}catch(Exception e){
e.printStackTrace();
}
//Echo the image filename
System.out.println(imageFileName);
//Load the image
BufferedImage myItemImage = loadImage("./" + imageFileName + ".png");
//Echo the image
System.out.println(myItemImage);
}
/**
* Method to load a image.
*
* @param ref
* @return BufferedImage
*/
public BufferedImage loadImage(String ref){
BufferedImage bimg = null;
try{
bimg = ImageIO.read(this.getClass().getClassLoader().getResource(ref));
}catch(Exception e){
e.printStackTrace();
}
return bimg;
}
/**
* Start.
*
* @param args
*/
public static void main(String args[]){
new ImageLoad();
}
}
myItem.txt
Image: 1
1.png
This is just a image made in paint 5x5 pixels with a black background.
Output:
1
BufferedImage@7b19f779: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@65c66812 transparency = 3 has alpha = true isAlphaPre = false ByteInterleavedRaster: width = 5 height = 5 #numDataElements 4 dataOff[0] = 3