zoukankan      html  css  js  c++  java
  • 获取图片的每一个像素颜色值

    + (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)x andY:(int)y count:(int)count
    {
        NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];
    
        // First get the image into your data buffer
        CGImageRef imageRef = [image CGImage];
        NSUInteger width = CGImageGetWidth(imageRef);
        NSUInteger height = CGImageGetHeight(imageRef);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
        NSUInteger bytesPerPixel = 4;
        NSUInteger bytesPerRow = bytesPerPixel * width;
        NSUInteger bitsPerComponent = 8;
        CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                        bitsPerComponent, bytesPerRow, colorSpace,
                        kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
    
        CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
        CGContextRelease(context);
    
        // Now your rawData contains the image data in the RGBA8888 pixel format.
        NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
        for (int i = 0 ; i < count ; ++i)
        {
            CGFloat alpha = ((CGFloat) rawData[byteIndex + 3] ) / 255.0f;
            CGFloat red   = ((CGFloat) rawData[byteIndex]     ) / alpha;
            CGFloat green = ((CGFloat) rawData[byteIndex + 1] ) / alpha;
            CGFloat blue  = ((CGFloat) rawData[byteIndex + 2] ) / alpha;
            byteIndex += bytesPerPixel;
    
            UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
            [result addObject:acolor];
        }
    
      free(rawData);
    
      return result;
    }
  • 相关阅读:
    UVA
    剑指offer 面试题11
    SharePoint 2013+ Sqlserver 2014 Kerberos 配置传奇, 最终的解决方案 验证。
    ASC(1)G(上升时间最长的序列)
    J2EE它是一个框架?平台?规范?
    C++和python使用struct传输二进制数据结构来实现
    前端开发面试题集(二)
    C语言中<CR>是什么意思
    Delphi ParamStr 使用方法
    打包工具 使用帮助 inno setup
  • 原文地址:https://www.cnblogs.com/yuxiaoyiyou/p/7047693.html
Copyright © 2011-2022 走看看