/** 将 png 图片的数据以字节数组的方式存入头文件,将头文件持久化到磁盘系统中~ */
-(void) savePngBytesAsHeaderFile:(NSString*)pngName columns:(int)columns {
// 唯有这种方式取得的 NSData 对象的 length 属性不再为0,有效!!
NSString *filePath = [[NSBundle mainBundle] pathForResource:pngName ofType:@"png"];
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath];
Byte *bytes = (Byte*)[imageData bytes];
NSUInteger length = [imageData length];
NSMutableString *hexStr = [NSMutableStringstring];
NSString *nameModified = [NSString stringWithString:pngName];
// 将图片名称中的 '-' 替换成 '_' ~
nameModified = [nameModifiedstringByReplacingOccurrencesOfString:@"-"withString:@"_"];
[hexStrappendFormat:@"#ifndef MacEncryptTool_%@_PNG_H\n", [nameModifieduppercaseString]];
[hexStrappendFormat:@"#define MacEncryptTool_%@_PNG_H\n\n", [nameModifieduppercaseString]];
[hexStrappendFormat:@"unsigned char %@_png[] = {\n\t", nameModified];
NSString *splitStr = [NSString stringWithString:@", "];
for(int i = 0; i < length; ++ i) {
NSString *itemStr = [NSString stringWithFormat:@"%x", bytes[i]&0xff];// 16进制数
if([itemStr length] == 1) { // 补一位 0 ~
itemStr = [NSStringstringWithFormat:@"0x0%@", itemStr];
} else {
itemStr = [NSStringstringWithFormat:@"0x%@", itemStr];
}
if(i != length-1) {
[hexStr appendFormat:@"%@%@", itemStr, splitStr];
if((i+1)%columns == 0) {
[hexStrappendString:@"\n\t"]; // 换行~
}
} else {
[hexStr appendFormat:@"%@\n", itemStr];
}
}
[hexStrappendFormat:@"};\nunsigned int %@_png_len = %u;\n", nameModified, length];
[hexStr appendString:@"\n#endif"];
NSString *fileName = [NSString stringWithFormat:@"%@.png.h", nameModified];
[hexStrwriteToFile:fileName atomically:NOencoding:NSUTF8StringEncodingerror:nil];
// NSData *fileData = [hexStr dataUsingEncoding:NSUTF8StringEncoding];
// [fileData writeToFile:fileName atomically:NO];
}