将UIImage转换为NSData

问题描述 投票:169回答:7

我在我的应用程序中使用此代码,这将帮助我发送图像。

但是,我有一个带图像的图像视图。我没有appbundle文件,但我的身边有图像。如何更改以下代码?任何人都可以告诉我如何将myimage转换为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"];
objective-c ios ipad cocoa-touch nsdata
7个回答
286
投票

请尝试以下操作之一,具体取决于您的图像格式:

UIImageJPEGRepresentation

以JPEG格式返回指定图像的数据。

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

UIImagePNGRepresentation

以PNG格式返回指定图像的数据

NSData * UIImagePNGRepresentation (
   UIImage *image
);

Here the docs

编辑:

如果要访问构成UIImage的原始字节,可以使用以下方法:

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

这将为您提供图像RGB像素的低级表示。 (如果你不使用ARC,则省略CFBridgingRelease位)。


158
投票
NSData *imageData = UIImagePNGRepresentation(myImage.image);

26
投票

如果你在UIImageView中有一个图像,例如“myImageView”,您可以执行以下操作:

使用UIImageJPEGRepresentation()或UIImagePNGRepresentation()转换图像,如下所示:

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

您还可以将此代码放在GCD块中并在另一个线程中执行,在此过程中显示UIActivityIndi​​catorView ...

//*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*
    });
});

24
投票

创建图像的引用....

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

在图像视图中显示图像... imagedisplay是imageview的参考:

imagedisplay.image = rainyImage;

通过传递NSData引用将其转换为UIImage并提供浮点值的压缩质量:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

2
投票

Swift 4中的解决方案

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

1
投票

使用if-let阻止数据以防止应用程序崩溃和安全执行代码,因为函数UIImagePNGRepresentation返回一个可选值。

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

注意:数据是Swift 3类。在Swift 3中使用Data而不是NSData

通用图像操作(如png和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...
     }
}

通过使用扩展名:

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

0
投票
- (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];
    }
© www.soinside.com 2019 - 2024. All rights reserved.