【问题标题】:How to convert code objective c to Swift to save image?如何将代码目标 c 转换为 Swift 以保存图像?
【发布时间】:2014-08-09 16:27:50
【问题描述】:

我在其他帖子中看到过这段代码,用于保存图片:

  // Create path.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSUserDomainMask, YES);
 NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

我正在尝试转换为 swift 以使用 avfoundatioin 保存照片,但我不知道在此处输入 NSDocumentDirectory 和 NSUserDomainMask 这个怎么转换?

谢谢!!

【问题讨论】:

    标签: path avfoundation swift nsdocumentdirectory


    【解决方案1】:

    如下:

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
        if paths.count > 0 {
            if let dirPath = paths[0] as? String {
                let readPath = dirPath.stringByAppendingPathComponent("Image.png")
                let image = UIImage(named: readPath)
                let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
                UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
            }
        }
    }
    

    “paths”是一个AnyObject[],所以你必须检查它的元素是否可以转换为String。

    当然,您实际上不会使用“NSDocumentDirectory”作为名称,我只是为了清楚起见。

    Xcode 7.2 更新

    NSSearchPathForDirectoriesInDomains 现在返回[String] 而不是[AnyObject]? 所以使用

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    if let dirPath = paths.first {
        // ...
    }
    

    .stringByAppendingPathComponent 也被弃用的事实在this answer 中得到处理...

    【讨论】:

    • 和其他行?因为对于文件路径,我可以选择:filePaths.stringByAppendingPathComponent("Image.png") 但如何选择索引 0 中的路径??
    • 如果我喜欢保存在我喜欢的路径中?可以用路径写一个字符串吗?
    • 答案已编辑以提供。第一部分(常量)/是/晦涩的。我理解的第二个(作为 AnyObject[] 的演员表)对于新用户来说是不熟悉的,但如果您阅读了所有文档,最后一个有点微不足道...... :(
    • 我还有一个问题,如果我写一个图像,保存在哪里? writePath 是什么? let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 如何查找图片然后保存?
    • 有了这个,应用程序中断.. 怎么可能把我自己喜欢的路径?例如文档/图片??
    【解决方案2】:

    这是我使用的:

        let fileManager = NSFileManager.defaultManager()
        let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
        let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
        let documentsURL = fileManager.URLsForDirectory(nsDocumentDirectory, inDomains: nsUserDomainMask).last
    

    【讨论】:

      【解决方案3】:

      这只是对 Swift 3

      的 @पवन 答案的修改
      import Foundation
      import UIKit
      import ImageIO
      import MobileCoreServices
      
      extension UIImage
      {
          func write(at path:String) -> Bool
          {
              let result = CGImageWriteToFile(image: self.cgImage!, filePath: path)
              return result
          }
      
          private func CGImageWriteToFile(image:CGImage, filePath:String) -> Bool
          {
              let imageURL:CFURL = NSURL(fileURLWithPath: filePath)
              var destination:CGImageDestination? = nil
      
              let ext = (filePath as NSString).pathExtension.lowercased()
              if ext == "jpg" || ext == "jpeg"
              {
                  destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG, 1, nil)
              }
              else if ext == "png" || ext == "pngf"
              {
                  destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePNG, 1, nil)
              }
              else if ext == "tiff" || ext == "tif"
              {
                  destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeTIFF, 1, nil)
              }
              else  if ext == "bmpf" || ext == "bmp"
              {
                  destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeBMP, 1, nil)
              }
      
      
              guard destination != nil else {
                  fatalError("Did not find any matching path extension to store the image")
              }
      
              CGImageDestinationAddImage(destination!, image, nil)
      
              if CGImageDestinationFinalize(destination!)
              {
                  return true
              }
              return false
          }
      }
      

      及用法

      let pickedImage = UIImage()
      let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent("image.tif")
      if pickedImage.write(at: path) == false
      {
          print("failed to write file to disk!")
      }
      

      【讨论】:

        【解决方案4】:

        使用此类别可以将任何图像保存在文档目录中

        import Foundation
        import UIKit
        import ImageIO
        import MobileCoreServices
        
        extension UIImage {
            func writeAtPath(path:String) -> Bool {
        
                let result = CGImageWriteToFile(self.CGImage!, filePath: path)
                return result
            }
        
            private func CGImageWriteToFile(image:CGImageRef, filePath:String) -> Bool {
                let imageURL:CFURLRef = NSURL(fileURLWithPath: filePath)
                var destination:CGImageDestinationRef? = nil
        
                let ext = (filePath as NSString).pathExtension.uppercaseString
        
                if ext == "JPG" || ext == "JPEG" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG, 1, nil)
                } else if ext == "PNG" || ext == "PNGF" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePNG, 1, nil)
                } else if ext == "TIFF" || ext == "TIF" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeTIFF, 1, nil)
                } else if ext == "GIFF" || ext == "GIF" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeGIF, 1, nil)
                } else if ext == "PICT" || ext == "PIC" || ext == "PCT" || ext == "X-PICT" || ext == "X-MACPICT" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePICT, 1, nil)
                } else if ext == "JP2" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG2000, 1, nil)
                } else  if ext == "QTIF" || ext == "QIF" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeQuickTimeImage, 1, nil)
                } else  if ext == "ICNS" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeAppleICNS, 1, nil)
                } else  if ext == "BMPF" || ext == "BMP" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeBMP, 1, nil)
                } else  if ext == "ICO" {
                    destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeICO, 1, nil)
                } else {
                    fatalError("Did not find any matching path extension to store the image")
                }
        
                if (destination == nil) {
                    fatalError("Did not find any matching path extension to store the image")
                    return false
                } else {
                    CGImageDestinationAddImage(destination!, image, nil)
        
                    if CGImageDestinationFinalize(destination!) {
                        return false
                    }
                    return true
                }
            }
        }
        

        //这是在你的应用程序中使用这个类别的方法。

        func testImageWrite() -> Bool {
        
            let img = UIImage(named: "test")
        
            var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
            path = (path as NSString).stringByAppendingPathComponent("Test.png")
        
            let result = img?.writeAtPath(path)
        
            return result!
        }
        

        【讨论】:

          【解决方案5】:

          对于 xCode 8.1、swift 3.0 你可以这样做:

          let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!

          我认为这更简洁。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多