【问题标题】:Convert UIImage to Base64 in swift 2.3在 swift 2.3 中将 UIImage 转换为 Base64
【发布时间】:2016-12-09 15:14:35
【问题描述】:

我正在尝试使用 swift 2.3 将 UIImage 转换为 Base64 编码字符串,但编码字符串无法在服务器上发布。

服务器抛出类似“处理异常时抛出异常(ErrorException:iconv():检测到输入字符串中的非法字符)”的错误。

我可以从编码字符串中删除特殊字符或我的源代码中的一些问题吗?因为我在下面提到了我的源代码。

 //*************** Image Picker function ********* //
 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
 {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    self.imageData = UIImageJPEGRepresentation(chosenImage, 0)         
    self.imageString = self.imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
   self.webServiceForShareData()
   dismissViewControllerAnimated(true, completion: nil)
 }//******** Image Picker End **** //



 func webServiceForShareData()
{
 let allowedCharacters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
    allowedCharacters.removeCharactersInString("+/=")


     //****************** Alamofire Request *********** // 
    Alamofire.request(.POST,"URL",parameters:["pic":self.imageString != nil ? (self.imageString!.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters))! :"", "txt" : self.txtTest.text!, "on_twitter" : self.twitterSuccess, "on_facebook" : self.facebookSuccess],headers : ["Authorization":(NSUserDefaults.standardUserDefaults().objectForKey("oneSocialToken") as! String)])
        .responseJSON
        { 
             response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serializatio
            if let JSON: NSDictionary = response.result.value as? NSDictionary
            {
                print(JSON)
            }
       }
 //*************** Alamofire Request End *************** //

 }// *** Function End 

【问题讨论】:

    标签: ios swift laravel uiimage base64


    【解决方案1】:

    来自docs:

    选项
    指定 Base-64 编码数据的选项的掩码。可能的值在 NSDataBase64EncodingOptions 中给出。

    所以你需要用NSDataBase64EncodingOptions().[one_of_the_following_values]替换你的NSDataBase64EncodingOptions():

    NSDataBase64Encoding64CharacterLineLength
    将最大行长度设置为 64 个字符,然后插入行尾。

    NSDataBase64Encoding76CharacterLineLength
    将最大行长度设置为 76 个字符,然后插入行尾。

    NSDataBase64EncodingEndLineWithCarriageReturn
    设置最大行长度时,指定要插入的行结尾应包含回车符。

    NSDataBase64EncodingEndLineWithLineFeed
    设置最大行长时,指定要插入的行结尾应包含换行符。

    来源:Apple docs

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2018-01-09
      • 2016-07-24
      相关资源
      最近更新 更多