我正在研究一個需要將圖像上傳到我的服務器的項目。我想將我的圖像的二進制數據存儲到數據庫中的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