-
-
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.
Extend Bitmap with initializer from UIImage and export to UIImage
- Loading branch information
1 parent
978404d
commit 996a6d9
Showing
1 changed file
with
63 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,63 @@ | ||
import Foundation | ||
|
||
#if canImport(UIKit) | ||
|
||
import UIKit | ||
|
||
extension Bitmap { | ||
|
||
public init?(image: UIImage) { | ||
guard let cgImage = image.cgImage else { return nil } | ||
|
||
// Redraw image for correct pixel format | ||
|
||
let colorSpace = CGColorSpaceCreateDeviceRGB() | ||
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue | ||
| CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue | ||
|
||
let width = Int(image.size.width) | ||
let height = Int(image.size.height) | ||
let size = width * height | ||
let imageData = UnsafeMutablePointer<UInt8>.allocate(capacity: size) | ||
defer { imageData.deallocate() } | ||
|
||
guard let imageContext = CGContext( | ||
data: imageData, | ||
width: width, | ||
height: height, | ||
bitsPerComponent: 8, | ||
bytesPerRow: width * 4, | ||
space: colorSpace, | ||
bitmapInfo: bitmapInfo | ||
) else { return nil } | ||
|
||
imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size)) | ||
let bufferPointer = UnsafeMutableBufferPointer<UInt8>(start: imageData, count: size) | ||
|
||
self.init(width: width, height: height, data: Array(bufferPointer)) | ||
} | ||
|
||
public func uiImage() -> UIImage? { | ||
let colorSpace = CGColorSpaceCreateDeviceRGB() | ||
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue | | ||
CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue | ||
var mutableBacking = backing | ||
return mutableBacking.withUnsafeMutableBufferPointer() { | ||
CGContext( | ||
data: $0.baseAddress, | ||
width: width, | ||
height: height, | ||
bitsPerComponent: 8, | ||
bytesPerRow: width * 4, | ||
space: colorSpace, | ||
bitmapInfo: bitmapInfo, | ||
releaseCallback: nil, | ||
releaseInfo: nil | ||
)? | ||
.makeImage() | ||
.flatMap(UIImage.init(cgImage:)) | ||
} | ||
} | ||
} | ||
|
||
#endif |