[objective-c] convert UIImage to NSData

I am using this code in my app which will help me to send a image.

However, I have an image view with an image. I have no file in appbundle but have the image in my side. How can I change the below code ? Can anyone tell me how can I convert myimage to NSData ?

// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];

This question is related to objective-c ios ipad cocoa-touch nsdata

The answer is


NSData *imageData = UIImagePNGRepresentation(myImage.image);

- (void) imageConvert
{
     UIImage *snapshot = self.myImageView.image;
     [self encodeImageToBase64String:snapshot];
}    


call this method for image convert in base 64 
    -(NSString *)encodeImageToBase64String:(UIImage *)image
    {
        return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    }

Create the reference of image....

UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];

displaying image in image view... imagedisplay is reference of imageview:

imagedisplay.image = rainyImage;

convert it into NSData by passing UIImage reference and provide compression quality in float values:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

Solution in Swift 4

extension UIImage {
    var data : Data? {
      return cgImage?.dataProvider?.data as Data?
    }
}

If you have an image inside a UIImageView , e.g. "myImageView", you can do the following:

Convert your image using UIImageJPEGRepresentation() or UIImagePNGRepresentation() like this:

NSData *data = UIImagePNGRepresentation(myImageView.image);
//or
NSData *data = UIImageJPEGRepresentation(myImageView.image, 0.8);
//The float param (0.8 in this example) is the compression quality 
//expressed as a value from 0.0 to 1.0, where 1.0 represents 
//the least compression (or best quality).

You can also put this code inside a GCD block and execute in another thread, showing an UIActivityIndicatorView during the process ...

//*code to show a loading view here*

dispatch_queue_t myQueue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);

dispatch_async(myQueue, ^{ 

    NSData *data = UIImagePNGRepresentation(myImageView.image);
    //some code....

    dispatch_async( dispatch_get_main_queue(), ^{
        //*code to hide the loading view here*
    });
});

Use if-let block with Data to prevent app crash & safe execution of code, as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3 class. Use Data instead of NSData with Swift 3

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(img)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to ipad

What is correct media query for IPad Pro? iPad Multitasking support requires these orientations How to restrict UITextField to take only numbers in Swift? How to present a modal atop the current view in Swift Presenting a UIAlertController properly on an iPad using iOS 8 Detect current device with UI_USER_INTERFACE_IDIOM() in Swift HTML5 Video tag not working in Safari , iPhone and iPad Install .ipa to iPad with or without iTunes How to hide UINavigationBar 1px bottom line How to fix UITableView separator on iOS 7?

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to nsdata

Convert UIImage to NSData and convert back to UIImage in Swift? Creating NSData from NSString in Swift How to initialise a string from NSData in Swift Convert between UIImage and Base64 string convert UIImage to NSData Convert NSData to String? Convert UTF-8 encoded NSData to NSString How do I convert an NSString value to NSData?