Ios UIImagePNGRepresentation是否返回零数据?
我正在尝试制作缩略图并保存到文档目录。 但问题是,当我试图将缩略图转换为NSData时。它返回零 这是我的密码Ios UIImagePNGRepresentation是否返回零数据?,ios,objective-c,xcode,Ios,Objective C,Xcode,我正在尝试制作缩略图并保存到文档目录。 但问题是,当我试图将缩略图转换为NSData时。它返回零 这是我的密码 UIImage *thumbNailimage=[image thumbnailImage:40 transparentBorder:0.2 cornerRadius:0.2 interpolationQuality:1.0]; NSData *thumbNailimageData = UIImagePNGRepresentation(thumbNailimage);// Retu
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];
那么,我也尝试过UIImageJPEG表示,但它不适合我,这是什么问题呢
谢谢。试试这段代码
-(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];
}
希望这对你有帮助,
快乐编码试试这个:
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
这将创建原始UIImage的副本。然后您可以调用
UIImagePNGRepresentation
,它将正常工作。对于Swift程序员,Rickster的回答对我帮助很大UIImageJPEGRepresentation在选择特定图像时使我的应用程序崩溃。我正在分享我对UIImage(或Objective-C术语中的类别)的扩展
你是否跟踪了thumbNailimage中的图像…?
thumbNailimage
可能也是nil
尝试使用一个显示thumbNailimage对象的图像视图,并确认该图像是否正确。否,我得到的thumbNailimage对象不是nil。。
import UIKit
extension UIImage {
/**
Creates the UIImageJPEGRepresentation out of an UIImage
@return Data
*/
func generateJPEGRepresentation() -> Data {
let newImage = self.copyOriginalImage()
let newData = UIImageJPEGRepresentation(newImage, 0.75)
return newData!
}
/**
Copies Original Image which fixes the crash for extracting Data from UIImage
@return UIImage
*/
private func copyOriginalImage() -> UIImage {
UIGraphicsBeginImageContext(self.size);
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage!
}
}