簡體   English   中英

iOS使用名稱保存圖像

[英]IOS Save image with name

我有一個需要拍照的應用程序,並將其與其他圖像合並。 我希望能夠顯示在應用程序(僅我的應用程序)中拍攝的圖像,並在圖庫視圖中顯示它們。 我遇到的問題是為圖像分配名稱。

我嘗試了多種方法

第一次嘗試

UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)

這保存了圖像,但我不知道如何獲取它

第二次嘗試

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

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

與第一次嘗試相同的問題

第三次嘗試

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)

這似乎是最有希望的,但是該文件確實可以自動保存

我在這里查看了各種答案,但仍然無法找到解決方案

將斜杠添加為imageName字符串的第一個字符,如下所示:

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

否則,路徑為“ .... / Documentsmyimagename”,但路徑應為“ .... / Documents / myimagename”,即,沒有其他斜杠,圖像將保存到“文檔”上方的文件夾中

我還建議不要在文件名中使用冒號字符,在Mac上不允許使用冒號並將其自動替換。

這是我在新的XCode項目中測試過的代碼,並且對我有用(我在項目的根文件夾中放入了“ myimage.png”文件):

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))
    }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM