当前位置: 首页 > 编程日记 > 正文

UIImage 各种处理(分类)

 1 @interface UIImage (conversion)
 2  
 3 //压缩图片到宽度1024
 4 + (UIImage *)imageCompressSizeToMin1024Width:(UIImage *)image;
 5  
 6  
 7 //修改图片size
 8 + (UIImage *)image:(UIImage *)image byScalingToSize:(CGSize)targetSize;
 9  
10 //UIColor 转UIImage
11 + (UIImage *)imageWithColor: (UIColor*) color;
12  
13 //图片转换成黑白(type1:灰 type2:橙 type3:蓝 other:不变)
14 + (UIImage *)grayscale:(UIImage*)anImage type:(int)type;
15  
16 //view转图片
17 +(UIImage *)getImageFromView:(UIView *)view;
18  
19 //图片转化成png
20 + (UIImage *)imageToPng:(UIImage *)image;
21  
22 //图片转换成jpg格式
23 + (UIImage *)imageToJpg:(UIImage *)image;
24  
25 //图片正向处理,相册读出来的图片有时候头不朝上
26 + (UIImage *)fixOrientation:(UIImage *)aImage;
27  
28 @end
.h
  1 @implementation UIImage (conversion)
  2 
  3 + (UIImage *)imageCompressSizeToMin1024Width:(UIImage *)image {
  4     CGSize size = CGSizeZero;
  5     if (image.size.width>1024) {
  6         size.width = 1024;
  7         size.height = image.size.height*1024/image.size.width;
  8         image = [UIImage image:image byScalingToSize:size];
  9     }
 10     return image;
 11 }
 12 
 13 /**
 14  *  修改图片size
 15  *
 16  *  @param image      原图片
 17  *  @param targetSize 要修改的size
 18  *
 19  *  @return 修改后的图片
 20  */
 21 + (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
 22     UIImage *sourceImage = image;
 23     UIImage *newImage = nil;
 24     
 25     UIGraphicsBeginImageContext(targetSize);
 26     
 27     CGRect thumbnailRect = CGRectZero;
 28     thumbnailRect.origin = CGPointZero;
 29     thumbnailRect.size.width  = targetSize.width;
 30     thumbnailRect.size.height = targetSize.height;
 31     
 32     [sourceImage drawInRect:thumbnailRect];
 33     
 34     newImage = UIGraphicsGetImageFromCurrentImageContext();
 35     UIGraphicsEndImageContext();
 36     
 37     return newImage ;
 38 }
 39 
 40 //UIColor 转UIImage
 41 + (UIImage *)imageWithColor: (UIColor*) color
 42 {
 43     CGRect rect=CGRectMake(0,0, 1, 1);
 44     UIGraphicsBeginImageContext(rect.size);
 45     CGContextRef context = UIGraphicsGetCurrentContext();
 46     CGContextSetFillColorWithColor(context, [color CGColor]);
 47     CGContextFillRect(context, rect);
 48     UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
 49     UIGraphicsEndImageContext();
 50     return theImage;
 51 }
 52 
 53 //图片转换成黑白
 54 + (UIImage *)grayscale:(UIImage*)anImage type:(int)type {
 55     //先转换成png
 56     UIImage *pngImage = [UIImage imageToPng:anImage];
 57     
 58     CGImageRef imageRef = pngImage.CGImage;
 59     
 60     size_t width  = CGImageGetWidth(imageRef);
 61     size_t height = CGImageGetHeight(imageRef);
 62     
 63     size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
 64     size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
 65     
 66     size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
 67     
 68     CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
 69     
 70     CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
 71     
 72     
 73     bool shouldInterpolate = CGImageGetShouldInterpolate(imageRef);
 74     
 75     CGColorRenderingIntent intent = CGImageGetRenderingIntent(imageRef);
 76     
 77     CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef);
 78     
 79     CFDataRef data = CGDataProviderCopyData(dataProvider);
 80     
 81     UInt8 *buffer = (UInt8*)CFDataGetBytePtr(data);
 82     
 83     NSUInteger  x, y;
 84     for (y = 0; y < height; y++) {
 85         for (x = 0; x < width; x++) {
 86             UInt8 *tmp;
 87             tmp = buffer + y * bytesPerRow + x * 4;
 88             
 89             UInt8 red,green,blue;
 90             red = *(tmp + 0);
 91             green = *(tmp + 1);
 92             blue = *(tmp + 2);
 93             
 94             UInt8 brightness;
 95             switch (type) {
 96                 case 1:
 97                     brightness = (77 * red + 28 * green + 151 * blue) / 256;
 98                     *(tmp + 0) = brightness;
 99                     *(tmp + 1) = brightness;
100                     *(tmp + 2) = brightness;
101                     break;
102                 case 2:
103                     *(tmp + 0) = red;
104                     *(tmp + 1) = green * 0.7;
105                     *(tmp + 2) = blue * 0.4;
106                     break;
107                 case 3:
108                     *(tmp + 0) = 255 - red;
109                     *(tmp + 1) = 255 - green;
110                     *(tmp + 2) = 255 - blue;
111                     break;
112                 default:
113                     *(tmp + 0) = red;
114                     *(tmp + 1) = green;
115                     *(tmp + 2) = blue;
116                     break;
117             }
118         }
119     }
120     CFDataRef effectedData = CFDataCreate(NULL, buffer, CFDataGetLength(data));
121     CGDataProviderRef effectedDataProvider = CGDataProviderCreateWithCFData(effectedData);
122     CGImageRef effectedCgImage = CGImageCreate(width, height,
123                                                bitsPerComponent, bitsPerPixel, bytesPerRow,
124                                                colorSpace, bitmapInfo, effectedDataProvider,
125                                                NULL, shouldInterpolate, intent);
126     UIImage *effectedImage = [[UIImage alloc] initWithCGImage:effectedCgImage];
127     CGImageRelease(effectedCgImage);
128     CFRelease(effectedDataProvider);
129     CFRelease(effectedData);
130     CFRelease(data);
131     
132     return effectedImage;
133     
134 }
135 
136 //view转图片
137 + (UIImage *)getImageFromView:(UIView *)view{
138     
139     UIGraphicsBeginImageContext(view.bounds.size);
140     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
141     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
142     UIGraphicsEndImageContext();
143     return image;
144 }
145 
146 //图片转换成png格式
147 + (UIImage *)imageToPng:(UIImage *)image {
148     //我们需要将其转换成NSdata二进制存储,
149     NSData *data;
150     if (UIImagePNGRepresentation(image) == nil) {
151         data = UIImageJPEGRepresentation(image, 1);
152     } else {
153         data = UIImagePNGRepresentation(image);
154     }
155     NSFileManager *fileManager = [NSFileManager defaultManager];
156     NSString *sandPath = NSHomeDirectory();
157     //文件路径
158     NSString *path = [sandPath stringByAppendingPathComponent:@"tmp/image.png"];
159     //    DLog(@"%@",path);
160     [fileManager createFileAtPath:path contents:data attributes:nil];   // 将图片保存为PNG格式
161     [data writeToFile:path atomically:YES];
162     UIImage *pngImage = [UIImage imageWithContentsOfFile:path];
163     return pngImage;
164 }
165 
166 //图片转换成jpg格式
167 + (UIImage *)imageToJpg:(UIImage *)image {
168     //我们需要将其转换成NSdata二进制存储,
169     NSData *data;
170     if (UIImagePNGRepresentation(image) == nil) {
171         data = UIImageJPEGRepresentation(image, 1);
172     } else {
173         data = UIImagePNGRepresentation(image);
174     }
175     
176     NSFileManager *fileManager = [NSFileManager defaultManager];
177     NSString *sandPath = NSHomeDirectory();
178     //文件路径
179     NSString *path = [sandPath stringByAppendingPathComponent:@"tmp/image.jpg"];
180     [fileManager createFileAtPath:path contents:data attributes:nil];   // 将图片保存为JPG格式
181     [data writeToFile:path atomically:YES];
182     
183     UIImage *jpgImage = [UIImage imageWithContentsOfFile:path];
184     
185     return jpgImage;
186 }
187 
188 //正向处理
189 + (UIImage *)fixOrientation:(UIImage *)aImage {
190     
191     // No-op if the orientation is already correct
192     if (aImage.imageOrientation ==UIImageOrientationUp)
193         return aImage;
194     
195     // We need to calculate the proper transformation to make the image upright.
196     // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
197     CGAffineTransform transform =CGAffineTransformIdentity;
198     
199     switch (aImage.imageOrientation) {
200         case UIImageOrientationDown:
201         case UIImageOrientationDownMirrored:
202             transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
203             transform = CGAffineTransformRotate(transform, M_PI);
204             break;
205             
206         case UIImageOrientationLeft:
207         case UIImageOrientationLeftMirrored:
208             transform = CGAffineTransformTranslate(transform, aImage.size.width,0);
209             transform = CGAffineTransformRotate(transform, M_PI_2);
210             break;
211             
212         case UIImageOrientationRight:
213         case UIImageOrientationRightMirrored:
214             transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
215             transform = CGAffineTransformRotate(transform, -M_PI_2);
216             break;
217         default:
218             break;
219     }
220     
221     switch (aImage.imageOrientation) {
222         case UIImageOrientationUpMirrored:
223         case UIImageOrientationDownMirrored:
224             transform = CGAffineTransformTranslate(transform, aImage.size.width,0);
225             transform = CGAffineTransformScale(transform, -1, 1);
226             break;
227             
228         case UIImageOrientationLeftMirrored:
229         case UIImageOrientationRightMirrored:
230             transform = CGAffineTransformTranslate(transform, aImage.size.height,0);
231             transform = CGAffineTransformScale(transform, -1, 1);
232             break;
233         default:
234             break;
235     }
236     
237     // Now we draw the underlying CGImage into a new context, applying the transform
238     // calculated above.
239     CGContextRef ctx =CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
240                                             CGImageGetBitsPerComponent(aImage.CGImage),0,
241                                             CGImageGetColorSpace(aImage.CGImage),
242                                             CGImageGetBitmapInfo(aImage.CGImage));
243     CGContextConcatCTM(ctx, transform);
244     switch (aImage.imageOrientation) {
245         case UIImageOrientationLeft:
246         case UIImageOrientationLeftMirrored:
247         case UIImageOrientationRight:
248         case UIImageOrientationRightMirrored:
249             // Grr...
250             CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
251             break;
252             
253         default:
254             CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
255             break;
256     }
257     
258     // And now we just create a new UIImage from the drawing context
259     CGImageRef cgimg =CGBitmapContextCreateImage(ctx);
260     UIImage *img = [UIImage imageWithCGImage:cgimg];
261     CGContextRelease(ctx);
262     CGImageRelease(cgimg);
263     return img;
264 }
265 
266 @end
.m

