FarisAlbalawi / PhotoVideoEditor

Photo and Video Editor like snapchat & instagrams swift 4
108 stars 33 forks source link

The watermark Image Issue #2

Open KiranDhokale8118 opened 5 years ago

KiranDhokale8118 commented 5 years ago

The watermark image not to be added on the video , when downloads the video.Please look at into it urgently.

KiranDhokale8118 commented 5 years ago

Update the Function for Add Watermark Image And Save the Video to Library

// Mark :- save a video photoLibrary func convertVideoAndSaveTophotoLibrary(videoURL: URL) { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let myDocumentPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("temp.mp4").absoluteString _ = NSURL(fileURLWithPath: myDocumentPath) let documentsDirectory2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL let filePath = documentsDirectory2.appendingPathComponent("video.mp4") deleteFile(filePath: filePath as NSURL)

  //Check if the file already exists then remove the previous file
  if FileManager.default.fileExists(atPath: myDocumentPath) {
     do { try FileManager.default.removeItem(atPath: myDocumentPath)
     } catch let error { print(error) }
  }

  // File to composit
  let asset = AVURLAsset(url: videoURL as URL)
  let composition = AVMutableComposition.init()
  composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)

  let clipVideoTrack = asset.tracks(withMediaType: AVMediaType.video)[0]
  // Rotate to potrait
  let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
  let videoTransform:CGAffineTransform = clipVideoTrack.preferredTransform
  //fix orientation
  var videoAssetOrientation_  = UIImage.Orientation.up
  var isVideoAssetPortrait_  = false
  if videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0 {
     videoAssetOrientation_ = UIImage.Orientation.right
     isVideoAssetPortrait_ = true
  }
  if videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0 {
     videoAssetOrientation_ =  UIImage.Orientation.left
     isVideoAssetPortrait_ = true
  }
  if videoTransform.a == 1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == 1.0 {
     videoAssetOrientation_ =  UIImage.Orientation.up
  }
  if videoTransform.a == -1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == -1.0 {
     videoAssetOrientation_ = UIImage.Orientation.down;
  }
  transformer.setTransform(clipVideoTrack.preferredTransform, at: CMTime.zero)
  transformer.setOpacity(0.0, at: asset.duration)
  //adjust the render size if neccessary
  var naturalSize: CGSize
  if(isVideoAssetPortrait_){
     naturalSize = CGSize(width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.width)
  } else {
     naturalSize = clipVideoTrack.naturalSize;
  }
  var renderWidth: CGFloat!
  var renderHeight: CGFloat!
  renderWidth = naturalSize.width
  renderHeight = naturalSize.height
  let parentlayer = CALayer()
  let videoLayer = CALayer()
  let watermarkLayer = CALayer()
  let videoComposition = AVMutableVideoComposition()
  videoComposition.renderSize = CGSize(width: renderWidth, height: renderHeight)
  videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
  videoComposition.renderScale = 1.0
  watermarkLayer.frame = CGRect(x: 0, y: 0, width: renderWidth, height: renderHeight)
  watermarkLayer.contents = self.tempImageView.toImage().cgImage
  watermarkLayer.opacity = 1.0

  parentlayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: naturalSize)
  videoLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: naturalSize)

  parentlayer.addSublayer(videoLayer)
  parentlayer.addSublayer(watermarkLayer)

  // Add watermark to video
  videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayers: [videoLayer], in: parentlayer)

  let instruction = AVMutableVideoCompositionInstruction()
  instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: CMTimeMakeWithSeconds(60, preferredTimescale: 30))

  instruction.layerInstructions = [transformer]
  videoComposition.instructions = [instruction]

  let exporter = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetHighestQuality)
  exporter?.outputFileType = AVFileType.mp4
  exporter?.outputURL = filePath
  exporter?.videoComposition = videoComposition
  self.OutputURL = exporter?.outputURL
  exporter!.exportAsynchronously(completionHandler: {() -> Void in
     if exporter?.status == .completed {
        let outputURL: URL? = exporter?.outputURL
        PHPhotoLibrary.shared().performChanges({
           PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL!)
        }) { saved, error in
           if saved {
              let fetchOptions = PHFetchOptions()
              fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
              let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).lastObject
              PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler: { (avurlAsset, audioMix, dict) in
                 let newObj = avurlAsset as! AVURLAsset
                 print(newObj.url)
                 DispatchQueue.main.async(execute: {
                    print(newObj.url.absoluteString)
                 })
              })
              print (fetchResult!)
           }
        }
     }
  })

}