2014-08-27 123 views
0

我正在使用opencv開發一個ios應用程序。目前,在我從相機獲取圖像後,我想將此圖像發送到後端服務器。所以我將Mat格式的圖像轉換爲NSString。將std字符串轉換爲nsstring

正如你可以看到下面:

//Convert image from mat format to vector unchar 
    cv::vector<uchar> buff;//buffer for coding 
    cv::vector<int> param = cv::vector<int>(2); 
    param[0]=CV_IMWRITE_JPEG_QUALITY; 
    param[1]=95;//default(95) 0-100 
    cv::imencode(".jpg",image,buff,param); 

    //Convert from vector unchar to string 
    std::string imageString(buff.begin(), buff.end()); 
    NSLog(@"%lu",imageString.size()); 

    //Convert from string to NSString 
    imageData = [NSString stringWithCString:imageString.c_str() encoding:[NSString defaultCStringEncoding]]; 
    NSLog(@"%@",imageData); 
    NSLog(@"%lu",(unsigned long)imageData.length); 

首先,我轉換圖像從墊到unchar載體。然後將此矢量轉換爲名爲imageString的std字符串。最後,將這個std字符串轉換爲NSString imageData。

然而,和imagestring的大小是80804,我認爲應該是正確的。但imageData的大小是4.我不知道這裏會發生什麼。

  • 2014年8月27日15:09:04.094人臉檢測[14540:60B] 80804
  • 2014年8月27日15:09:04.095人臉檢測[14540:60B]ÿ‡
  • 2014-08 -27 15:09:04.097人臉檢測[14540:60B] 4
  • 2014年8月27日15:09:05.438人臉檢測[14540:60B]

下面是代碼:

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:imageData, @"imageData", latitude, @"latitude", longitude, @"longitude", nil]; 
從服務器210

和響應:

2014年8月27日15:09:05.438人臉檢測[14540:60B]使用NSSting因爲它ËÿËâ¡53.28588327-6.21796840

此致

+0

看起來像編碼問題 – Iducool 2014-08-27 14:20:15

+0

是的,但我不知道爲什麼尺寸從std字符串轉換爲nsstring後急劇下降 – Xiang 2014-08-27 14:23:15

+0

如果您想將它發送到服務器,那麼Base64是最可取的。 – Iducool 2014-08-28 05:33:21

回答

1

避免將丟棄不可打印的字符。使用NSData將圖像信息發送到您的服務器。

+0

我嘗試使用NSData的。它的工作原理,但問題是我想將它們發送到服務器,我想將其轉換爲JSON。如你所見:NSDictionary * jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:imageData,@「imageData」,latitude,@「latitude」,longitude,@「longitude」,nil]; NSData * requestData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:nil];我不知道如果我能的NSData轉換成JSON像NSDictionary中有一個關鍵 – Xiang 2014-08-28 12:41:23

+0

正如你可以爲Base64發送圖像數據的意見,一個被提及,因爲這將其轉換爲可打印字符串,但它不是最好的解決辦法。只是不要使用JSON來處理二進制數據 - 它不適用於它。我建議在多部分請求中發送圖像數據。 – 2014-08-31 08:28:44