ios 将 UIImage 转换为 NSData

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6476929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:31:01  来源:igfitidea点击:

convert UIImage to NSData

objective-ciosipadcocoa-touchnsdata

提问by Christina

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 myimageto NSData?

但是,我有一个带有图像的图像视图。我在 appbundle 中没有文件,但在我身边有图像。如何更改以下代码?谁能告诉我如何转换myimageNSData

// 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"];

回答by sergio

Try one of the following, depending on your image format:

根据您的图像格式,尝试以下操作之一:

UIImageJPEGRepresentation

Returns the data for the specified image in JPEG format.

UIImageJPEG 表示

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

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

UIImagePNGRepresentation

Returns the data for the specified image in PNG format

UIImagePNG 表示

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

NSData * UIImagePNGRepresentation (
   UIImage *image
);

Here the docs.

这里的文档

EDIT:

编辑:

if you want to access the raw bytes that make up the UIImage, you could use this approach:

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

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

This will give you the low-level representation of the image RGB pixels. (Omit the CFBridgingReleasebit if you are not using ARC).

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

回答by Radix

NSData *imageData = UIImagePNGRepresentation(myImage.image);

回答by FormigaNinja

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

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

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

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

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

您也可以将此代码放在 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*
    });
});

回答by Jemythehigh

Create the reference of image....

创建图像的参考....

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

displaying image in image view... imagedisplayis reference of imageview:

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

imagedisplay.image = rainyImage;

convert it into NSDataby passing UIImagereference and provide compression quality in float values:

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

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

回答by Charlton Provatas

Solution in Swift 4

Swift 4 中的解决方案

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

回答by Krunal

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

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

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

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

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

Generic image operations (like png & jpg both):

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

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

回答by Jayesh Mardiya

- (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];
    }