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.
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
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!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With