如何在iOS中将图像转换为二进制格式? [英] How to convert image into binary format in iOS?

查看:164
本文介绍了如何在iOS中将图像转换为二进制格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个项目,我需要将图像上传到我的服务器。我想将我的图像的二进制数据存储到数据库中的BLOB数据类型字段。因此,我需要将我的图像转换为二进制格式。这样它就可以保存在服务器数据库中。

I am working on a project where I need to upload image to my server. I want to store my image's binary data to BLOB data type field in database. Therefore I need to convert my image into binary format. So that it can be saved on servers database.

那么如何将图像转换为二进制格式?请指教。

So How to convert an image into binary format? Please advise.

推荐答案

您可以使用 CoreGraphics '方法 UIImagePNGRepresentation(UIImage * image),返回 NSData 并保存。
如果你想再转换成 UIImage 使用创建它[UIimage imageWithData:(NSData * data)] 方法。

You can use the CoreGraphics' method UIImagePNGRepresentation(UIImage *image), which returns NSData and save it. and if you want to convert it into again UIImage create it using [UIimage imageWithData:(NSData *data)] method.

演示将UIImage发送到服务器

Demo to send your UIImage to Server

- (void)sendImageToServer {
       UIImage *yourImage= [UIImage imageNamed:@"image.png"];
       NSData *imageData = UIImagePNGRepresentation(yourImage);
       NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]];

       // Init the URLRequest
       NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
       [request setHTTPMethod:@"POST"];
       [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
       [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
       [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
       [request setHTTPBody:imageData];

       NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
       if (connection) {
       }
       [request release];
 }

这篇关于如何在iOS中将图像转换为二进制格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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