将图像转换为NSData&回来是零

时间:2015-07-21 19:13:31

标签: objective-c cocoa-touch uiimageview uiimage nsdata

当我这样做时

UIImage *photo = [UIImage imageNamed:@"sample_thumbnail.png"];
self.thumbnail.image = photo;

我看到缩略图,PNG,很好。当我转换为NSData&回过头来做:

UIImage *photo = [UIImage imageNamed:@"sample_thumbnail.png"];
NSData *data = UIImagePNGRepresentation(photo);
self.photoData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.thumbnail.image = [UIImage imageWithData:[self.photoData dataUsingEncoding:NSUTF8StringEncoding]];

self.photoData是零。

为什么会这样?

1 个答案:

答案 0 :(得分:2)

我认为问题在于您从NSData实例创建图像的方式。试试这个:

UIImage *photo = [UIImage imageNamed:@"sample_thumbnail.png"];
NSData *data = UIImagePNGRepresentation(photo);
UIImage *image = [UIImage imageWithData:data];

<强> __ UPDATE __

以下是this post

的摘录
- (NSString *)imageToNSString:(UIImage *)image
{
    NSData *imageData = UIImagePNGRepresentation(image);

    return [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (UIImage *)stringToUIImage:(NSString *)string
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string
                                                  options:NSDataBase64DecodingIgnoreUnknownCharacters];

    return [UIImage imageWithData:data];
}