我在目录中有图像。必须得到该图像并转换为base64字符串?

时间:2016-08-11 04:17:57

标签: ios swift swift2

如何从目录中获取图像,然后将其转换为base64string并通过Web服务发送。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

// Gets image from your file directory
UIImage *image = [UIImage imageWithContentsOfFile:@"path/to/your/directory"];
// Converts it to NSData type.
NSData *imageData = UIImageJPEGRepresentation(image, 1);
// Converts it to base64 string.
NSString *encodedString = [imageData base64Encoding];



// Swift 

var image: UIImage = UIImage.imageWithContentsOfFile("path/to/your/directory")!
    // Converts it to NSData type.
var imageData: NSData = UIImageJPEGRepresentation(image, 1)
    // Converts it to base64 string.
var encodedString: String = imageData.base64Encoding()

答案 1 :(得分:0)

我添加了所有三个场景(三个示例完全没有关联) 1.转换图像。 2.从files目录中查找图像 3.在服务器上发布图像

以下是创建base64图像的方法

//Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!

//OR next possibility

//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!

以下是从文件管理器中找到图像的方法

NSString *searchFilename = @"hello.png"; // name of the PDF you are searching for

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];

NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
  if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
    continue;
  }

  NSLog(@"found %@", documentsSubpath);
}

要发送请求,我使用NSMutableURLRequest来处理JSON请求

var request = NSMutableURLRequest(URL: NSURL(string: url))
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

要准备HTTPBody,我必须将图像编码为Base64字符串。这可以通过以下方式完成:

var imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) // encode the image

执行此操作后,我已将编码图像放入相应参数中的Dictionary中。我将它序列化为JSON表示,我将其分配给HTTPBody。

var err: NSError? = nil
var params = ["image":[ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(0), error: &err)!

我使用共享会话对象来创建发送请求的任务。我创建了一个请求模型,我可以将其转换为MutableURLRequest。你可以看到它在这里的样子。

var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request.toMutableURLRequest(), completionHandler: { data, response, error -> Void in
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
    var err: NSError?

    // process the response
})

task.resume() // this is needed to start the task

请求完成后,将执行通过completionHandler传递的块。从那里,我能够评估响应。这就是我能够将手机相机拍摄的图像发送到服务器的方式。