UIImagePNGRepresentation返回nil数据?

7

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

以下是我的代码:

  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];

所以问题是,我也尝试使用UIImageJPEGRepresentation,但它对我无效。谢谢。

5
你有追踪到缩略图中的图片吗? - Nitin Gohel
1
thumbNailimage 可能也是 nil - Levi
尝试使用一个ImageView来显示thumbNailimage对象,并确认是否为正确的图像。 - Mrunal
没有,我已经得到了缩略图图像对象,它不是空的。 - Sunny Shah
3个回答

17
请尝试以下方法:
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这将创建原始UIImage的副本。然后,您可以调用 UIImagePNGRepresentation ,它将正常工作。


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];
}

希望这能帮到你,愉快编码。

4
对于Swift程序员来说,Rickster的回答对我帮助很大!在选择某些图片时,UIImageJPEGRepresentation会导致我的应用程序崩溃。我分享了我对UIImage的扩展(或者在Objective-C术语中叫做类别)。
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!
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接