将 UIImage 转换为 NSData [英] convert UIImage to NSData
问题描述
我正在我的应用中使用此代码,它将帮助我发送图像.
但是,我有一个带有图像的图像视图.我在 appbundle 中没有文件,但在我身边有图像.如何更改以下代码?谁能告诉我如何将 myimage
转换为 NSData
?
//在邮件中附加图片NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];NSData *myData = [NSData dataWithContentsOfFile:path];[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
根据您的图像格式,尝试以下方法之一:
<块引用>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
);
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).
这篇关于将 UIImage 转换为 NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!