iOS對圖片進行馬賽克處理

    - (UIImage *)getMosicaImageWithOriginal:(UIImage *)originalImage level:(NSUInteger)level {

    //獲取BitmapData
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGImageRef imageRef = originalImage.CGImage;
    CGFloat width = CGImageGetWidth(imageRef);
    CGFloat heigth = CGImageGetHeight(imageRef);
    CGImageAlphaInfo bitmapInfo = CGImageGetAlphaInfo(imageRef);
    CGContextRef context = CGBitmapContextCreate(nil, width, heigth, 8, width*PerPixelChannelCount, colorSpace, bitmapInfo);
    CGContextDrawImage(context, CGRectMake(0, 0, width, heigth), imageRef);
    unsigned char *bitmapDatas = CGBitmapContextGetData(context);

    NSUInteger index =0,perIndex=0;
    unsigned char *pixel[PerPixelChannelCount] = {0};
    for(int i = 0; i < width; i++){

        for(int j = 0; j < heigth; j++){

            index = i*width + j;
            if(i%level == 0){

                if(j%level == 0){
                    memcpy(pixel, bitmapDatas+PerPixelChannelCount*index, PerPixelChannelCount);
                }else{
                    memcpy(bitmapDatas+PerPixelChannelCount*index, pixel, PerPixelChannelCount);
                }
            }else{
                perIndex = (i-1)*width +j;
                memcpy(bitmapDatas+PerPixelChannelCount*index, bitmapDatas+PerPixelChannelCount*perIndex, PerPixelChannelCount);
            }

        }
    }

    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmapDatas, width*heigth*PerPixelChannelCount, NULL);

    //創建輸出的圖像
    CGImageRef mosaicImageRef = CGImageCreate(width, heigth, 8, 32, width*PerPixelChannelCount, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, NO, kCGRenderingIntentDefault);

    CGContextRef outputRef = CGBitmapContextCreate(nil, width, heigth, 8, width*PerPixelChannelCount, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(outputRef, CGRectMake(0, 0, width, heigth), mosaicImageRef);

    CGImageRef resultImageRef = CGBitmapContextCreateImage(outputRef);
    UIImage *resultImage = nil;
    if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
        float scale = [[UIScreen mainScreen] scale];
        resultImage = [UIImage imageWithCGImage:resultImageRef scale:scale orientation:UIImageOrientationUp];
    } else {
        resultImage = [UIImage imageWithCGImage:resultImageRef];
    }

    CGContextRelease(context);
    CGDataProviderRelease(provider);
    CGImageRelease(mosaicImageRef);
    CGImageRelease(resultImageRef);
    CGContextRelease(outputRef);
    CGColorSpaceRelease(colorSpace);

    return resultImage;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章