相册图片选择器
https://github.com/banchichen/TZImagePickerController
由URL获取图片(异步加载)
SDWebImage用法,只需要提供一个下载的url和占位图,就可以在回调里拿到下载后的图片
- imageview控件使用
#import
[imageview sd_setImageWithURL:[NSURL URLWithString:@"......"] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
imageview.image = image;
NSLog(@"图片加载完成");
}];
// 也可以图片下载完成后,直接显示下载后的图片
[imageview sd_setImageWithURL:[NSURL URLWithString:@"....."]];
- Button控件使用
#import
[self.headBtn sd_setImageWithURL:[NSURL URLWithString:headImgUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"登录2"]];
由URL获取图片(同步加载)
NSString *imgurl = @".....";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgurl]];
UIImage *img3 = [UIImage imageWithData:data];
截屏
-(void)cutScreenPic{
//开启上下文
CGSize imageSize = self.view.bounds.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
//将某个View的所有内容渲染到图形的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
//获得图片
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//保存
[UIImagePNGRepresentation(image) writeToFile:@"/Users/CC/Desktop/imageName.png" atomically:YES];
}
改变图片渲染方式(设置Rander)
img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
压缩图片
/* 压缩图片至 指定像素 */
- (UIImage *)rescaleImageToPX:(CGFloat )toPX{
CGSize size = self.size;
if(size.width <= toPX && size.height <= toPX)
return self; // 图片如果比指定像素小,不需压缩
CGFloat scale = size.width / size.height; //比例
if(size.width > size.height){
size.width = toPX;
size.height = size.width / scale;
}
else{
size.height = toPX;
size.width = size.height * scale;
}
return [self rescaleImageToSize:size];
}
/* 压缩图片至 指定尺寸 */
- (UIImage *)rescaleImageToSize:(CGSize)size
{
CGRect rect = (CGRect){CGPointZero, size};
UIGraphicsBeginImageContext(rect.size);
[self drawInRect:rect];
UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resImage;
}
保存图片到本地
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
多选图片
http://www.jianshu.com/p/6181f32bb844
聊天泡泡尖角图片
http://www.jianshu.com/p/c6c645394b06
比较两个图片是否相等
- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
NSData *data1 = UIImagePNGRepresentation(image1);
NSData *data2 = UIImagePNGRepresentation(image2);
return [data1 isEqual:data2];
}
设置图片圆角、圆形图片
// 封装工具方法
- (UIImage *)cutCircleImage {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 获取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 设置圆形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
图片上传
用AFN3.0进行上传操作
//首先压缩图片
NSData *imageData = UIImageJPEGRepresentation(_imageV.image, 0.1);
- (void)upLoad{
//1. 创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2. 地址、参数,用字典保存。不需要的可以省略。
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:_fireID,@"id",_longitude,@"longitude",_latitude,@"latitude", nil];
NSString *urlString = @“... ...”;//(后台给你url)
//3. post请求
[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id _Nonnull formData) {
// 在网络开发中,上传文件时不允许文件重名,解决方案:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss"; // 设置时间格式
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
/*
此方法参数:
1. 要上传的[二进制数据]
2. imgFile是对应后台给你url里面的图片参数。
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
[formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
// 上传进度
NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败:%@",error);
}];
}
判断图片类型
//封装工具方法。通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"jpeg";
case 0x89:
return @"png";
case 0x47:
return @"gif";
case 0x49:
case 0x4D:
return @"tiff";
case 0x52:
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"])
{
return @"webp";
}
return nil;
}
return nil;
}
//外界调用
//假设这是一个网络获取的URL
NSString *path = @"http://pic.rpgsky.net/images/2016/07/26/3508cde5f0d29243c7d2ecbd6b9a30f1.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
//调用获取图片扩展名
NSString *string = [self contentTypeForImageData:data];
//输出结果为 png
NSLog(@"%@",string);
在图片上绘制文字
//自定义工具方法
- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
{
//画布大小
CGSize size=CGSizeMake(self.size.width,self.size.height);
//创建一个基于位图的上下文
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0
[self drawAtPoint:CGPointMake(0.0,0.0)];
//文字居中显示在画布上
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
//计算文字所占的size,文字居中显示在画布上
CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
CGFloat width = self.size.width;
CGFloat height = self.size.height;
CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
//绘制文字
[title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
//返回绘制的新图形
UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
拉伸图片
例子:QQ会话窗口,气泡的背景图片拉伸
// 自定义工具方法
+ (UIImage *)resizeWithImage:(UIImage *)image{
CGFloat top = image.size.height/2.0;
CGFloat left = image.size.width/2.0;
CGFloat bottom = image.size.height/2.0;
CGFloat right = image.size.width/2.0;
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)resizingMode:UIImageResizingModeStretch];
}
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
//此方法返回返回拉伸后的图像。第二个参数resizingMode是图像拉伸模式:
UIImageResizingModeTile 平铺 、UIImageResizingModeStretch, 拉伸
获得灰度图
+ (UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage
{
int width = sourceImage.size.width;
int height = sourceImage.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return nil;
}
CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
CGImageRef contextRef = CGBitmapContextCreateImage(context);
UIImage *grayImage = [UIImage imageWithCGImage:contextRef];
CGContextRelease(context);
CGImageRelease(contextRef);
return grayImage;
}
由View生成图片
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
// 下面方法:第一个参数 表示区域大小。
第二个参数 表示是否非透明。半透明效果需要传NO,否则传YES。
第三个参数 是屏幕密度 [UIScreen mainScreen].scale。
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
生成纯色图片
- (UIImage *)imageWithColor:(UIColor *)color {
// 描述矩形
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
// 开启位图上下文
UIGraphicsBeginImageContext(rect.size);
// 获取位图上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 使用color演示填充上下文
CGContextSetFillColorWithColor(context, [color CGColor]);
// 渲染上下文
CGContextFillRect(context, rect);
// 从上下文中获取图片
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
// 结束上下文
UIGraphicsEndImageContext();
return theImage;
}
毛玻璃效果
根据bundle中的文件名读取图片
+ (UIImage *)imageWithFileName:(NSString *)name {
NSString *extension = @"png";
NSArray *components = [name componentsSeparatedByString:@"."];
if ([components count] >= 2) {
NSUInteger lastIndex = components.count - 1;
extension = [components objectAtIndex:lastIndex];
name = [name substringToIndex:(name.length-(extension.length+1))];
}
// 如果为Retina屏幕且存在对应图片,则返回Retina图片,否则查找普通图片
if ([UIScreen mainScreen].scale == 2.0) {
name = [name stringByAppendingString:@"@2x"];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
}
}
if ([UIScreen mainScreen].scale == 3.0) {
name = [name stringByAppendingString:@"@3x"];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
}
}
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path) {
return [UIImage imageWithContentsOfFile:path];
}
return nil;
}
保存图片到本地相册
-(void)saveImage:(UIImage *)img{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
});
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if(error != NULL){
[SVProgressHUD showNOmessage:@"保存失败"];
}else{
[SVProgressHUD showYESmessage:@"保存成功"];
}
}
图片合并
//图片合成
+ (UIImage *)imageCombineImage:(UIImage *)useImage maskImage:(UIImage *)maskImage
{
UIGraphicsBeginImageContextWithOptions(useImage.size ,NO, 0.0);
[useImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height)];
//四个参数为水印图片的位置
[maskImage drawInRect:CGRectMake(50, 50, 50, 50)];
//如果要多个位置显示,继续drawInRect就行
//[maskImage drawInRect:CGRectMake(0, useImage.size.height/2, useImage.size.width, useImage.size.height/2)];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
UIImage和Base64格式图片相互转化
/* 方法一 */
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
/* 方法二 */
- (BOOL) imageHasAlpha: (UIImage *) image {
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
return (alpha == kCGImageAlphaFirst ||
alpha == kCGImageAlphaLast ||
alpha == kCGImageAlphaPremultipliedFirst ||
alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image {
NSData *imageData = nil;
NSString *mimeType = nil;
if ([self imageHasAlpha: image]) {
imageData = UIImagePNGRepresentation(image);
mimeType = @"image/png";
} else {
imageData = UIImageJPEGRepresentation(image, 1.0f);
mimeType = @"image/jpeg";
}
return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
[imageData base64EncodedStringWithOptions: 0]];
}
- (UIImage *) dataURL2Image: (NSString *) imgSrc
{
NSURL *url = [NSURL URLWithString: imgSrc];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *image = [UIImage imageWithData: data];
return image;
}
图片处理
https://github.com/lisongrc/UIImage-Categories