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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值