【问题标题】:Image to UInt8 Conversion Swift Distorts Image图像到 UInt8 转换 Swift 扭曲图像
【发布时间】:2016-07-25 16:57:13
【问题描述】:

这是this thread 的延续。我的第一个问题得到了回答,所以我认为继续评论和扩展问题是不礼貌的。

使用下面的代码,我将 RGBA 图像转换为整数数组。但是,当我转换回图像时,数据很奇怪。 我的反向转换过程不是问题,因为当我在创建时调试像素阵列时,像素与原始图像不匹配:它们与扭曲的图像匹配。

我想知道这些问题的根源是什么。

代码:

   init?(fromImage image: UIImage!) {
    let imageRef = image!.CGImage
    self.width = CGImageGetWidth(imageRef)
    self.height = CGImageGetHeight(imageRef)
    let colorspace = CGColorSpaceCreateDeviceRGB()
    let bytesPerRow = (4 * width);
    let bitsPerComponent :UInt = 8
    let pixels = UnsafeMutablePointer<UInt8>(malloc(width*height*4))


    var context = CGBitmapContextCreate(pixels, width, height, Int(bitsPerComponent), bytesPerRow, colorspace, CGImageAlphaInfo.PremultipliedLast.rawValue);

    CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)

    for row in 0 ..< height {
        for col in 0 ..< width {
            let offset = 4 * (width * row) + col
            print("\(pixels[offset]) ", terminator:"")
            print("\(pixels[offset + 1]) ", terminator:"")
            print("\(pixels[offset + 2]) ", terminator:"")
            print("\(pixels[offset + 3]) ", terminator:"")
            print(" | ", terminator:"")
        }
        print(" ")
    }
}

任何帮助!再次感谢。

【问题讨论】:

    标签: ios arrays swift image int


    【解决方案1】:

    你的偏移逻辑有点缺陷

    let offset = 4 * (width * row) + col
    

    rowcol 为 0 时,偏移量为 0 - 没关系。

    row 为 0 且 col 为 1 时,偏移量为 1 - 这不好,我们只是与前一个像素发生碰撞。

    解决方法就是添加括号:

    let offset = 4 * ((width * row) + col)
    

    现在row 为 0,col 为 1 得到 4 - 这是正确的。


    虽然,除非您特别需要处理像素位置 - 我通常更喜欢在一个循环中循环遍历像素数据。例如:

    for i in 0 ..< width*height {
        let offset = 4 * i
        print("\(pixels[offset]) ", terminator:"")
        print("\(pixels[offset + 1]) ", terminator:"")
        print("\(pixels[offset + 2]) ", terminator:"")
        print("\(pixels[offset + 3]) ", terminator:"")
        print(" | ", terminator:"")
        print(" ")
    }
    

    【讨论】:

    • 哇。做得好。极好的。我觉得很尴尬,我在这个问题上浪费了整个问题。我应该删除它,因为这个问题对我来说太具体了?
    • 嗯...我真的不确定。它肯定在“简单的印刷错误”附近的灰色区域 - 尽管可以提出一个论点,因为这种问题难以捕捉(编译器不会抛出错误并且不会发生运行时异常),它可能很有用对于未来的读者。正如我回答的那样,我可能有点偏向于保持它。我建议至少保持几天,看看社区中的其他人是否觉得它值得接近,然后从那里开始。虽然,如果你真的想删除它 - 我删除我的答案没有问题。
    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2014-08-13
    • 2016-03-18
    • 2016-01-02
    • 2017-02-12
    相关资源
    最近更新 更多