2016-03-15 37 views
1

我有一個從Swift保存到MySQL數據庫的Base64字符串。當它回來時,它不顯示圖像。將Base64字符串應用於UIImageView無法在iOS中工作Swift 2

它是如何在db:

LzlqLzRBQVFTa1pKUmdBQkFRQUFTQUJJQUFELzRRQk1SWGhwWmdBQVRVMEFLZ0FBQUFnQUFnRVNBQU1BQUFBQg0KQUFFQUFJZHBBQVFBQUFBQkFBQUFKZ0FBQUFBQUFxQUNBQEZMUlUlJSUUFVVVVVQUZGRkZBQlJSUlFBVVVVVUFGRkZGQUJSUlJRQVVVVVVBRkZGRkFCUlJSUUFVVQ0KVVVBRkZGaWdBcEtXaWdBcEtXaw0Kb0FLS0tLQUNpaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQVNpbG9vQVNpbG9vQVNpaWlnQW9vb29BS0tLS0FDaQ0KaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQUtLS0tB

,這是如何,我試圖接受它,但它不工作:

let partUrl = "data:image/jpg;base64,"; 
let appndd = partUrl.stringByAppendingString(baseStringNew!) 

let urlWeb = appndd 
let requestURL: NSURL = NSURL(string: urlWeb)! 
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) 
let session = NSURLSession.sharedSession() 

let task = session.dataTaskWithRequest(urlRequest) { 
    (data, response, error) -> Void in 

    if error == nil { 
     NSLog("Success!") 

     dispatch_async(dispatch_get_main_queue(), { 

     imageNewView.layer.cornerRadius = 10.0 
     imageNewView.clipsToBounds = true 

     // Adding a border to the image profile 
     imageNewView.layer.borderWidth = 1.0 
     imageNewView.layer.borderColor = UIColor.grayColor().CGColor 
     imageNewView.image = UIImage(data:data!) 

     }) 

    } else { 
     NSLog("Fail") 
    } 

} //end of task 

task.resume() 

這會在UIImageView中顯示空白圖像。我如何讓這個字符串顯示爲圖像?

+0

插入你的字符串中http://codebeautify.org/base64-to-image-converter,沒有顯示了爲圖像。你確定它其實是一個圖像?它從哪裏來的? –

+0

它的一個圖像,我刪除了一些url,使其適合StackOverflow窗口 – MizAkita

+0

您是否嘗試過NSData NSData(base64EncodedString:string,options:[])的base64編碼字符串初始值設定項,然後使用該NSData創建UIImage? –

回答

1

確保您預先將您的數據添加到data:image/png;base64

這裏是一個q &關於這一點,How to display a base64 image within a UIImageView?

+0

這會失敗:let partUrl =「data:image/png; base64,」; 讓appndd = partUrl.stringByAppendingString(baseStringNew!) 讓decodedData = NSData的(base64EncodedString:appndd,選擇:[]) imageNewView.image = UIImage的(數據:decodedData) – MizAkita

0

你可能要檢查你存儲,並從MySQL數據庫中檢索以base64字符串。嘗試使用BLOB數據類型。

然後將base64字符串轉換爲NSData,然後UIImage非常簡單直接。

let rawData = NSData.init(contentsOfURL: NSURL(string: "http://cdn.sstatic.net/stackoverflow/company/img/logos/so/so-logo.png")!)! 
let base64String = rawData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) 
let imageData = NSData(base64EncodedString: base64String, options: .IgnoreUnknownCharacters) 
let image = UIImage(data: imageData!) 
+0

此未能以讓RAWDATA = NSData的.. 。我將我的數據類型轉換爲blob,但仍然沒有運氣。我的字符串看起來像let:partUrl =「data:image/jpg; base64,」; let appndd = partUrl.stringByAppendingString(baseStringNew!) – MizAkita

+0

我想我的困惑是如何構造字符串......現在我的base64拉入像:LzlqLzRBQVFTa1我附加了:data:image/jpg; base64,但似乎並不喜歡你的建議NSURL(字符串:appndd) – MizAkita

+0

沒有需要追加「圖像/ jpg; base64」。另外,你是否將圖像的URL(轉換爲base64字符串)存儲到數據庫中? – megakilo

相關問題