Background
In my company's business flow, we will take photo on user's information, then add wateramrk on the photo. This article will try to show two ways how to add watermark on UIImage.
Immutable Attachment
One condition is just adding some immutable pattern such as info of author and company, or logo on the photos. In this condition, we can initially put that info into a template. When handling a new photo, we can just cover the template on it. Notice that the template has a clear background color.
- (UIImage *)addWatermarkOnImage:(UIImage *)origin withImage:(UIImage *)template {
if (origin == nil || template == nil) return [[UIImage init] alloc];
double width = origin.size.width;
double height = origin.size.height;
UIGraphicsBeginImageContext(CGSizeMake(width, height));
[origin drawInRect:CGRectMake(0.0, 0.0, width, height)];
[template drawInRect:CGRectMake(0.0, 0.0, width, height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Mutable Attachement
Another condition is adding mutable info, for instance, the date, remark, etc. So when adding this type of watermark on new photo, we can print the strings on the photo directly.
- (UIImage*)drawText:(NSString*)text inImage:(UIImage*)image {
if (image == nil) return [[UIImage init] alloc];
UIFont *font = [UIFont boldSystemFontOfSize:40];
CGSize textsize = [text sizeWithFont:font];
CGPoint margin = CGPointMake(20, 20);
// draw text at bottom-right
CGRect textrect = CGRectMake(image.size.width - 0.7 * textsize.width + 0.3 * textsize.width - margin.x,
image.size.height - textsize.height - margin.y,
textsize.width,
textsize.height);
UIGraphicsBeginImageContext(image.size);
// draw image
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
// draw rotated text
[[UIColor lightGrayColor] set];
[text drawWithBasePoint:textrect.origin andAngle:-M_PI_4 andFont:font];
// get new image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Tips
- You may fix the image orientation before adding watermark on it.