mark -- 1. 对照片做处理的时候 先旋转方向   再改变格式

2.如果拍设的照片太大的话上传后台估计会出错

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {UIImage *originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];if (!originalImage) {originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];}UIImage *imga = [UIImage fixOrientation:originalImage];//图片正向处理UIImage *img = [UIImage imageToJpg:imga];//转换成jpg
    NSData *imageData = UIImageJPEGRepresentation(img, 1);if  (imageData.length>300000){UIImage *image = [UIImage imageWithData:imageData];imageData = UIImageJPEGRepresentation(image, 0.005);}NSString *encodedImageStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];[picker dismissViewControllerAnimated:YES completion:nil];
}

转载于:https://www.cnblogs.com/xuaninitial/p/6641551.html

相关文章:

Matlab随笔之矩阵入门知识

直接输入法创建矩阵 – 矩阵的所有元素必须放在方括号“[ ]”内&#xff1b; – 矩阵列元素之间必须用逗号“&#xff0c;”或空格隔开&#xff0c;每行必须用“;”隔开 – 矩阵元素可以是任何不含未定义变量的表达式。可以是实数&#xff0c;或者是复数。 – 例a[1,2;3,4] 或 …

[微信小程序]提交表单返回成功后自动清空表单的值

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 实现思路: 给每一个input绑定相同的value对象,提交成功后把这个对象赋值为空. 下面看代码: <form bindsubmitformsubmit><view><span>* </span>公司名称:&l…

