将图像转换为 NSData 并返回为 nil
Converting image to NSData & back is nil
当我做的时候
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
为零。
为什么会这样?
我认为问题在于您从 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];
}
当我做的时候
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
为零。
为什么会这样?
我认为问题在于您从 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];
}