Konwertuj UIImage do NSData

Używam tego kodu w mojej aplikacji, który pomoże mi wysłać obraz.

Mam jednak widok obrazu z obrazem. Nie mam pliku w appbundle, ale mam obraz na mojej stronie. Jak Mogę zmienić poniższy kod ? Czy ktoś może mi powiedzieć jak mogę zamienić myimage na 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"];
Author: Super Chafouin, 2011-06-25

7 answers

Wypróbuj jedną z poniższych opcji, w zależności od formatu obrazu:

UIImageJPEGRepresentation

Zwraca dane dla podanego obrazu w FORMACIE JPEG.

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality
);

UIImagePNGRepresentation

Zwraca dane dla podanego obrazu w formacie PNG

NSData * UIImagePNGRepresentation (
   UIImage *image
);

Tutaj dokumenty .

EDIT:

Jeśli chcesz uzyskać dostęp do surowych bajtów tworzących interfejs, możesz użyć tego podejście:

CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];

Dzięki temu uzyskasz niskopoziomową reprezentację pikseli RGB obrazu. (Pomiń bit CFBridgingRelease, Jeśli nie używasz ARC).

 285
Author: sergio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-17 14:51:34
NSData *imageData = UIImagePNGRepresentation(myImage.image);
 157
Author: Radix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-27 06:14:46

Jeśli masz obraz wewnątrz interfejsu , np. "myImageView", możesz wykonać następujące czynności:

Konwertuj obraz za pomocą UIImageJPEGRepresentation() lub UIImagePNGRepresentation () w następujący sposób:

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).

Możesz również umieścić ten kod wewnątrz bloku GCD i wykonać w innym wątku, pokazując Widok interfejsu użytkownika podczas procesu ...

//*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*
    });
});
 25
Author: FormigaNinja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-01 05:12:06

Utwórz odniesienie do obrazu....

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

Wyświetlanie obrazu w widoku obrazu... imagedisplay jest odniesieniem do imageview:

imagedisplay.image = rainyImage;

Przelicz go na {[3] } przekazując referencję UIImage i podaj jakość kompresji w wartościach float:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);
 24
Author: Jemythehigh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-09 14:52:38

Rozwiązanie w Swift 4

extension UIImage {
    var data : Data? {
      return cgImage?.dataProvider?.data as Data?
    }
}
 2
Author: Charlton Provatas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-15 14:53:11

Użyj if-let block z danymi, aby zapobiec awarii aplikacji i bezpiecznemu wykonaniu kodu, ponieważ funkcja UIImagePNGRepresentation zwraca opcjonalną wartość.

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

Uwaga: Dane to klasa Swift 3. Użyj danych zamiast NSData z Swift 3

Ogólne operacje na obrazach (jak png i jpg):

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

Za pomocą rozszerzenia:

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...
     }
}
 1
Author: Krunal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-27 08:50:06
- (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];
    }
 0
Author: jayesh mardiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-10 07:29:29