Created
October 15, 2025 04:02
-
-
Save VishwaiOSDev/2dbebed28a736d65208e2b28bd82e990 to your computer and use it in GitHub Desktop.
Swift to create or generate a thumbnail image from a video url using AVFoundation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import AVFoundation | |
| import UIKit | |
| import SwiftUI | |
| /// Generates a thumbnail (UIImage) from a video URL asynchronously. | |
| func generateThumbnail(for url: URL, at time: Double = 0.0) async -> UIImage? { | |
| let asset = AVURLAsset(url: url) | |
| let generator = AVAssetImageGenerator(asset: asset) | |
| // Ensures the thumbnail has the correct orientation | |
| generator.appliesPreferredTrackTransform = true | |
| // CMTime specifies the time in the video to capture a frame. | |
| // We use a preferred timescale of 600 for high precision. | |
| let timestamp = CMTime(seconds: time, preferredTimescale: 600) | |
| do { | |
| // Use the async 'image(at:)' method to generate the CGImage | |
| let imageRef = try await generator.image(at: timestamp).image | |
| return UIImage(cgImage: imageRef) | |
| } catch { | |
| print("Error generating thumbnail for \(url): \(error)") | |
| return nil | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment