iOS 그림 압축,필터,잘라 내기 및 렌 더 링 등 상세 한 설명
본 고 는 주로 iOS 이미지 압축,필터,잘라 내기 및 렌 더 링 에 관 한 내용 을 소개 하고 참고 학습 을 제공 합 니 다.다음은 더 이상 말 하지 않 겠 습 니 다.상세 한 소 개 를 해 보 겠 습 니 다.
주요 내용:
1.이미지 기초 지식 에 대한 소개
2.그림 압축
앨범 에서 사진 한 장 얻 기직접 형식 변환 압축:png,jpg,Context 다시 그립 니 다3.이미지 처리
그림 픽 셀 기반 수정그림 클립
렌 더 링
캡 처
1.그림 기초 지식 에 대한 소개
한 장의 그림 은 픽 셀 점 의 집합 으로 모든 픽 셀 은 하나의 독립 적 이 고 자신의 색깔 이 있다.그림 은 일반적으로 배열 로 저장 되 는데 2 차원 배열 이 라 고 할 수 있다.백 수천 만 개의 픽 셀 을 모 아 그림 을 만 들 었 다.도형 을 나타 내 는 방식 은 여러 가지 YUV,RGBA,가장 간단 한 것 은 32 비트 RGBA 모드 이다.한 색상 의 값 을 32 비트(또는 4 바이트)에 저장 합 니 다.각 바이트 에 하나의 색상 채널(RGBA)을 저장 합 니 다.
그림 압축
2.1 간단하게 돌 이 켜 보고 앨범 에서 사진 한 장 가 져 오기
<1>,시스템 의 그림 에 대해 말하자면 앨범 과 카메라 가 없어 서 는 안 됩 니 다.실제 컴퓨터 가 사용 할 때 앨범/사진 기능 을 성공 적 으로 호출 할 수 있 도록 하려 면 info.plist 류 에 두 개의 키 를 설정 해 야 합 니 다.Privacy-Camera Usage 설명 과 Privacy-Photo Library Usage 설명 은 테스트 할 때 붕괴 에 따라 추가 하 는 것 이 좋 습 니 다.
카메라 와 앨범 키
<2>,두 개의 프 록 시 걸 기:
<3>,두 button,앨범 의 tag 값 101,카메라 102,UIImagePickerController 호출
#pragma mark
-(void)selectImage:(UIButton *)sender{
NSInteger tag = sender.tag - 100;
NSUInteger sourceType = 0;
if (tag == 1) {
//
// 1. ( )
if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}else if (tag == 2){
//
// 2. ( )
if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
sourceType = UIImagePickerControllerSourceTypeCamera;
}
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//
imagePickerController.delegate = self;
// imagePickerController.allowsEditing = YES;
imagePickerController.sourceType = sourceType;
[self presentViewController:imagePickerController animated:YES completion:nil];
}
<4>,UIImagePickerController 에이전트 방법의 실현(편집 그림 을 잠시 제거)
#pragma mark - UIImagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
//
if ([mediaType isEqualToString:@"public.image"]) {
UIImage * image;
// ,
// if ([picker allowsEditing]){
//
// image = [info objectForKey:UIImagePickerControllerEditedImage];
// } else {
//
image = [info objectForKey:UIImagePickerControllerOriginalImage];
// }
// ( )
}
[self dismissViewControllerAnimated:YES completion:NULL];
}
// ,
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@" --- %s", __func__);
[self dismissViewControllerAnimated:YES completion:nil];
}
<4>,계산 NSData 크기
#pragma mark NSData
- (NSString*)length:(NSInteger)length{
if (length > 1024 * 1024) {
int mb = (int)length/(1024*1024);
int kb = (length%(1024*1024))/1024;
return [NSString stringWithFormat:@"%dMb%dKB",mb, kb];
}else{
return [NSString stringWithFormat:@"%ldKB",length/1024];
}
}
2.2 위 에서 우 리 는 이미 사진 을 받 았 습 니 다.그러면 아래 우리 팀 사진 의 압축 을 통 해 처리 하 겠 습 니 다.<1>:png 압축
//
NSData *dataPNG = UIImagePNGRepresentation(image);
UIImage *compressPNGImage = [UIImage imageWithData:dataPNG];
NSLog(@"%@",[self length:dataPNG.length]);
알림:이런 압축 방식 은 메모리 급등 이 나타 날 것 이다
/**
:UIIMage
: ( )0~1
*/
NSData *dataJPG = UIImageJPEGRepresentation(image, 0.1);
UIImage *compressJPGImage = [UIImage imageWithData:dataJPG];
NSLog(@"%@",[self length:dataJPG.length]);
알림:1.JPEG 를 통 해 그림 을 압축 한다 면,그림 을 압축 한 후 에는 진실 하지 않 습 니 다.
2.애플 은 JPG 사진 을 사용 하 는 것 을 공식 적 으로 추천 하지 않 습 니 다.왜냐하면 현실 JPG 사진 은 압축 을 풀 때 성능 이 매우 소모 되 기 때 문 입 니 다.
3.이런 압축 방식 은 그림 의 질 을 설정 할 수 있 지만 메모리 가 급증 할 수도 있다.
<3>:사용자 정의 size 압축 은 상하 문 을 통 해 그림 을 압축 합 니 다
UIImage *compressImg = [self compressOriginalImage:image withImageSize:CGSizeMake(200, 200)];
NSLog(@"%@",NSStringFromCGSize(compressImg.size));
//
- (UIImage *)compressOriginalImage:(UIImage *)originalImage withImageSize:(CGSize)size{
//
UIGraphicsBeginImageContext(size);
//
[originalImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
//
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//
UIGraphicsEndImageContext();
return newImage;
}
알림:이런 방식 은 메모리 의 급등 을 해결 하 는 좋 은 압축 방식 이 라 고 할 수 있 습 니 다.<4>:주의:일반적인 상황 에서 앨범 에서 그림 을 가 져 오 는 기능 과 관련 되면 메모 리 를 처리 해 야 합 니 다.일반적인 상황 에서 다음 프로그램 이 시작 하면 20m 정도 의 메모 리 를 차지 합 니 다.메모리 가 500 M 정도 치 솟 을 때 시스템 은 메모리 경 고 를 보 냅 니 다.이 때 메모 리 를 풀 어야 합 니 다.그렇지 않 으 면 메모리 가 100 M 정도 로 방출 되면 반 짝 입 니 다.그러면 시스템 은 우리 의 응용 프로그램 을 반 짝 이지 않 을 것 이다.즉,한 응용 프로그램 이 사용 하 는 메모리 가 20~100 일 때 비교적 안전 한 내용 범위 라 는 것 이다.
그림 처리
3.1 이미지 픽 셀 기반 수정
<1>,필터 그림:그림 과 관련 된 픽 셀 처리 도 상하 문 에 따라 조작 하여 그립 니 다.그림 파일 에서 그림 데이터 의 픽 셀 을 꺼 내(RGBA)픽 셀 을 조작 하여 변환(Bitmap(GPU))
수정 후 복원(그림 의 속성 RGBA,RGBA(너비,높이,색 값 공간,너비 와 높이,각각 픽 셀 몇 개,줄 몇 개 그리 기)
필터 그림
-(void)filterImage{
CGImageRef imageRef = self.imageView1.image.CGImage;
// 1 = 8bit 17152 17152*8
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bits = CGImageGetBitsPerComponent(imageRef); // 8
size_t bitsPerrow = CGImageGetBytesPerRow(imageRef); // width * bits
//
CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
// AlphaInfo: RGBA AGBR RGB :AlphaInfo
CGImageAlphaInfo alpInfo = CGImageGetAlphaInfo(imageRef);
// bitmap
CGDataProviderRef providerRef = CGImageGetDataProvider(imageRef);
CFDataRef bitmapData = CGDataProviderCopyData(providerRef);
NSInteger pixLength = CFDataGetLength(bitmapData);
// byte
Byte *pixbuf = CFDataGetMutableBytePtr((CFMutableDataRef)bitmapData);
// RGBA
for (int i = 0; i < pixLength; i+=4) {
[self eocImageFiletPixBuf:pixbuf offset:i];
}
//
// bitmap
CGContextRef contextR = CGBitmapContextCreate(pixbuf, width, height, bits, bitsPerrow, colorSpace, alpInfo);
CGImageRef filterImageRef = CGBitmapContextCreateImage(contextR);
UIImage *filterImage = [UIImage imageWithCGImage:filterImageRef];
self.imageView1.image = filterImage;
}
// RGBA
- (void)eocImageFiletPixBuf:(Byte*)pixBuf offset:(int)offset{
int offsetR = offset;
int offsetG = offset + 1;
int offsetB = offset + 2;
// int offsetA = offset + 3;
int red = pixBuf[offsetR];
int gre = pixBuf[offsetG];
int blu = pixBuf[offsetB];
// int alp = pixBuf[offsetA];
int gray = (red + gre + blu)/3;
pixBuf[offsetR] = gray;
pixBuf[offsetG] = gray;
pixBuf[offsetB] = gray;
}
<2>,그림 복원:이것 은 사실 할 말 이 없습니다.필터 전의 그림 의 UIIMage 를 저장 하고 다시 값 을 부여 하면 됩 니 다.3.2 이미지 편집 클립
그림 클립
<1>,규칙 그림 잘라 내기(원형,사각형 등)
#pragma mark ( )
-(void)clipImage{
CGSize size = CGSizeMake(100, 100);
//
UIGraphicsBeginImageContext(size);
//
CGContextRef context = UIGraphicsGetCurrentContext();
// ( )
CGRect rect = CGRectMake(0, 0, size.width, size.height);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);
//
[self.oriImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//
self.imageView2.image = clipImage;
}
<2>,불규칙 한 그림 잘라 내기(사용자 정의 path 에 따라 잘라 내기)
#pragma mark ( )
-(void)irRegularclipImage{
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
CGContextRef context = UIGraphicsGetCurrentContext();
// path
CGMutablePathRef pathRef = CGPathCreateMutable();
CGPoint lines[] = {
CGPointMake(50,0),
CGPointMake(100,0),
CGPointMake(150,80),
CGPointMake(0,80),
CGPointMake(50,0)
};
CGPathAddLines(pathRef, NULL, lines, 5);
CGContextAddPath(context, pathRef);
CGContextClip(context);
[self.oriImage drawInRect:CGRectMake(0, 0, 200, 200)];
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//
self.imageView3.image = clipImage;
}
3.3 이미지 렌 더 링
#pragma mark
-(void)blend{
//
CGSize size = CGSizeMake(self.imageView1.frame.size.width, self.imageView1.frame.size.height);
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.oriImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
//
UIColor *redColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5];
CGContextSetFillColorWithColor(context, redColor.CGColor);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
// CGImageRef
CGImageRef imageRef = CGBitmapContextCreateImage(context);
self.imageView1.image = [UIImage imageWithCGImage:imageRef];
UIGraphicsEndImageContext();
}
3.4,캡 처(대상 의 모든 보 기 를 캡 처),self.view 의 보 기 를 캡 처 하 는 것 을 예 로 들 면캡 처**(대상 의 모든 보 기 를 캡 처),self.view 의 보 기 를 캡 처 하 는 것 을 예 로 들 면
<1>,캡 처 방식 1
- (UIImage *)jk_snapshotImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0);
[self.view drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
<2>,캡 처 방식 1
- (UIImage *)imageFromFullView{
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
UIGraphicsEndImageContext();
return newImage;
}
이 블 로그 의demo ( 로 컬 다운로드 )총결산
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Swift의 패스트 패스Objective-C를 대체하기 위해 만들어졌지만 Xcode는 Objective-C 런타임 라이브러리를 사용하기 때문에 Swift와 함께 C, C++ 및 Objective-C를 컴파일할 수 있습니다. Xcode는 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.