将UIImage转换为NSData [英] convert UIImage to NSData

查看:211
本文介绍了将UIImage转换为NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



但是,我有一个图像视图的图像。我没有在appbundle文件,但有我的身边的形象。如何更改以下代码?任何人都可以告诉我如何将 myimage 转换为 NSData

  //将图片附加到电子邮件
NSString * path = [[NSBundle mainBundle] pathForResource:@rainyofType:@jpg];
NSData * myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@image / jpegfileName:@rainy];


解决方案

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



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




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




UIImagePNGRepresentation



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




  NSData * UIImagePNGRepresentation $ b UIImage * image 
);

这是文档



编辑: / p>

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

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

这将给出图像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).

这篇关于将UIImage转换为NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