【发布时间】:2022-10-23 23:47:05
【问题描述】:
我正在尝试在 UInt8 数组上裁剪图像。这是我尝试过的方法:
func cropImageArray(byteArray: [UInt8], sourceWidth: Int32, bitsPerPixel: Int32, rect: Int32Rect) -> [UInt8] {
var blockSize = bitsPerPixel / 8
var outputPixels = [UInt8]()
for _ in 0..<(rect.width * rect.height * blockSize) {
outputPixels.append(UInt8(0.0))
}
for line in Int32(0) ..< rect.height {
var sourceIndex = (((rect.y + line) * sourceWidth) + rect.x) * blockSize
var destinationIndex = (line * rect.width) * blockSize
for i in Int32(0) ..< Int32(rect.width * blockSize) {
outputPixels[Int(destinationIndex + i)] = byteArray[Int(sourceIndex + i)]
}
}
return outputPixels
}
它不能正常工作。它给出了破碎的图像。你有想法吗?
编辑:这是我获取字节数组的方式。
let img: UIImage! = UIImage(named: "example")
let d: Data! = img.pngData()
let ptr = UnsafeMutablePointer<UInt8>.allocate(capacity: d.count)
d.withUnsafeBytes { (buff) -> Void in
ptr.initialize(from: buff.bindMemory(to: UInt8.self).baseAddress!, count: d.count)
}
let byteArray = UnsafeMutableBufferPointer(start: ptr, count: d.count).map({$0})
编辑2: 由于性能很高,我用作solution 的功能。
【问题讨论】:
-
您是如何获得
byteArray的? -
我已经编辑了这个问题。
标签: arrays swift image crop uint8array