Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
Sunny Shah Avatar asked Jul 03 '13 06:07

Sunny Shah


3 Answers

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.

like image 104
Rickster Avatar answered Nov 18 '22 06:11

Rickster


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

like image 4
Dhruvik Avatar answered Nov 18 '22 08:11

Dhruvik


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!
    }
}
like image 4
Glenn Posadas Avatar answered Nov 18 '22 06:11

Glenn Posadas