将图像转换为灰度会混淆alpha

时间:2016-03-21 05:35:58

标签: bitmap uiimage swift2 alpha

这是我用来将图像转换为灰度的代码。

func convertToGrayScale(image: UIImage) -> UIImage 
{
    let imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
    let colorSpace = CGColorSpaceCreateDeviceGray()
    let width = image.size.width
    let height = image.size.height
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue)
    let context = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue)
    CGContextDrawImage(context, imageRect, image.CGImage)
    let imageRef = CGBitmapContextCreateImage(context)
    let newImage = UIImage(CGImage: imageRef!)
    return newImage
}

结果如下:enter image description here enter image description here

我不想看到黑色背景。我该如何解决?

编辑:我已尝试使用此代码执行此操作,但是现在需要3秒才能加载图片。

func convertToGrayScale(image: UIImage) -> UIImage {

    let cgImage = image.CGImage!

    let beginImage = CIImage(CGImage: cgImage)
    let filter = CIFilter(name: "CIColorControls")!
    filter.setValue(beginImage, forKey: kCIInputImageKey)
    filter.setValue(0, forKey: kCIInputSaturationKey)
    return UIImage(CIImage: filter.outputImage!)
}

1 个答案:

答案 0 :(得分:1)

这个功能解决了我的问题。它不一定会将图像变成灰度,但是我能够将其变为黑色以用于未知的配方,深灰色用于半已知的配方。为已知着色。

func createTintedImageFromImage(originalImage: UIImage, desiredColor: UIColor) -> UIImage {
    let imageSize: CGSize = originalImage.size
    let imageScale: CGFloat = originalImage.scale
    let contextBounds: CGRect = CGRectMake(0, 0, imageSize.width, imageSize.height)

    UIGraphicsBeginImageContextWithOptions(imageSize, false, imageScale)
    UIColor.blackColor().setFill()
    UIRectFill(contextBounds)
    originalImage.drawAtPoint(CGPointZero)
    let imageOverBlack: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    desiredColor.setFill()
    UIRectFill(contextBounds)

    imageOverBlack.drawAtPoint(CGPointZero, blendMode: .Multiply, alpha: 1)
    originalImage.drawAtPoint(CGPointZero, blendMode: .DestinationIn, alpha: 1)

    let finalImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return finalImage
}

enter image description here