简体   繁体   中英

IOS Save image with name

i have an app that takes a picture and merges it with another image. I want to be able to display al the images taken in the app (and only my app) and display them in a gallery view. the problem I am having is in assigning the image a name.

I have tried a number of different ways

First Attempt

UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)

this saved the image but i do not know how i can retrieve it

Second Attempt

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(newImage)

    }, completionHandler: { (success, error) -> Void in
        if success {
            //image saved to photos library.
            print("image saved")
        }
});

Same Problem as first attempt

Third Attempt

let date :NSDate = NSDate()

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'_'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "GMT")

let imageName = "\(dateFormatter.stringFromDate(date)).jpg"

//var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)
var documentsDirectoryPath = getDocumentsURL().relativePath
documentsDirectoryPath! += imageName

let settingsData: NSData = UIImageJPEGRepresentation(newImage, 1.0)!
settingsData.writeToFile(documentsDirectoryPath!, atomically: true)

This seems to have the most promise but the file does bot save

I have looked at various answers on here but I still cant identify a solution

Add a slash as first character of the imageName string like this:

let imageName = "/\(dateFormatter.stringFromDate(date)).jpg"

otherwise the path would be "..../Documentsmyimagename" but it should be "..../Documents/myimagename" ie without the additional slash the image is saved to the folder above "Documents"

I also recomend not to use the colon character in filenames, on a mac the colon is not allowed and is replaced automatically.

This is the code I tested in a new XCode project and that worked for me (I put a file "myimage.png" in the root folder of the project):

let newImage = UIImage.init(named: "myimage")


        let date :NSDate = NSDate()

        let dateFormatter = NSDateFormatter()
        //dateFormatter.dateFormat = "yyyy-MM-dd'_'HH:mm:ss"
        dateFormatter.dateFormat = "yyyy-MM-dd'_'HH_mm_ss"

        dateFormatter.timeZone = NSTimeZone(name: "GMT")

        let imageName = "/\(dateFormatter.stringFromDate(date)).jpg"
        print(imageName)
        //var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)
        //var documentsDirectoryPath = getDocumentsURL().relativePath
        var documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
        documentsDirectoryPath += imageName
        print(documentsDirectoryPath)

        let settingsData: NSData = UIImageJPEGRepresentation(newImage!, 1.0)!
        settingsData.writeToFile(documentsDirectoryPath, atomically: true)

SWIFT 3 :)

import UIKit

class ShowImageViewController: UIViewController {

@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var tempImageView: UIImageView!

private var lastPoint = CGPoint.zero
private var red: CGFloat = 0.0
private var green: CGFloat = 0.0
private var blue: CGFloat = 0.0
private var brushWidth: CGFloat = 10.0
private var opacity: CGFloat = 1.0
private var swiped = false


override func viewDidLoad() {
    super.viewDidLoad()
    mainImageView.image = captureImages[selectedImageindex]
    tempImageView.frame = getImageRect(for: mainImageView)

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first {
        lastPoint = touch.location(in: tempImageView)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: tempImageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
        drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }

    // Merge tempImageView into mainImageView
    UIGraphicsBeginImageContext(mainImageView.frame.size)
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height), blendMode: .normal, alpha: opacity)
    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    tempImageView.image = nil
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
    UIGraphicsBeginImageContext(mainImageView.frame.size)
    let context = UIGraphicsGetCurrentContext()
    tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height))

    context!.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
    context!.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
    context!.setLineCap(.round)
    context!.setLineWidth(brushWidth)
    context!.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context!.setBlendMode(.normal)

    context!.strokePath()

    tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    tempImageView.alpha = opacity
    UIGraphicsEndImageContext()

}

func getImageRect(for imageView: UIImageView) -> CGRect {
    let resVi =  (imageView.image?.size.width)! / (imageView.image?.size.height)!
    let resPl =     imageView.frame.size.width / imageView.frame.size.height
    if resPl > resVi {
        let imageSize = CGSize(width: CGFloat((imageView.image?.size.width)! * imageView.frame.size.height / (imageView.image?.size.height)!), height: CGFloat(imageView.frame.size.height))
        return CGRect(x: CGFloat((imageView.frame.size.width - imageSize.width) / 2), y: CGFloat((imageView.frame.size.height - imageSize.height) / 2), width: CGFloat(imageSize.width), height: CGFloat(imageSize.height))
    }
    else {
        let imageSize = CGSize(width: CGFloat(imageView.frame.size.width), height: CGFloat((imageView.image?.size.height)! * imageView.frame.size.width / (imageView.image?.size.width)!))
        return CGRect(x: CGFloat((imageView.frame.size.width - imageSize.width) / 2), y: CGFloat((imageView.frame.size.height - imageSize.height) / 2), width: CGFloat(imageSize.width), height: CGFloat(imageSize.height))
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM