Created
March 8, 2021 20:33
-
-
Save emmanuelkehinde/973de8be2dd2096ed8bd949d4fb78f0c to your computer and use it in GitHub Desktop.
Remove transparency from an image in swift
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
extension UIImage { | |
func trimmed() -> UIImage { | |
let newRect = cropRect() | |
if let imageRef = cgImage?.cropping(to: newRect) { | |
return UIImage(cgImage: imageRef) | |
} | |
return self | |
} | |
private func cropRect() -> CGRect { | |
let cgImage = self.cgImage! | |
let bitmapBytesPerRow = cgImage.width * 4 | |
let bitmapByteCount = bitmapBytesPerRow * cgImage.height | |
let colorSpace = CGColorSpaceCreateDeviceRGB() | |
let bitmapData = malloc(bitmapByteCount) | |
if bitmapData == nil { | |
return CGRect(x: 0, y: 0, width: 0, height: 0) | |
} | |
guard let context = CGContext( | |
data: bitmapData, | |
width: cgImage.width, | |
height: cgImage.height, | |
bitsPerComponent: 8, | |
bytesPerRow: bitmapBytesPerRow, | |
space: colorSpace, | |
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | |
) else { | |
return CGRect(x: 0, y: 0, width: 0, height: 0) | |
} | |
let height = cgImage.height | |
let width = cgImage.width | |
let rect = CGRect(x: 0, y: 0, width: width, height: height) | |
context.clear(rect) | |
context.draw(cgImage, in: rect) | |
guard let data = context.data else { | |
return CGRect(x: 0, y: 0, width: 0, height: 0) | |
} | |
var lowX = width | |
var lowY = height | |
var highX: Int = 0 | |
var highY: Int = 0 | |
// Filter through data and look for non-transparent pixels. | |
for y in 0..<height { | |
for x in 0..<width { | |
let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */ | |
let color = data.load(fromByteOffset: pixelIndex, as: UInt32.self) | |
if color != 0 { // Alpha value is not zero pixel is not transparent. | |
if x < lowX { | |
lowX = x | |
} | |
if x > highX { | |
highX = x | |
} | |
if y < lowY { | |
lowY = y | |
} | |
if y > highY { | |
highY = y | |
} | |
} | |
} | |
} | |
return CGRect(x: lowX, y: lowY, width: highX - lowX, height: highY - lowY) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment