Skip to content

Instantly share code, notes, and snippets.

@ptvyas
Last active March 2, 2024 05:45
Show Gist options
  • Save ptvyas/6c72f1f8d41526ba93183d2cec64ca33 to your computer and use it in GitHub Desktop.
Save ptvyas/6c72f1f8d41526ba93183d2cec64ca33 to your computer and use it in GitHub Desktop.
Generate Programatically Image and save on Document directory
/// Generate UIImage and Save in Document Directory
func generateImageAndSave() {
var arrText : [String] = []
//arrText = ([Int](0...100)).map { $0.description } // Numbers list
arrText = (0..<26).map { i in String(UnicodeScalar("A".unicodeScalars.first!.value + i)!) } // ABCD Alphabet list
let imgSize = CGSize(width: 900, height: 1600)
for value in arrText {
guard let image = generateImage(withText: value,
imageSize: imgSize) else { continue }
guard let urlDocDir = urlDocumentDirectory.first else { continue }
let urlImage = urlDocDir.appendingPathComponent(value.description + ".jpeg")
// Convert to Data
guard let data = image.jpegData(compressionQuality: 0) else {
print("Not generate img data")
continue
}
do {
try data.write(to: urlImage)
print("save image | \(value) : \(urlImage)")
} catch {
print("Unable to Write Image Data to DocumentDirectory | Error: \(error.localizedDescription)")
}
}
}
/// Getting UIImage with Specific Size, Background color and Text
func generateImage(withText: String?,
imageSize: CGSize,
bgColor: UIColor? = UIColor.random()) -> UIImage? {
let frame = CGRect(origin: .zero, size: imageSize)
let nameLabel = UILabel(frame: frame)
nameLabel.textAlignment = .center
nameLabel.backgroundColor = bgColor
nameLabel.textColor = .black
nameLabel.font = UIFont.boldSystemFont(ofSize: (imageSize.width/2))
nameLabel.text = withText
UIGraphicsBeginImageContext(frame.size)
guard let currentContext = UIGraphicsGetCurrentContext() else { return nil }
nameLabel.layer.render(in: currentContext)
let nameImage = UIGraphicsGetImageFromCurrentImageContext()
return nameImage
}
/// Getting Document Directory URLs
let urlDocumentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
/// Generate Random UI Color
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0
)
}
}
/// Generate Random CGFloat Value
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment