objective-c - 将 UIImage 转换为 NSData

标签 objective-c ios ipad cocoa-touch nsdata

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

但是,我有一个带有图像的 ImageView 。我在 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"];

最佳答案

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

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 .

编辑:

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

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

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

关于objective-c - 将 UIImage 转换为 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6476929/

相关文章:

ios - 使用 3D Touch Peek & Pop 时以模态方式呈现提交 View Controller 而不是推送

iphone - 为什么我的NSUserDefault值未写入?

ios - setStatusBarHidden 在 UIDocumentInteractionController 呈现 Preview Animated 后停止正常工作

objective-c - 界面生成器自定义 nsview 向父级发送操作

ios - 如何让tableview控件适合整个屏幕

ios - 如何从 Swift 中所有可用语言环境的货币代码中获取货币符号?

iphone - 将 iPad xib 转换为 iPhone xib

iphone - 如何确定 UISearchDisplayController 是否为 searchResults TableView 可见?

iphone - 在 iPhone 上播放生成的音频

Objective-C/Cocoa 等效于 C# ManualResetEvent