两种常会用到的图片载入函数,第一种是根据给定的图片路径生成图片,第二种是将图片压到数组中,根据在数组中的起始位置和长度以及数组文件的路径生成图片
/**
* 图片载入函数
* @param str String 图片路径
* @return Image 返回载入后的图片
*/
private Image loadImage(String str) {
Image img = null;
try {
img = Image.createImage(str);
}
catch (IOException e) {
e.printStackTrace();
System.out.print("trouble in loadimage:" + str + " Exception is " + e);
}
return img;
}
/**
* 图片载入函数(数组版)
* @param imgArray byte[]
* @param start int
* @param length int
* @return Image
*/
private Image loadImage(byte[] imgArray, int start, int length) {
Image img = null;
try {
img = Image.createImage(imgArray, start, length);
}
catch (Exception e) {
e.printStackTrace();
System.out.print("trouble in loadImg by imgArray");
}
return img;
}
/**
* 流中读取图片
* @param start long
* @param len int
* @param fname String
* @return byte[]
*/
private byte[] readImage(long start, int len, String fname) {
byte[] buff = null;
buff = new byte[len];
try {
InputStream is = getClass().getResourceAsStream(fname);
is.skip(start);
is.read(buff);
is.close();
is = null;
for (int i = 0; i < buff.length; i++) {
buff[i] ^= 2;
}
}
catch (Exception e) {
e.printStackTrace();
}
return buff;
}
/**
* 计算流读取的起始位置
* @param c short[]
* @param index short
* @return long
*/
private long getStart(short[] c, short index) {
long start = 0;
for (int i = 0; i < index; i++) {
start += c[i];
}
return start;
}