gpt4 book ai didi

ios - 无法获取非方形图像的字节

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:36 24 4
gpt4 key购买 nike

我使用了this post中介绍的方法,为 Swift 修改:

func getRaster() -> [UIColor] {
let result = NSMutableArray()

let img = self.CGImage
let width = CGImageGetWidth(img)
let height = CGImageGetHeight(img)
let colorSpace = CGColorSpaceCreateDeviceRGB()

var rawData = [UInt8](count: width * height * 4, repeatedValue: 0)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bytesPerComponent = 8

let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
let context = CGBitmapContextCreate(&rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo)

CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), img);
for x in 0..<width {
for y in 0..<height {
let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

let red = CGFloat(rawData[byteIndex] ) / 255.0
let green = CGFloat(rawData[byteIndex + 1]) / 255.0
let blue = CGFloat(rawData[byteIndex + 2]) / 255.0
let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0

let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
result.addObject(color)
}
}

return (result as NSArray) as! [UIColor]
}

但问题是,只有当图像是正方形(即 32x32 Sprite )时,它才会成功,每当我尝试获取图像的“光栅”时,其尺寸不相等,我得到一个“索引超出范围"在 x = 16 和 y = 0 上发生 red 的 fatal error (对于大小为 h: 16、w: 32 的图像)。什么可以解决这个问题?

提前致谢!

最佳答案

很容易解决,实际上,这是问题部分:

for x in 0..<width {
for y in 0..<height {
let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

它应该是这样的:

for y in 0..<height {
for x in 0..<width {
let byteIndex = (bytesPerRow * y) + x * bytesPerPixel

我认为这不需要任何进一步的解释。

关于ios - 无法获取非方形图像的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38712781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com