IOS 图片水印或者文字

来源:互联网 发布:网络爬虫可以做什么 编辑:程序博客网 时间:2024/05/16 15:32

一般在客户端做图片处理的数量不宜太多,因为受设备性能的限制,如果批量的处理图片,将会带来交互体验性上的一些问题。首先让我们来看看在图片上添加文字的方法、

  1. -(UIImage *)addText:(UIImage *)img text:(NSString *)text1   
  2. {   
  3. //上下文的大小   
  4. int w = img.size.width;   
  5. int h = img.size.height;   
  6. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//创建颜色   
  7. //创建上下文   
  8. CGContextRef context = CGBitmapContextCreate(NULL, w, h, 844 * w, colorSpace, kCGImageAlphaPremultipliedFirst);   
  9. CGContextDrawImage(context, CGRectMake(00, w, h), img.CGImage);//将img绘至context上下文中   
  10. CGContextSetRGBFillColor(context, 0.01.01.01);//设置颜色   
  11. char* text = (charchar *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];   
  12. CGContextSelectFont(context, "Georgia"30, kCGEncodingMacRoman);//设置字体的大小   
  13. CGContextSetTextDrawingMode(context, kCGTextFill);//设置字体绘制方式   
  14. CGContextSetRGBFillColor(context, 255001);//设置字体绘制的颜色   
  15. CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2, text, strlen(text));//设置字体绘制的位置   
  16. //Create image ref from the context   
  17. CGImageRef imageMasked = CGBitmapContextCreateImage(context);//创建CGImage   
  18. CGContextRelease(context);   
  19. CGColorSpaceRelease(colorSpace);   
  20. return [UIImage imageWithCGImage:imageMasked];//获得添加水印后的图片   
  21. }  

在上面的方法中,我们可以看到,我们可以通过将图片和文字绘制到同一个上下文中,并且重新生成图片,所获得图片就是包括图片和文字。

另外在一些项目中我们可能还回用到图片叠加,比如打水印等功能,这种功能相对上面给图片添加文字更容易,只是在上下文中,绘制两张图片,然后重新生成,以达到图片的叠加、代码如下:

  1. -(UIImage *)addImageLogo:(UIImage *)img text:(UIImage *)logo   
  2. {   
  3. //get image width and height   
  4. int w = img.size.width;   
  5. int h = img.size.height;   
  6. int logoWidth = logo.size.width;   
  7. int logoHeight = logo.size.height;   
  8. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();   
  9. //create a graphic context with CGBitmapContextCreate   
  10. CGContextRef context = CGBitmapContextCreate(NULL, w, h, 844 * w, colorSpace, kCGImageAlphaPremultipliedFirst);   
  11. CGContextDrawImage(context, CGRectMake(00, w, h), img.CGImage);   
  12. CGContextDrawImage(context, CGRectMake(w-logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);   
  13. CGImageRef imageMasked = CGBitmapContextCreateImage(context);   
  14. CGContextRelease(context);   
  15. CGColorSpaceRelease(colorSpace);   
  16. return [UIImage imageWithCGImage:imageMasked];   
  17. // CGContextDrawImage(contextRef, CGRectMake(100, 50, 200, 80), [smallImg CGImage]);   
  18. }  

对于图片叠加文字,和图片叠加图片,基本的原理是一样的,创建绘图上下文,然后在上下文中绘制图片或者文字,然后重新生成图片,以达到我们需要的效果。



0 0
原创粉丝点击