且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 UIImage 转换为 NSData

更新时间:2023-11-29 14:43:16

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

UIImageJPEG 表示

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

NSData * UIImageJPEGRepresentation (UIImage *图像,CGFloat 压缩质量);

UIImagePNG 表示

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

NSData * UIImagePNGRepresentation (用户界面图像 *图像);

这里是文档.

如果你想访问组成 UIImage 的原始字节,你可以使用这种方法:

CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);NSData* 数据 = (id)CFBridgingRelease(CGDataProviderCopyData(provider));const uint8_t* 字节 = [数据字节];

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

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

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

UIImageJPEGRepresentation

Returns the data for the specified image in JPEG format.

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

UIImagePNGRepresentation

Returns the data for the specified image in PNG format

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:

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 CFBridgingRelease bit if you are not using ARC).