JBuilder設計獲取圖片屬性程序(3 / 3)

return model;

}

private static byte[] readFromFile(String fileName) throws IOException

{

PicsModel model = null;

FileInputStream fin = new FileInputStream(fileName);

byte [] buf = new byte[fin.available()];

fin.read(buf);

fin.close();

return buf;

}

private static String getFileExtendName(byte[] byte1)

{

String strFileExtendName;

strFileExtendName = null;

//header bytes contains GIF87a or GIF89a?

if ((byte1[0] == 71)&&(byte1[1] == 73)&&(byte1[2] == 70)&&(byte1[3] == 56)&&((byte1[4] == 55)||(byte1[4] == 57))&&(byte1[5] == 97))

{

strFileExtendName = "GIF";

}

//header bytes contains JFIF?

if ((byte1[6] == 74)&&(byte1[7] == 70)&&(byte1[8] == 73)&&(byte1[9] == 70))

{

strFileExtendName = "JPG";

}

//header bytes contains BM?

if ((byte1[0] == 66)&&(byte1[1] == 77))

{

strFileExtendName = "BMP";

}

//header bytes contains PNG?

if ((byte1[1] == 80)&&(byte1[2] == 78)&&(byte1[3] == 71))

{

strFileExtendName = "PNG";

}

return strFileExtendName;

}

private static int getFileAttribute(byte[] byte2,int n,int m,String fileextendname)

{

int j,FileAttributeValue;

j = 0;

FileAttributeValue = 0;

String str,str1;

str = "";

str1 = "";

//如果其大於127,則反之出現少於0,需要進行+256運算

for (int k = 0; k < m; k ++)

{

if (byte2[n-k] < 0)

{

j = byte2[n-k];

j = j + 256;

}

else

{

j = byte2[n-k];

}

str1 = Integer.toHexString(j);

//轉化為16進製,不足位補0

if (str1.length() < 2)

{

str1 = "0" + str1;

}

//格式的不同,表達屬性的字節也有變化

if(fileextendname.equalsIgnoreCase("JPG")||fileextendname.equalsIgnoreCase("PNG"))

{

str = str1 + str;

}

else

{

str = str + str1;

}

}

FileAttributeValue = HexToDec(str);

return FileAttributeValue;

}

private static int HexToDec(String cadhex)

{

int n, i, j,k,decimal;

String CADHEX1;

n = 0;

i = 0;

j = 0;

k = 0;

decimal = 0;

CADHEX1 = null;

n =cadhex.length();

CADHEX1 = cadhex.trim().toUpperCase();

while(i < n)

{

j = CADHEX1.charAt(i);

if ((j >= 48) && (j < 65))

{

j = j - 48;

}

if (j >= 65)

{

j = j - 55;

}

i = i + 1;

//16冪運算

k = 1;

for (int m = 0; m < (n-i); m ++)

{

k = 16 * k;

}

decimal = j*k + decimal;

}

return decimal;

}

private static String getPicColor(int color)

{

int k;

k = 1;

String piccolor;

piccolor = null;

//2冪運算

for (int m = 0; m < color; m ++)

{

k = 2 * k;

}

Integer kk;

kk = null;

if (k >= 1048576)

{

k = k / 1048576;

kk = new Integer(k);

piccolor = kk.toString() + "M";

}

else if (k >= 1024)

{

k = k / 1024;

kk = new Integer(k);

piccolor = kk.toString() + "K";

}

else if (k > 0)

{

kk = new Integer(k);

piccolor = kk.toString();

}

return piccolor;

}

}

四、 後記

以上源代碼在Win 2k和Jbuilder 7等環境下正常運行過。由於時間關係,該程序目前隻支持GIF(有87A/89A兩種格式)、JPG、PNG和BMP格式。另外,對於PNG圖片因缺少相關資源文件未作色彩分析。