xebium周末启动_我如何在周末建立和启动聊天机器人

xebium周末启动by Mike Williams由Mike Williams 我如何在周末建立和启动聊天机器人 (How I Built And Launched A Chatbot Over The Weekend) 在数小时内将您的想法带入功能性bot&#xff0c;获得真实的用户反馈&#xff0c;并在周末结束前启动&#xff01; &#xff1f; (Ta…

transition属性值

一、transition-property: transition-property是用来指定当元素其中一个属性改变时执行transition效果&#xff0c;其主要有以下几个值&#xff1a;none(没有属性改变)&#xff1b;all&#xff08;所有属性改变&#xff09;这个也是其默认值&#xff1b;indent&#xff08;元素…

[微信小程序]下拉菜单

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 动画效果是使用CSS3 keyframes 规则(使 div 元素匀速向下移动) <view class page_row><view class"nav" wx:for{{nav_title}} wx:key"index"><vi…

文件解析库doctotext源码分析

doctotext中没有make install选项&#xff0c;make后生成可执行文件在buile目录下面有.so动态库和头文件&#xff0c;需要的可以从这里面拷贝build/doctotext就是可执行程序。doctotext内置了两种检测文件类型方法&#xff1a;1、以后缀为依据检测文件类型2、以内容为依据检测文…

