使用 CGImage 将 UIImage 中的所有白色/接近白色的像素替换为 alpha?
我有一个白色背景的 UIImage。我想用 alpha 透明像素替换白色背景/像素。我查看了 StackOverflow 上的其他问题以及 Quartz 文档,但尚未找到解决此问题的连贯“开始到结束”。这是怎么做到的?
I have a UIImage with white background. I would like replace the white background/pixels with alpha-transparent pixels. I've looked at other questions on StackOverflow, along with Quartz documentation, but have yet to find a coherent "start-to-end" for this problem. How is this done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UIImage 包装了 CGImage。获取 CGImage,通过 CGImageCreateWithMaskingColors 运行它,然后从结果创建一个新的 UIImage 或将结果分配回 UIImage。
A UIImage wraps a CGImage. Take the CGImage, run it through CGImageCreateWithMaskingColors, then either create a new UIImage from the result or assign the result back to the UIImage.
第一步是您需要定义某种“距离”函数来确定像素距离白色有多远。然后,您需要定义一个距离阈值,低于该阈值的像素将被视为白色。然后,您需要迭代图像的像素,根据距离和阈值将任何被视为白色的像素更改为透明。不过,主要的技巧是提高效率……通过函数触摸像素会非常慢;最好的选择是通过访问像素所在的内存缓冲区并逐步遍历它们来直接触摸像素。
The first step is you need to define some sort of "distance" function to determine how far away a pixel is from being white. Then you need to define a distance threshold below which a pixel is considered white. Then you would need to iterate over the pixels of the image, changing any pixels that were considered white according to your distance and threshold, to being transparent. The main trick, though, is making this efficient... touching pixels through functions will be very slow; your best bet is to touch the pixels directl by gaining access to the memory buffer in which the pixels reside and stepping through them.