是否可以将图像存储为可可中的字符串?

时间:2011-05-28 18:26:34

标签: cocoa image

我想硬编码类文件中图像的二进制数据。当类初始化时,从该数据创建NSImage。将图像存储在资源文件夹中不是一种选择。

这可能吗?如何?

2 个答案:

答案 0 :(得分:4)

使用NSData而不是NSString

NSImage符合NSCoding - 它知道如何存档,以及如何创建/读取其他文件格式的图像表示。

如果您想使用其他图片表示,可以使用CGImage apis创建CGImage,然后可以使用该NSImage创建{{1}}。

答案 1 :(得分:3)

//get the image
NSImage *newImage = [[NSImage alloc] initWithContentsOfFile:@"~/Desktop/testImg.png"];
//convert to BitmapImageRep
NSBitmapImageRep *bitmap = [[newImage representations] objectAtIndex:0];
//convert to NSData
NSData *data = [bitmap representationUsingType: NSPNGFileType properties: nil];
//base64 encode and now I have the string. 
NSString *imageString = [data encodeBase64WithNewlines:NO];
NSLog(@"image %@", imageString);
//No that I have the string, I can hard code it into my source code (paste it in).

//When I want to create an image out of it I just get the imageString and convert it to an image
NSData *revData = [imageString decodeBase64WithNewlines:NO];
newImage = [[NSImage alloc] initWithData:revData];

我在这里使用了2个NSData类别(encodeBase64WithNewlines:NO和decodeBase64WithNewlines:NO)您必须包含libcrypto.dylib才能使用它们。我想我是从Cocoa Dev

复制的
- (NSString *) encodeBase64WithNewlines: (BOOL) encodeWithNewlines
{
// Create a memory buffer which will contain the Base64 encoded string
BIO * mem = BIO_new(BIO_s_mem());

// Push on a Base64 filter so that writing to the buffer encodes the data
BIO * b64 = BIO_new(BIO_f_base64());
if (!encodeWithNewlines)
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
mem = BIO_push(b64, mem);

// Encode all the data
BIO_write(mem, [self bytes], [self length]);
int flushResult = BIO_flush(mem);
if(flushResult != 0){
    //throw some warning?
}

// Create a new string from the data in the memory buffer
char * base64Pointer;
long base64Length = BIO_get_mem_data(mem, &base64Pointer);
NSData * base64data = [NSData dataWithBytesNoCopy:base64Pointer length:base64Length freeWhenDone:NO];
NSString * base64String = [[NSString alloc] initWithData:base64data encoding:NSUTF8StringEncoding];

// Clean up and go home
BIO_free_all(mem);
return [base64String autorelease];
}



- (NSData *)decodeBase64WithNewLines:(BOOL)encodedWithNewlines
{
// Create a memory buffer containing Base64 encoded string data
BIO * mem = BIO_new_mem_buf((void *) [self bytes], [self length]);

// Push a Base64 filter so that reading from the buffer decodes it
BIO * b64 = BIO_new(BIO_f_base64());
if (!encodedWithNewlines)
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
mem = BIO_push(b64, mem);

// Decode into an NSMutableData
NSMutableData * data = [NSMutableData data];
char inbuf[512];
int inlen;
while ((inlen = BIO_read(mem, inbuf, sizeof(inbuf))) > 0)
    [data appendBytes: inbuf length: inlen];

// Clean up and go home
BIO_free_all(mem);
return data;
}