Nota: Questa funzione non funziona con iPhone PNG compressi, questa compressione viene eseguita automaticamente dal XCode e modificare l'intestazione dell'immagine, vedere maggiori dettagli qui e come disattivare questa funzione: http://discussions.apple.com/thread.jspa?threadID=1751896
versioni future di PSFramework interpreterà anche queste intestazioni, restate sintonizzati.
Vedere questa funzione, fa proprio questo. Legge solo 30 byte del file PNG e restituisce la dimensione (CGSize). Questa funzione fa parte di un framework per l'elaborazione di immagini chiamate PSFramework (http://sourceforge.net/projects/photoshopframew/). Non ancora implementato per altri formati di immagine, gli sviluppatori sono i benvenuti.Il progetto è Open Source sotto la licenza 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);
}
fonte
2010-01-05 13:29:47
CGImageSource è l'API perfetta per questo, ma fastidiosamente non è disponibile su iPhone. Probabilmente dovrai implementarlo da solo. Detto questo, tieni presente che UIImage eliminerà i suoi dati se usi + imageWithContentsOfFile: che dovrebbe rimuovere i tuoi dubbi sull'uso della memoria. –