注:此功能不與iPhone壓縮的PNG工作,這壓縮是自動進行的XCode這裏改變圖像的頭,看到更多的細節,以及如何禁用此功能:http://discussions.apple.com/thread.jspa?threadID=1751896
未來版本的PSFramework也會解釋這個標題,敬請關注。
看到這個功能,她就是這麼做的。只讀取PNG文件的30個字節並返回大小(CGSize)。該功能是處理稱爲PSFramework(http://sourceforge.net/projects/photoshopframew/)的圖像框架的一部分。尚未實現其他圖像格式,歡迎開發者。該項目是GNU許可下的開源軟件。
CGSize PSPNGSizeFromMetaData(NSString* anFileName) {
// File Name from Bundle Path.
NSString *fullFileName = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], anFileName ];
// File Name to C String.
const char* fileName = [fullFileName UTF8String];
/* source file */
FILE * infile;
// Check if can open the file.
if ((infile = fopen(fileName, "rb")) == NULL)
{
NSLog(@"PSFramework Warning >> (PSPNGSizeFromMetaData) can't open the file: %@", anFileName);
return CGSizeZero;
}
////// ////// ////// ////// ////// ////// ////// ////// ////// ////// //////
// Lenght of Buffer.
#define bytesLenght 30
// Bytes Buffer.
unsigned char buffer[bytesLenght];
// Grab Only First Bytes.
fread(buffer, 1, bytesLenght, infile);
// Close File.
fclose(infile);
////// ////// ////// ////// //////
// PNG Signature.
unsigned char png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
// Compare File signature.
if ((int)(memcmp(&buffer[0], &png_signature[0], 8))) {
NSLog(@"PSFramework Warning >> (PSPNGSizeFromMetaData) : The file (%@) don't is one PNG file.", anFileName);
return CGSizeZero;
}
////// ////// ////// ////// ////// ////// ////// ////// ////// //////
// Calc Sizes. Isolate only four bytes of each size (width, height).
int width[4];
int height[4];
for (int d = 16; d < (16 + 4); d++) {
width[ d-16] = buffer[ d ];
height[d-16] = buffer[ d + 4];
}
// Convert bytes to Long (Integer)
long resultWidth = (width[0] << (int)24) | (width[1] << (int)16) | (width[2] << (int)8) | width[3];
long resultHeight = (height[0] << (int)24) | (height[1] << (int)16) | (height[2] << (int)8) | height[3];
// Return Size.
return CGSizeMake(resultWidth, resultHeight);
}
CGImageSource是完美的API,但令人討厭的是它在iPhone上不可用。你可能必須自己實現它。也就是說,請記住,如果您使用+ imageWithContentsOfFile,UIImage將清除其數據:這將消除您的內存使用問題。 – 2009-10-11 23:13:35