How can I add a watermark to an image using this code?

bkSwifty picture bkSwifty · Jan 29, 2016 · Viewed 7.9k times · Source

I know there are several other ways to do this; I don't want to import anything that I don't need to. If someone can help me with his code, that would be great.

Currently, it is only saving the original image without the watermark image.

extension UIImage {

    class func imageWithWatermark(image1: UIImageView, image2: UIImageView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(image1.bounds.size, false, 0.0)
        image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

func addWatermark() {
    let newImage = UIImage.imageWithWatermark(imageView, image2: watermarkImageView)
    UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
}

EDIT: I've got the watermark appearing on the saved images.

I had to switch the order of the layers:

 image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
 image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)

HOWEVER, it is not appearing in the correct place.It seems to always appear in the center of the image.

Answer

mrkbxt picture mrkbxt · Jan 29, 2016

If you grab the UIImageViews' images you could use the following concept:

if let img = UIImage(named: "image.png"), img2 = UIImage(named: "watermark.png") {

    let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)

    UIGraphicsBeginImageContextWithOptions(img.size, true, 0)
    let context = UIGraphicsGetCurrentContext()

    CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
    CGContextFillRect(context, rect)

    img.drawInRect(rect, blendMode: .Normal, alpha: 1)
    img2.drawInRect(CGRectMake(x,y,width,height), blendMode: .Normal, alpha: 1)

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(result, nil, nil, nil)

}