简体   繁体   中英

UIImagePNGRepresentation returns nil data?

I am trying to make thumbnail images and save to the document directory. But the problem is that when I am trying to convert the thumbnail images to NSData. It returns nil.

Here is my code,

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

So what is the problem I have also tried with UIImageJPEGRepresentation but it not works for me.

Thanks.

Try this:

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

This creates a copy of the original UIImage. You can then call UIImagePNGRepresentation and it will work correctly.

To Swift programmers, Rickster's answer helped me a lot! UIImageJPEGRepresentation was crashing my app when selecting a certain image. I'm sharing my extension of UIImage (or Category in Objective-C term).

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!
    }
}

Try this code,

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

Hope this Helps you, happy Coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM