我正在研究一个需要将图像上传到我的服务器的项目。我想将我的图像的二进制数据存储到数据库中的BLOB数据类型字段。因此我需要将我的图像转换为二进制格式。这样它可以保存在服务器数据库上。如何在iOS中将图像转换为二进制格式?
那么如何将图像转换为二进制格式?请指教。
我正在研究一个需要将图像上传到我的服务器的项目。我想将我的图像的二进制数据存储到数据库中的BLOB数据类型字段。因此我需要将我的图像转换为二进制格式。这样它可以保存在服务器数据库上。如何在iOS中将图像转换为二进制格式?
那么如何将图像转换为二进制格式?请指教。
您可以使用CoreGraphics
'方法UIImagePNGRepresentation(UIImage *image)
,它返回NSData
并保存它。 如果你想再次将其转换成UIImage
使用[UIimage imageWithData:(NSData *data)]
方法创建它。
演示您的UIImage发送到服务器
- (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) {
// response data of the request
}
[request release];
}
用途:
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//OR
NSData *data = UIImagePNGRepresentation(image);
根据要求。
使用CoreGraphics的方法UIImagePNGRepresentation(UIImage * image),它返回NSData并以这种方式保存。 – Buntylm 2013-05-06 10:33:30
谢谢@BuntyMadan但它不会以二进制格式转换图像。 – 2013-05-06 10:34:39
但您可以将NSData原始数据发送到服务器,然后将其转换为UIImage。 – Buntylm 2013-05-06 10:36:04