2017-02-08 94 views
0

爲什麼當我嘗試使用NSKeyedArchiver對其進行編碼和解碼時,此代碼段中的UIImage不會恢復到其原始狀態?爲什麼不能成功解碼UIImage?

我期待「decodeImage」包含解碼後的圖像,但它只是NULL。

// Any image here seems to repro the issue 
UIImage *image = [UIImage imageNamed:@"soda.jpg"]; 

// This prints YES (1), just a sanity check. 
NSLog(@"Confirms %d", [[UIImage class] conformsToProtocol:@protocol(NSCoding)]); 

NSMutableData *data = [[NSMutableData alloc] init]; 
NSKeyedArchiver *coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 

[coder encodeObject:image forKey:@"image"]; 
[coder finishEncoding]; 

// I would expect this to be large, instead it's < 1kb. 
NSLog(@"Data length is: %zu", (unsigned long)data.length); 

NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 

// This prints YES (1) 
NSLog(@"containsValueForKey returns %d", [decoder containsValueForKey:@"image"]); 

// decodedImage is NULL here, even though containsValueForKey returned YES 
UIImage *decodedImage = [decoder decodeObjectForKey:@"image"]; 

[decoder finishDecoding]; 

在這種情況下,我沒有尋找一種解決方法,例如先將UIImage轉換爲NSData並對其進行編碼。原因是我試圖重現一個不相關的代碼,它使用了類似這樣的代碼,我試圖理解它。

如果我首先通過nsdata返回圖像並返回到uiimage,代碼將按預期工作,爲什麼?

UIImage *originalImage = [UIImage imageNamed:@"soda.jpg"]; 
NSData *imageData = UIImagePNGRepresentation(originalImage); 
UIImage *image = [UIImage imageWithData:imageData]; 
+0

我認爲這個奇怪的事實與使用[UIImage imageNamed:]創建的UIImage沒有像其他UIImages一樣的序列化,也許是因爲它知道圖像來自應用程序包... –

回答

0

我找到了解決辦法。

事實證明,這隻發生在圖像通過[UIImage imageNamed:]加載。如果通過[UIImage imageWithContentsOfFile:]創建UIImage,則問題不會發生。

我相信這一定是ios方面的一個bug。 imageNamed:創建UIImage的方式專門用於捆綁中的圖像。必須進行一些優化,導致NSCoder無法按預期工作,因爲UIImage似乎實際上不包含圖像數據(因爲解碼似乎返回nil,而不是像預期的那樣從包中重新創建UIImage)。

0

入住這

解碼數據圖像:

+(NSData *)decodeBase64ToImage:(NSString *)strEncodeData 
{ 

    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; 
    return data; 
} 

self.btnLicenseFront.image=[UIImage imageWithData:[Themes decodeBase64ToImage:licenseFront]]; 
0

我用你的代碼,並與2個圖像嘗試:

1.正確的圖像文件

的輸出是

> [36133:5889153] Confirms 1 
> [36133:5889153] Data length is: 68267 
> [36133:5889153] containsValueForKey returns 1 
> [36133:5889153] decodedImage is 1879681920 

2.不正確的/損壞的圖像文件

輸出是

> [36130:5888794] Confirms 1 
> [36130:5888794] Data length is: 136 
> [36130:5888794] containsValueForKey returns 1 
> [36130:5888794] decodedImage is 0 

所以看起來像你的源JPG文件已損壞或無效。

+0

我的圖像沒有損壞,我可以在很多其他應用程序中打開它 –