bitmapImage

2018-12-06  本文已影响0人  牧_e50d
-(void)pixelImageShow:(CGImageRef)image width:(int)width andHeigth:(int)height{
    int mutiple=9;
    for (int i=0; i<height; i++) {
        for (int colu=0; colu<width; colu++) {
            CGImageRef tempImage=CGImageCreateWithImageInRect(image, CGRectMake(colu, i, 1, 1));
            CALayer *tempLayer=[CALayer layer];
            tempLayer.frame=CGRectMake(100+colu*mutiple, 100+i*mutiple, mutiple, mutiple);
            tempLayer.bounds=CGRectMake(0, 0, mutiple, mutiple);
            tempLayer.contents=(__bridge id _Nullable)(tempImage);
            [self.view.layer addSublayer:tempLayer];
            CFRelease(tempImage);
        }
    }
}

-(UIImage *)updateImageColor:(CGImageRef)image{
    CGContextRef context=NULL;
    CGColorSpaceRef colorSpace;
    void * bitmapData;
    size_t bitmapByteCount;
    size_t bitmapBytesPerRow;
    size_t pixelWidth=CGImageGetWidth(image);//图片的像素宽度
    size_t pixelHeight=CGImageGetHeight(image);//图片的像素高度
    bitmapBytesPerRow=(pixelWidth*4);//一个像素4Byte==32bit,内容是RGBA,所以图片一行的像素占字节数是pixelWidth*4
    bitmapByteCount=(bitmapBytesPerRow*pixelHeight);//图片的总大小=每一行占的字节数X总行数(就是像素的高度,比如高度是10个像素)
    colorSpace=CGColorSpaceCreateDeviceRGB();
    if (colorSpace==NULL) {
        fprintf(stderr, "Error alloocating color space\n");
    }
    bitmapData=malloc(bitmapByteCount);
    context=CGBitmapContextCreate(bitmapData, pixelWidth, pixelHeight, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(context, CGRectMake(0, 0, pixelWidth, pixelHeight), image);
    unsigned char* data = CGBitmapContextGetData(context);
    for (int i=0; i<pixelHeight; i++) {
        if (i%2==0) {
            for (int pixelOffset=0; pixelOffset<bitmapBytesPerRow; pixelOffset+=4) {
//                int red=data[i*bitmapBytesPerRow+pixelOffset]
//                int gree=data[i*bitmapBytesPerRow+pixelOffset+1];
//                int blue=data[i*bitmapBytesPerRow+pixelOffset+2];
//                data[i*bitmapBytesPerRow+pixelOffset+3];
                
//                int red=255;
//                int green=20;
//                int blue=50;
//                data[i*bitmapBytesPerRow+pixelOffset]=red;
//                data[i*bitmapBytesPerRow+pixelOffset+1]=green;
//                data[i*bitmapBytesPerRow+pixelOffset+2]=blue;
                if (pixelOffset%8==0) {
                    data[i*bitmapBytesPerRow+pixelOffset+3]=0;
                }
                
            }
        }
    }
    CGImageRef imageNew=CGBitmapContextCreateImage(context);
    [self pixelImageShow:imageNew width:pixelWidth andHeigth:pixelHeight];
    UIImage *useImage=[UIImage imageWithCGImage:imageNew];
    CFRelease(colorSpace);
    free(bitmapData);
    CGContextRelease(context);
    CFRelease(imageNew);
    return useImage;
}
上一篇 下一篇

猜你喜欢

热点阅读