-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
NSImage
: Added write(to:options:type:jpegCompressionFactor:)
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// | ||
// NSImage.swift | ||
// OTCore • https://github.com/orchetect/OTCore | ||
// © 2023 Steffan Andrews • Licensed under MIT License | ||
// | ||
|
||
#if os(macOS) | ||
|
||
import AppKit | ||
|
||
extension NSImage { | ||
/// Compress image and write image file to disk. | ||
/// | ||
/// - Parameters: | ||
/// - url: The location to write the data into.. | ||
/// - options: Options for writing the data. | ||
/// - type: Image file type. | ||
/// - jpegCompressionFactor: Compression factor for JPEG images only. (`0.0 ... 1.0`) | ||
/// Values outside this range will be clamped to the valid value range. | ||
@_disfavoredOverload | ||
public func write( | ||
to url: URL, | ||
options: Data.WritingOptions = [], | ||
type: NSBitmapImageRep.FileType, | ||
jpegCompressionFactor compressionFactor: Double? = 0.85 | ||
) throws { | ||
var properties: [NSBitmapImageRep.PropertyKey: Any] = [:] | ||
properties[.compressionFactor] = compressionFactor?.clamped(to: 0.0 ... 1.0) as NSNumber? | ||
|
||
guard | ||
let imageData = tiffRepresentation, | ||
let imageRep = NSBitmapImageRep(data: imageData), | ||
let fileData = imageRep.representation(using: type, properties: properties) | ||
else { | ||
throw CocoaError(.fileWriteUnknown) | ||
} | ||
|
||
try fileData.write(to: url, options: options) | ||
} | ||
} | ||
|
||
#endif |