美文网首页swift4.0
获取图片每像素颜色值

获取图片每像素颜色值

作者: 279cb620c509 | 来源:发表于2019-01-23 09:55 被阅读0次

    关于获取图片每像素颜色值

    以下是oc及swift实现

    swift:

    func getimageColorarray(_ image:UIImage) ->[[(CGFloat,CGFloat,CGFloat,CGFloat)]] {
            var colorA = [[(CGFloat,CGFloat,CGFloat,CGFloat)]]()
            //        image.cgImage.sc
            let pixelData = image.cgImage?.dataProvider?.data
            let data:UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
            let length = CFDataGetLength(pixelData)
    
            for x in 0..<Int(image.size.height) {
                var colorR = [(CGFloat,CGFloat,CGFloat,CGFloat)]()
                for y in 0..<Int(image.size.width) {
    
                    let pixelInfo: Int = ((Int(image.size.width)*Int(y)) + Int(x)) * 4
    
                    let r = CGFloat(data[pixelInfo])
                    let g = CGFloat(data[pixelInfo+1])
                    let b = CGFloat(data[pixelInfo+2])
                    let a = CGFloat(data[pixelInfo+3])
    
                    let rgba = (r,g,b,a)
                    colorR.append(rgba)
                }
                colorA.append(colorR)
            }
    
            return colorA
        }
    

    object-c:

    +(NSMutableArray*)imageFunc:(UIImage *)image{
    NSMutableArray *colorArray = [NSMutableArray array];
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t bytesPerRow = imageWidth * 4;
    uint32_t *rgbImageBuf = (uint32_t *)malloc(bytesPerRow * imageHeight);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        NSMutableArray  *colorRow = [NSMutableArray array];
        uint8_t *ptr = (uint8_t *)pCurPtr;
        int r = ptr[0];
        int g = ptr[1];
        int b = ptr[2];
        int a = ptr[3];
        [colorRow addObject:[[NSNumber alloc] initWithInt:r]];
        [colorRow addObject:[[NSNumber alloc] initWithInt:g]];
        [colorRow addObject:[[NSNumber alloc] initWithInt:b]];
        [colorRow addObject:[[NSNumber alloc] initWithInt:a]];
    
        [colorArray addObject:colorRow];
    }
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return colorArray;
    }
    

    相关文章

      网友评论

        本文标题:获取图片每像素颜色值

        本文链接:https://www.haomeiwen.com/subject/xvxjjqtx.html