Chr*_*ina 170 cocoa-touch objective-c nsdata ipad ios
我在我的应用程序中使用此代码,这将帮助我发送图像.
但是,我有一个带图像的图像视图.我没有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"];
Run Code Online (Sandbox Code Playgroud)
ser*_*gio 286
请尝试以下操作之一,具体取决于您的图像格式:
UIImageJPEGRepresentation
以JPEG格式返回指定图像的数据.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
Run Code Online (Sandbox Code Playgroud)
UIImagePNGRepresentation
以PNG格式返回指定图像的数据
NSData * UIImagePNGRepresentation (
UIImage *image
);
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要访问构成UIImage的原始字节,可以使用以下方法:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
Run Code Online (Sandbox Code Playgroud)
这将为您提供图像RGB像素的低级表示.(CFBridgingRelease如果您不使用ARC,请忽略该位).
Rad*_*dix 161
NSData *imageData = UIImagePNGRepresentation(myImage.image);
Run Code Online (Sandbox Code Playgroud)
For*_*nja 26
如果你在UIImageView中有一个图像,例如"myImageView",你可以执行以下操作:
使用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).
Run Code Online (Sandbox Code Playgroud)
您还可以将此代码放在GCD块中并在另一个线程中执行,在此过程中显示UIActivityIndicatorView ...
//*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*
});
});
Run Code Online (Sandbox Code Playgroud)
Jem*_*igh 24
创建图像的引用....
UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];
Run Code Online (Sandbox Code Playgroud)
在图像视图中显示图像... imagedisplay是imageview的参考:
imagedisplay.image = rainyImage;
Run Code Online (Sandbox Code Playgroud)
NSData通过传递UIImage引用将其转换为浮点值并提供压缩质量:
NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);
Run Code Online (Sandbox Code Playgroud)