快速合并两个不同的图像

时间:2015-08-13 19:19:19

标签: ios image swift merge

我面临以下问题:由于合并,我必须合并两个图像A和B以创建新图像C. 第一张图像(A)是一个.png,它是我拍摄的第二张图片(B)。如何将这两个图像合并为一个新的(C),其大小与第一个(A)相同?

我试过这段代码:

var bottomImage: UIImage = polaroidFoto.image!
var image: UIImage = immaginePropria.image!
var newSize: CGSize = CGSizeMake(300, 300)
UIGraphicsBeginImageContext(newSize)
bottomImage.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height), blendMode: kCGBlendModeNormal, alpha: 0.8) //0.8 default
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

但是这个给我一个新的图像(C),但是对它有alpha效果,我希望图像(A)保持在图像上(B)并将这两个合并为一个新的(C)!谢谢!

更新 有人可以尝试更正此代码:

func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {
var colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
var maskImageRef: CGImageRef = maskImage.CGImage()
var mainViewContentContext: CGContextRef = CGBitmapContextCreate(Nil, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst)
CGColorSpaceRelease(colorSpace)
if mainViewContentContext == nil {
    return nil
}
var ratio: CGFloat = 0
ratio = maskImage.size.width / image.size.width
if ratio * image.size.height < maskImage.size.height {
    ratio = maskImage.size.height / image.size.height
}
var rect1: CGRect = 00maskImage.size.widthmaskImage.size.height
var rect2: CGRect = -((image.size.width * ratio) - maskImage.size.width) / 2-((image.size.height * ratio) - maskImage.size.height) / 2image.size.width * ratioimage.size.height * ratio
CGContextClipToMask(mainViewContentContext, rect1, maskImageRef)
CGContextDrawImage(mainViewContentContext, rect2, image.CGImage)
var newImage: CGImageRef = CGBitmapContextCreateImage(mainViewContentContext)
CGContextRelease(mainViewContentContext)
var theImage: UIImage = UIImage.imageWithCGImage(newImage)
CGImageRelease(newImage)
return theImage }

这个可能有用,但语法充满了错误!谢谢!

1 个答案:

答案 0 :(得分:2)

请尝试使用以下代码来帮助您。

 func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

    let maskRef = maskImage.CGImage

    let mask = CGImageMaskCreate(
        CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef),
        nil,
        false)

    let masked = CGImageCreateWithMask(image.CGImage, mask)
    let maskedImage = UIImage(CGImage: masked)!

    // No need to release. Core Foundation objects are automatically memory managed.

    return maskedImage

}

然后按照以下方式拨打电话:

var imageA : UIImage = UIImage(named:"YourImageName")!
var imageB : UIImage = UIImage(named:"YourImageName")!

var maskedImage: UIImage = self.maskImage(imageA, withMask: imageB)