UIImagePNGRepresentation返回零数据?

Sun*_*hah 6 xcode objective-c ios

我正在尝试制作缩略图并保存到文档目录.但问题是,当我试图将缩略图转换为NSData时.它返回零.

这是我的代码,

  UIImage *thumbNailimage=[image thumbnailImage:40 transparentBorder:0.2 cornerRadius:0.2 interpolationQuality:1.0];
NSData *thumbNailimageData = UIImagePNGRepresentation(thumbNailimage);// Returns nil
[thumbNailimageData writeToFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.png"] atomically:NO];
Run Code Online (Sandbox Code Playgroud)

那么我用UIImageJPEGRepresentation尝试过的问题是什么,但它对我不起作用.

谢谢.

Ric*_*ter 17

试试这个:

UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

这将创建原始UIImage的副本.然后你可以打电话UIImagePNGRepresentation,它将正常工作.


Dhr*_*vik 4

试试这个代码,

-(void) createThumbnail
{
   UIImage *originalImage = imgView2.image; // Give your original Image
   CGSize destinationSize = CGSizeMake(25, 25); // Give your Desired thumbnail Size
   UIGraphicsBeginImageContext(destinationSize);
   [originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   NSData *thumbNailimageData = UIImagePNGRepresentation(newImage);
   UIGraphicsEndImageContext();
   [thumbNailimageData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"1.png"] atomically:NO];
}
Run Code Online (Sandbox Code Playgroud)

希望这对您有帮助,祝您编码愉快