### Complete ViewController Integration Example (Swift) Source: https://context7.com/tousc/video2livephoto/llms.txt Demonstrates integrating video to LivePhoto conversion within a UIViewController. It copies a bundled video to a writable location and then converts it using the LivePhotoUtil. Requires UIKit. ```swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Copy bundled video to a writable location let tmpPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/origin.mp4" let tmpURL = URL(filePath: tmpPath) // Remove existing file if present try? FileManager.default.removeItem(at: tmpURL) // Copy video from app bundle if let bundleURL = Bundle.main.url(forResource: "origin", withExtension: "mp4") { try? FileManager.default.copyItem(at: bundleURL, to: tmpURL) } // Convert video to LivePhoto LivePhotoUtil.convertVideo(tmpPath) { success, msg in if success { print("Conversion successful!") } else { print("Error: (msg ?? "Unknown error")") } } } } ``` -------------------------------- ### AVAsset Frame Analysis Utilities (Swift) Source: https://context7.com/tousc/video2livephoto/llms.txt Extension methods for analyzing video assets, counting frames, and extracting still image timing and frame images. Requires AVKit framework. ```swift import AVKit let asset = AVURLAsset(url: videoURL) // Count total frames in video (approximate) let approximateFrameCount = asset.countFrames(exact: false) print("Approximate frames: (approximateFrameCount)") // Count exact frames (slower, reads entire video) let exactFrameCount = asset.countFrames(exact: true) print("Exact frames: (exactFrameCount)") // Get the still image time from an existing LivePhoto video if let stillTime = asset.stillImageTime() { print("Still image time: (CMTimeGetSeconds(stillTime)) seconds") } // Create a time range for still image metadata at 20% into video let stillImageRange = asset.makeStillImageTimeRange(percent: 0.2, inFrameCount: exactFrameCount) print("Still image range: (stillImageRange)") // Extract a frame at 50% position if let frameImage = asset.getAssetFrame(percent: 0.5) { // Use frameImage for preview or still image component print("Frame size: (frameImage.size)") } ``` -------------------------------- ### Convert Video to LivePhoto (Objective-C) Source: https://context7.com/tousc/video2livephoto/llms.txt This Objective-C utility class orchestrates the entire conversion pipeline for creating a LivePhoto from a video file and saving it to the photo library. It takes the video file path as input and provides a completion handler to report success or failure. ```objective-c #import "LivePhotoUtil.h" // Convert a video file to LivePhoto and save to photo library NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"input.mp4"]; [LivePhotoUtil convertVideo:videoPath complete:^(BOOL success, NSString *message) { if (success) { NSLog(@"LivePhoto created successfully!"); } else { NSLog(@"Conversion failed: %@", message); } }]; ``` -------------------------------- ### Video Processing for LivePhoto (Swift) Source: https://context7.com/tousc/video2livephoto/llms.txt This Swift class provides essential video manipulation functions required for LivePhoto conversion, including duration adjustment, time-scaling acceleration, resizing, and rotation. It also handles embedding the QuickTime metadata identifiers necessary for LivePhoto compatibility. The functions are chained using completion handlers. ```swift import AVFoundation let converter = Converter4Video(path: outputPath) // Step 1: Adjust video duration to target length (3 seconds) converter.durationVideo(at: inputPath, outputPath: durationPath, targetDuration: 3.0) { success, error in guard success else { print("Duration adjustment failed: (error?.localizedDescription ?? "Unknown error")") return } // Step 2: Accelerate video to LivePhoto duration (550/600 seconds) let livePhotoDuration = CMTimeMake(value: 550, timescale: 600) converter.accelerateVideo(at: durationPath, to: livePhotoDuration, outputPath: acceleratePath) { success, error in guard success else { return } // Step 3: Resize video to LivePhoto dimensions (1080x1920) let livePhotoSize = CGSize(width: 1080, height: 1920) converter.resizeVideo(at: acceleratePath, outputPath: resizePath, outputSize: livePhotoSize) { success, error in guard success else { return } // Step 4: Write final video with LivePhoto metadata let assetIdentifier = UUID().uuidString let metaURL = Bundle.main.url(forResource: "metadata", withExtension: "mov")! converter.write(dest: finalVideoPath, assetIdentifier: assetIdentifier, metaURL: metaURL) { success, error in if success { print("Video processing complete with asset ID: (assetIdentifier)") } } } } } ``` -------------------------------- ### Save LivePhoto to Photo Library (Swift) Source: https://context7.com/tousc/video2livephoto/llms.txt Saves a processed LivePhoto (image and video components) to the device's photo library using PHAssetCreationRequest. Requires Photos framework and user permission. ```swift import Photos let picturePath = "/path/to/livephoto.heic" let videoPath = "/path/to/livephoto.mov" PHPhotoLibrary.shared().performChanges({ let request = PHAssetCreationRequest.forAsset() let photoURL = URL(fileURLWithPath: picturePath) let pairedVideoURL = URL(fileURLWithPath: videoPath) // Add the still image as the photo resource request.addResource(with: .photo, fileURL: photoURL, options: PHAssetResourceCreationOptions()) // Add the video as the paired video resource request.addResource(with: .pairedVideo, fileURL: pairedVideoURL, options: PHAssetResourceCreationOptions()) }) { success, error in DispatchQueue.main.async { if success { print("LivePhoto saved to photo library!") } else { print("Failed to save: (error?.localizedDescription ?? "Unknown error")") } } } ``` -------------------------------- ### HEIC Image Processing for LivePhoto (Swift) Source: https://context7.com/tousc/video2livephoto/llms.txt This Swift class handles the still image component of a LivePhoto, embedding Apple's maker note metadata to link it with its paired video via a shared asset identifier. It extracts a frame from the video to create the HEIC image and writes it to the specified destination. ```swift import UIKit // Extract a frame from video and create the LivePhoto still image let asset = AVURLAsset(url: videoURL) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true generator.requestedTimeToleranceAfter = .zero generator.requestedTimeToleranceBefore = .zero let time = CMTimeMakeWithSeconds(0.5, preferredTimescale: asset.duration.timescale) let cgImage = try generator.copyCGImage(at: time, actualTime: nil) let image = UIImage(cgImage: cgImage) // Create image converter and write HEIC with LivePhoto metadata let imageConverter = Converter4Image(image: image) let assetIdentifier = UUID().uuidString // Must match paired video identifier let imagePath = documentsPath + "/livephoto.heic" imageConverter.write(dest: imagePath, assetIdentifier: assetIdentifier) // Read back the asset identifier to verify if let readIdentifier = imageConverter.read() { print("Embedded asset identifier: (readIdentifier)") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.