【发布时间】:2016-10-20 10:16:47
【问题描述】:
我想知道是否有一种简单的方法可以使用 CoreGraphics 或 CoreImage 和 Swift3 修剪/裁剪图像?
给定顶部的输入图像(带有红色/玫瑰色背景),我们将这些红色像素修剪掉,只留下真实的、有趣的部分?
【问题讨论】:
标签: macos core-graphics swift3 core-image
我想知道是否有一种简单的方法可以使用 CoreGraphics 或 CoreImage 和 Swift3 修剪/裁剪图像?
给定顶部的输入图像(带有红色/玫瑰色背景),我们将这些红色像素修剪掉,只留下真实的、有趣的部分?
【问题讨论】:
标签: macos core-graphics swift3 core-image
我刚刚在这里回答了一个类似问题的一个子集:Iterate over individual pixels of a UIImage with height information
以下是获取顶部和底部唯一像素的方法。
func pixelNotMatchingTopLeftColor(in image: UIImage, first isFirst: Bool) -> CGPoint? {
let width = Int(image.size.width)
let height = Int(image.size.height)
guard width > 1 || height < 1 else {
return nil
}
if let cfData:CFData = image.cgImage?.dataProvider?.data, let pointer = CFDataGetBytePtr(cfData) {
let cornerPixelRed = pointer.pointee
let cornerPixelGreen = pointer.advanced(by: 0).pointee
let cornerPixelBlue = pointer.advanced(by: 1).pointee
let cornerPixelAlpha = pointer.advanced(by: 2).pointee
let bytesPerpixel = 4
let firstPixel = 1 * bytesPerpixel
let lastPixel = width * height * bytesPerpixel - 1 * bytesPerpixel
let range = isFirst ? stride(from: firstPixel, through: lastPixel, by: bytesPerpixel) :
stride(from: lastPixel, through: firstPixel + bytesPerPixel, by: -bytesPerpixel)
for pixelAddress in range {
if pointer.advanced(by: pixelAddress).pointee != cornerPixelRed || //Red
pointer.advanced(by: pixelAddress + 1).pointee != cornerPixelGreen || //Green
pointer.advanced(by: pixelAddress + 2).pointee != cornerPixelBlue || //Blue
pointer.advanced(by: pixelAddress + 3).pointee != cornerPixelAlpha { //Alpha
print(pixelAddress)
return CGPoint(x: (pixelAddress / bytesPerpixel) % width, y: (pixelAddress / bytesPerpixel) / width)
}
}
}
return nil
}
func firstUniquePixel( in image: UIImage) -> CGPoint? {
return pixelNotMatchingTopLeftColor(in: image, first: true)
}
func lastUniquePixel( in image: UIImage) -> CGPoint? {
return pixelNotMatchingTopLeftColor(in: image, first: false)
}
您必须为左右做类似的事情(如果您在计算指针数学时遇到问题,请告诉我)。然后使用 top、left、bottom 和 right 你只需调用 CGImageCreateWithImageInRect。
【讨论】: