菜鸟教程小白 发表于 2022-12-11 19:44:25

ios - Swift 将 UIImage 转换为没有 alpha channel 的 24 位 RGB


                                            <p><p>我想将 UIImage 转换为 24 位 RGB,中间没有 32 位 RGBA 缓冲区。</p>

<p>我试过了,但它不起作用(字节全为零):</p>

<pre><code>public func pixelsRGB() -&gt; ? {

    let size = self.size
    let dataSize = size.width * size.height * 3
    var pixelData = (repeating: 0, count: Int(dataSize))
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let context = CGContext(data: &amp;pixelData,
                            width: Int(size.width),
                            height: Int(size.height),
                            bitsPerComponent: 8,
                            bytesPerRow: 3 * Int(size.width),
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
    guard let cgImage = self.cgImage else {
      return nil
    }
    context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

    return pixelData
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这有点老了,但因为我也很挣扎,所以我认为添加一些我发现的东西会很好。</p>

<p>正如 <a href="https://stackoverflow.com/questions/8704577/is-it-possible-to-make-a-nsbitmapimagerep-with-24-bpp-and-no-alpha-channel" rel="noreferrer noopener nofollow">this SO post</a> 上的回答, Quartz 不支持 24 位 RGB 图像。查看支持的格式 <a href="https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-CJBEAGHH" rel="noreferrer noopener nofollow">here</a> . @matt 也回答了这个问题 <a href="https://stackoverflow.com/questions/54974385/unable-to-get-a-valid-cgcontext-when-using-any-rgb-color-space" rel="noreferrer noopener nofollow">here</a> </p>

<p>我怀疑它未能创建 CGContext 并为 <em>context</em> 返回 nil。然后它永远不会写入上下文,而只会返回您为字节缓冲区初始化的值。 </p>

<p>如果你换行:</p>

<pre><code>bytesPerRow: 3 * Int(size.width),
</code></pre>

<p>到:</p>

<pre><code>bytesPerRow: 4 * Int(size.width), //to accommodate the non-existing alpha channel
</code></pre>

<p>您将获得一个有效的上下文并能够使用它来绘制。有点痛苦,但这就是我解决它的方法。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Swift 将 UIImage 转换为没有 alphachannel 的 24 位 RGB,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48753643/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48753643/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Swift 将 UIImage 转换为没有 alpha channel 的 24 位 RGB