Swift如何修改从移动相机拍摄的图像中的exif信息 [英] Swift how to modify exif info in images taken from mobile camera

查看:258
本文介绍了Swift如何修改从移动相机拍摄的图像中的exif信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用UIImagePickerController在我的iOS应用程序中选择图像,我知道可以通过info [UIImagePickerControllerMediaMetadata]获取exif信息。但是当我通过UIImage将我的图像上传到我的服务器时,大多数exif信息都被条带化了。我想知道是否可以在Http请求中将exif信息添加到我的图像中(之后上传为jpg的图像)。如果没有,我该如何解决这个问题?我想改变Make,Model属性(换句话说,用什么设备来拍这张照片)

I use UIImagePickerController to pick images in my iOS App and I know exif info can be got by info[UIImagePickerControllerMediaMetadata]. But when I upload my image to my server by UIImage, most of exif info has been striped. I wonder whether I can add exif info to my image in Http request(image uploaded as jpg after that). If not, how should I solve this problem? I wanna change Make, Model attributes(in other words, what device was used to take this picture)

以下是我的代码片段:

func Tapped() {
    let myPickerController = UIImagePickerController()

    myPickerController.delegate = self
    myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
    myPickerController.allowsEditing = false
    self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    myImageView.image = image
    UIImageWriteToSavedPhotosAlbum(image!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}

func myImageUploadRequest()
{

    let myUrl = NSURL(string: "http://XXXXXX/Uploadfile")

    let request = NSMutableURLRequest(URL:myUrl!)
    request.HTTPMethod = "POST"

    let param = [
        "userId"    : "7"
    ]

    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

    if(imageData == nil)  { return; }

    request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)



    myActivityIndicator.startAnimating()

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("******* response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("****** response data = \(responseString!)")

        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

        }catch{
            print(error)
        }


        dispatch_async(dispatch_get_main_queue(),{
            self.myActivityIndicator.stopAnimating()
            self.myImageView.image = nil
        })

    }

    task.resume()
}

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "test.jpg"

    let mimetype = "image/jpg"

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.appendData(imageDataKey)
    body.appendString("\r\n")



    body.appendString("--\(boundary)--\r\n")

    return body
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

extension NSMutableData {

func appendString(string: String) {
    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    appendData(data!)
}
}


推荐答案

是的!最后我做了一个修改EXIF信息的技巧。首先,您可以通过UIImageJPEGRepresentation从信息[UIImagePickerControllerMediaMetadata]和没有EXIF的NSData获取EXIF信息。然后,您可以使用修改的EXIF信息创建新的NSDictionary。在此之后,打电话给我的功能在下面,你可以得到图像的NSData与修改EXIF

Yes! Finally I made a trick to modify the EXIF info. At first, you can get EXIF info from info[UIImagePickerControllerMediaMetadata] and NSData without EXIF from picked UIImage by UIImageJPEGRepresentation. Then, you can create a new NSDictionary with modified EXIF info. After that, call my function in the following, you can get image NSData with modified EXIF!

func saveImageWithImageData(data: NSData, properties: NSDictionary, completion: (data: NSData, path: NSURL) -> Void) {

    let imageRef: CGImageSourceRef = CGImageSourceCreateWithData((data as CFDataRef), nil)!
    let uti: CFString = CGImageSourceGetType(imageRef)!
    let dataWithEXIF: NSMutableData = NSMutableData(data: data)
    let destination: CGImageDestinationRef = CGImageDestinationCreateWithData((dataWithEXIF as CFMutableDataRef), uti, 1, nil)!

    CGImageDestinationAddImageFromSource(destination, imageRef, 0, (properties as CFDictionaryRef))
    CGImageDestinationFinalize(destination)

    var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let savePath: String = paths[0].stringByAppendingPathComponent("exif.jpg")

    let manager: NSFileManager = NSFileManager.defaultManager()
    manager.createFileAtPath(savePath, contents: dataWithEXIF, attributes: nil)

    completion(data: dataWithEXIF,path: NSURL(string: savePath)!)

    print("image with EXIF info converting to NSData: Done! Ready to upload! ")

}

这篇关于Swift如何修改从移动相机拍摄的图像中的exif信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