本文主要是介绍图片转换成data afn上传图片 图片转string,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.转换
NSData *data;
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
data =UIImagePNGRepresentation(image);
}else {
//返回为JPEG图像。
data =UIImageJPEGRepresentation(image, 1.0);
//如果是0.5,图片大小就降到原来的一半 比如这里 24KB 降到11KB
}
//保存
//[[NSFileManager defaultManager] createFileAtPath:self.imagePath contents:data attributes:nil];
//以下方法 就是把一图片压缩成二进制 再转换成图片做显示 效果 不错 -(void)Read_ImageData {UIImageView *imageView1=[[UIImageView alloc]initWithFrame:CGRectMake(0, 80, 200, 200)];imageView1.image=[UIImage imageNamed:@"cat_food.png"];[self.view addSubview:imageView1]; UIImageView *imageView3=[[UIImageView alloc]initWithFrame:CGRectMake(0, 280, 200, 200)];imageView3.image=[UIImage imageWithData:[Function Image_TransForm_Data:imageView1.image] ];[self.view addSubview:imageView3];NSData *data = [NSData dataWithData:[Function Image_TransForm_Data:imageView1.image ]];[data writeToFile:[Function CreateTheFolder_From:Library_Cache FileHolderName:MyFolder FileName:@"pp111111.png"] atomically:YES]; }
3.图片转string 再还原
NSData*data=UIImagePNGRepresentation(image);//数据转换
NSString *string1=[database64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//当数据量比较大得时候,以前的data转string会溢出,得到结果为空置,所以要用base64处理。
NSLog(@"转码后数据%@",string1);
//===========================还原======================
NSData *data2=[[NSDataalloc]initWithBase64EncodedString:string1options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *img2=[[UIImagealloc]initWithData:data2];
4.上传
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
[mgr POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[formData appendPartWithFileData:data name:@"images" fileName:@"status" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
5.传多张
[mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSArray *imagesArray = images; //self.commitPhotosView.images;
for (int i = 0; i < imagesArray.count; i++){
UIImage *image = imagesArray[i];
NSData *data;
NSString *filename;
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
data = UIImagePNGRepresentation(image);
filename = [NSString stringWithFormat:@"image[%d].png", i];
}else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 1.0);
filename = [NSString stringWithFormat:@"image[%d].jpg", i];
}
[formData appendPartWithFileData: data name:@"images" fileName:filename mimeType:@"image/png"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
}
这篇关于图片转换成data afn上传图片 图片转string的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!