tmux系统剪切板_实践中的tmux:与系统剪贴板集成

tmux系统剪切板by Alexey Samoshkin通过阿列克谢萨莫什金(Alexey Samoshkin) 在实践中使用tmux&#xff1a;与系统剪贴板集成 (tmux in practice: integration with the system clipboard) 如何在tmux复制缓冲区和系统剪贴板之间建立桥梁&#xff0c;以及如何在OSX或Linux系统…

【Java面试题】54 去掉一个Vector集合中重复的元素

在Java中去掉一个 Vector 集合中重复的元素 1)通过Vector.contains&#xff08;&#xff09;方法判断是否包含该元素&#xff0c;如果没有包含就添加到新的集合当中&#xff0c;适用于数据较小的情况下。 import java.util.Vector; public class DeleteVector {public static v…

tornado+nginx上传视频文件

[http://arloz.me/tornado/2014/06/27/uploadvideotornado.html] [NGINX REFRER: Nginx upload module] 由于tornado通过表达上传的数据最大限制在100M&#xff0c;所以如果需要上传视屏文件的情况在需要通过其他方式实现&#xff0c; 此处采用nginx的nginx-upload-module和jQu…

微信小程序swiper组件宽高自适应方法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 我把 swiper 的 width 设定成了屏幕的95%宽度, 如果想宽度也自适应的话请改成 width:{{width*2}}rpx <swiper classadvertising2 indicator-dots"true" styleheight:{{…

全面访问JavaScript的最佳资源

Looking for a new job is a daunting task. There are so many things to consider when trying to find the perfect role - location, company, job responsibilities, pay and compensation, training and much more.找一份新工作是艰巨的任务。 试图找到理想的职位时&…

Redis集群官方推荐方案 Redis-Cluster

Redis-Cluster redis使用中遇到的瓶颈 我们日常在对于redis的使用中&#xff0c;经常会遇到一些问题 1、高可用问题&#xff0c;如何保证redis的持续高可用性。 2、容量问题&#xff0c;单实例redis内存无法无限扩充&#xff0c;达到32G后就进入了64位世界&#xff0c;性能下降…

[微信小程序]单选框以及多选框实例代码附讲解

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 效果图 <radio-group class"radio-group" bindchange"radioChange"><label class"radio" wx:for"{{k7}}" wx:key"index&q…

IDL_GUI

菜单栏设计 PRO IDLGui;构建界面;显示;添加事件tlbWIDGET_BASE(xsize400,ysize400,/column,mbarmbar);实现基类fileWIDGET_BUTTON(mbar, $ &#xff1b;新建button&#xff0c;value文件)openwidget_button(file,value打开,/menu)jpgwidget_button(open,valuejpg)existwidget_…

git隐藏修改_您可能不知道的有关Git隐藏的有用技巧

git隐藏修改I have launched a newsletter Git Better to help learn new tricks and advanced topics of Git. If you are interested in getting your game better in Git, you should definitely check that out.我已经发布了Git Better通讯&#xff0c;以帮助学习Git的新技…

css 层叠式样式表(2)

一&#xff0c;样式表分类 &#xff08;1&#xff09;内联样式。 --优先级最高&#xff0c;代码重复使用最差。 &#xff08;当特殊的样式需要应用到单独某个元素时&#xff0c;可以使用。 直接在相关的标签中使用样式属性。样式属性可以包含任何 CSS 属性。&#xff09; &…

Hadoop学习笔记之三 数据流向

http://hadoop.apache.org/docs/r1.2.1/api/index.html 最基本的&#xff1a; 1. 文本文件的解析 2. 序列文件的解析 toString会将Byte数组中的内存数据 按照字节间隔以字符的形式显示出来。 文本文件多事利用已有的字符处理类&#xff0c; 序列文件多事创建byte数组&#xff0…

[微信小程序]星级评分和展示(详细注释附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 星级评分分成两种情况: 一:展示后台给的评分数据 二:用户点击第几颗星星就显示为几星评分; <!--pages/test/test.wxml--> <view> <view>一:显示后台给的评分</…

uber_这就是我本可以免费骑Uber的方式

uberby AppSecure通过AppSecure 这就是我本可以免费骑Uber的方式 (Here’s how I could’ve ridden for free with Uber) 摘要 (Summary) This post is about a critical bug on Uber which could have been used by hackers to get unlimited free Uber rides anywhere in th…

磁盘I/O 监控 iostat

iostat -cdxm 2 5 dm-4 如果没有这个命令&#xff0c;需要安装sysstat 包。 Usage: iostat [ options ] [ <interval> [ <count> ] ]Options are:[ -c ] [ -d ] [ -N ] [ -n ] [ -h ] [ -k | -m ] [ -t ] [ -V ] [ -x ] [ -z ][ <device> [...] | ALL ] [ -p…

[微信小程序]物流信息样式加动画效果(源代码附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 效果图片:(信息仅为示例) <!--pages/order/order_wl.wxml--> <view classpage_row top><image classgoods src../../images/dsh.png></image><view cl…

在 Ubuntu 14.04 Chrome中安装Flash Player(转)

在 Ubuntu 14.04 中安装 Pepper Flash Player For Chromium 一个 Pepper Flash Player For Chromium 的安装器已经被 Ubuntu14.04 的官方源收录。Flash Player For Linux 自11.2 起已经停止更新&#xff0c;目前 Linux 平台下面的 Flash Player 只能依靠 Google Chrom 的 PPAPI…

数据结构显示树的所有结点_您需要了解的有关树数据结构的所有信息

数据结构显示树的所有结点When you first learn to code, it’s common to learn arrays as the “main data structure.”第一次学习编码时&#xff0c;通常将数组学习为“主要数据结构”。 Eventually, you will learn about hash tables too. If you are pursuing a Comput…

Unity应用架构设计(9)——构建统一的 Repository

谈到 『Repository』 仓储模式&#xff0c;第一映像就是封装了对数据的访问和持久化。Repository 模式的理念核心是定义了一个规范&#xff0c;即接口『Interface』&#xff0c;在这个规范里面定义了访问以及持久化数据的行为。开发者只要对接口进行特定的实现就可以满足对不同…

PHP连接数据库并创建一个表

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 <html> <body><form action"test.class.php" method"post"> title: <input type"text" name"title"><br> centent: <input t…

MyBatis 入门

什么是 MyBatis &#xff1f; MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手工设置参数以及抽取结果集。MyBatis 使用简单的 XML 或注解来配置和映射基本体&#xff0c;将接口和 Java 的 POJOs(Plain Old Java O…

cms基于nodejs_我如何使基于CMS的网站脱机工作

cms基于nodejsInterested in learning JavaScript? Get my ebook at jshandbook.com有兴趣学习JavaScript吗&#xff1f; 在jshandbook.com上获取我的电子书 This case study explains how I added the capability of working offline to the writesoftware.org website (whic…

how-to-cartoon-ify-an-image-programmatically

http://stackoverflow.com/questions/1357403/how-to-cartoon-ify-an-image-programmatically 转载于:https://www.cnblogs.com/guochen/p/6655333.html

Android Studio 快捷键

2015.02.05补充代码重构快捷键 Alt回车 导入包 自动修正CtrlN 查找类​CtrlShiftN 查找文件CtrlAltL 格式化代码CtrlAltO 优化导入的类和包AltInsert 生成代码(如get,set方法,构造函数等)CtrlE或者AltShiftC 最近更改的代码CtrlR 替换文本CtrlF 查找文本CtrlShiftSpace 自动补全…

【微信小程序】异步请求,权重,自适应宽度并折行,颜色渐变,绝对定位

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 写这篇博文主要是为了能够给到大家做类似功能一些启迪&#xff0c;下面效果图中就是代码实现的效果&#xff0c;其中用到的技巧点还是比较多的&#xff0c; <!--pages/demo_list/d…