Ios 如何使用CGContext获取像素的RGB值?
我试图通过改变像素来编辑图像 我有以下代码:Ios 如何使用CGContext获取像素的RGB值?,ios,swift,core-graphics,Ios,Swift,Core Graphics,我试图通过改变像素来编辑图像 我有以下代码: let imageRect = CGRectMake(0, 0, self.image.image!.size.width, self.image.image!.size.height) UIGraphicsBeginImageContext(self.image.image!.size) let context = UIGraphicsGetCurrentContext() CGContextSaveGState
let imageRect = CGRectMake(0, 0, self.image.image!.size.width, self.image.image!.size.height)
UIGraphicsBeginImageContext(self.image.image!.size)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextDrawImage(context, imageRect, self.image.image!.CGImage)
for x in 0...Int(self.image.image!.size.width) {
for y in 0...Int(self.image.image!.size.height) {
var red = 0
if y % 2 == 0 {
red = 255
}
CGContextSetRGBFillColor(context, CGFloat(red/255), 0.5, 0.5, 1)
CGContextFillRect(context, CGRectMake(CGFloat(x), CGFloat(y), 1, 1))
}
}
CGContextRestoreGState(context)
self.image.image = UIGraphicsGetImageFromCurrentImageContext()
我循环遍历所有像素并更改每个像素的值,然后将其转换回图像。我想做的是以某种方式获得当前像素的值(在y-for-loop中),并对该数据进行处理。我还没有在互联网上找到关于这个问题的任何信息。好的,我想我有一个解决方案可以在Swift 2中为您提供 下面的UIColor扩展将归功于 因为我需要一张图片来测试这一点,所以我选择了一个切片(50 x 50-左上角) 下面的代码将其转换为:
对此:
这对我来说在操场上很有用-你所要做的就是复制并粘贴到操场上,以查看结果:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
extension CALayer {
func colorOfPoint(point:CGPoint) -> UIColor
{
var pixel:[CUnsignedChar] = [0,0,0,0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace,bitmapInfo.rawValue)
CGContextTranslateCTM(context, -point.x, -point.y)
self.renderInContext(context!)
let red:CGFloat = CGFloat(pixel[0])/255.0
let green:CGFloat = CGFloat(pixel[1])/255.0
let blue:CGFloat = CGFloat(pixel[2])/255.0
let alpha:CGFloat = CGFloat(pixel[3])/255.0
//println("point color - red:\(red) green:\(green) blue:\(blue)")
let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)
return color
}
}
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r,g,b,a)
}
}
//get an image we can work on
var imageFromURL = UIImage(data: NSData(contentsOfURL: NSURL(string:"https://www.gravatar.com/avatar/ba4178644a33a51e928ffd820269347c?s=328&d=identicon&r=PG&f=1")!)!)
//only use a small area of that image - 50 x 50 square
let imageSliceArea = CGRectMake(0, 0, 50, 50);
let imageSlice = CGImageCreateWithImageInRect(imageFromURL?.CGImage, imageSliceArea);
//we'll work on this image
var image = UIImage(CGImage: imageSlice!)
let imageView = UIImageView(image: image)
//test out the extension above on the point (0,0) - returns r 0.541 g 0.78 b 0.227 a 1.0
var pointColor = imageView.layer.colorOfPoint(CGPoint(x: 0, y: 0))
let imageRect = CGRectMake(0, 0, image.size.width, image.size.height)
UIGraphicsBeginImageContext(image.size)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextDrawImage(context, imageRect, image.CGImage)
for x in 0...Int(image.size.width) {
for y in 0...Int(image.size.height) {
var pointColor = imageView.layer.colorOfPoint(CGPoint(x: x, y: y))
//I used my own creativity here - change this to whatever logic you want
if y % 2 == 0 {
CGContextSetRGBFillColor(context, pointColor.components.red , 0.5, 0.5, 1)
}
else {
CGContextSetRGBFillColor(context, 255, 0.5, 0.5, 1)
}
CGContextFillRect(context, CGRectMake(CGFloat(x), CGFloat(y), 1, 1))
}
}
CGContextRestoreGState(context)
image = UIGraphicsGetImageFromCurrentImageContext()
我希望这对你有用。我玩得很开心 在封面下,
UIGraphicsBeginImageContext
创建一个cgbitmapecontext
。您可以使用CGBitmapContextGetData
访问上下文的像素存储。这种方法的问题在于UIGraphicsBeginImageContext
函数选择用于存储像素数据的字节顺序和颜色空间。这些选择(特别是字节顺序)可能会在未来版本的iOS中发生变化(甚至在不同的设备上)
因此,让我们直接使用CGBitmapContextCreate
创建上下文,这样我们就可以确定字节顺序和颜色空间
在我的操场上,我添加了一个名为pic@2x.jpeg
import XCPlayground
import UIKit
let image = UIImage(named: "pic.jpeg")!
XCPCaptureValue("image", value: image)
下面是我们如何创建位图上下文,同时考虑图像比例(您在问题中没有这样做):
接下来,我们调整坐标系以匹配UIGraphicsBeginImageContextWithOptions
的功能,以便能够正确、轻松地绘制图像:
CGContextTranslateCTM(context, 0, CGFloat(rowCount))
CGContextScaleCTM(context, image.scale, -image.scale)
UIGraphicsPushContext(context!)
image.drawAtPoint(CGPointZero)
UIGraphicsPopContext()
请注意,UIImage.drawAtPoint
考虑了image.orientation
CGContextDrawImage
没有
现在,让我们从上下文中获取指向原始像素数据的指针。如果我们定义一个结构来访问每个像素的各个组件,代码就会更清晰:
struct Pixel {
var a: UInt8
var b: UInt8
var g: UInt8
var r: UInt8
}
let pixels = UnsafeMutablePointer<Pixel>(CGBitmapContextGetData(context))
最后,我们从上下文中获得一个新图像:
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!, scale: image.scale, orientation: UIImageOrientation.Up)
XCPCaptureValue("newImage", value: newImage)
结果,在我的游乐场时间表中:
最后,请注意,如果图像很大,逐像素扫描可能会很慢。如果您能找到一种使用Core image或GPUImage执行图像处理的方法,那么速度会快得多。如果做不到这一点,使用Objective-C并手动对其进行矢量化(使用NEON Intrinsic)可能会带来很大的提升。这个答案假设您创建了图像的CGContext。答案的一个重要部分是将行偏移量四舍五入到8的倍数,以确保这适用于任何图像大小,这是我在其他在线解决方案中没有看到的 Swift 5
func colorAt(x: Int, y: Int) -> UIColor {
let capacity = context.width * context.height
let widthMultiple = 8
let rowOffset = ((context.width + widthMultiple - 1) / widthMultiple) * widthMultiple // Round up to multiple of 8
let data: UnsafeMutablePointer<UInt8> = context!.data!.bindMemory(to: UInt8.self, capacity: capacity)
let offset = 4 * ((y * rowOffset) + x)
let red = data[offset+2]
let green = data[offset+1]
let blue = data[offset]
let alpha = data[offset+3]
return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)
}
func colorAt(x:Int,y:Int)->UIColor{
让容量=context.width*context.height
设宽度倍数=8
设rowOffset=((context.width+widthMultiple-1)/widthMultiple)*widthMultiple//四舍五入为8的倍数
let data:UnsafeMutablePointer=context!.data!.bindMemory(to:UInt8.self,capacity:capacity)
设偏移量=4*((y*行偏移量)+x)
设红色=数据[偏移量+2]
设绿色=数据[偏移量+1]
设蓝色=数据[偏移量]
设alpha=数据[偏移量+3]
返回UIColor(红色:CGFloat(红色)/255.0,绿色:CGFloat(绿色)/255.0,蓝色:CGFloat(蓝色)/255.0,alpha:CGFloat(alpha)/255.0)
}
您是否尝试过此方法:相关答案看起来不错IMOdo您的意思是:定义Context时bitmapInfo.rawValue不起作用:layer.bounds.maxX与image.size.width不同,因此它会缩小图片比例,并用黑色填充其余部分我更新了上面的解决方案,使其在游乐场中工作。请让我知道这是否有帮助。为什么当你说要使用20x20正方形时,你输入了50x50。我先是20乘20,但那只是纯绿色=不太有趣。我调整了注释。你有到NEON intrinsics的链接吗?它允许我更改像素数据吗?NEON是一组ARM CPU指令和寄存器,可同时对多个数据单元进行操作。(与Intel x86相当的称为SSE。)您可以使用它们来加快速度。如果可以访问像素数据,则可以使用它们修改像素数据。我的回答显示了如何访问CGBitmapContext
的像素数据。
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!, scale: image.scale, orientation: UIImageOrientation.Up)
XCPCaptureValue("newImage", value: newImage)
func colorAt(x: Int, y: Int) -> UIColor {
let capacity = context.width * context.height
let widthMultiple = 8
let rowOffset = ((context.width + widthMultiple - 1) / widthMultiple) * widthMultiple // Round up to multiple of 8
let data: UnsafeMutablePointer<UInt8> = context!.data!.bindMemory(to: UInt8.self, capacity: capacity)
let offset = 4 * ((y * rowOffset) + x)
let red = data[offset+2]
let green = data[offset+1]
let blue = data[offset]
let alpha = data[offset+3]
return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)
}