繁体   English   中英

UIImage像素设置RGB值

[英]UIImage Pixel setting RGB Value

我要做的就是检查特定像素的RGB值,并与它旁边的像素相同,然后将第一个像素的RGB值设置为两个像素的RGB值之间的范围

这是代码

   int width = img.size.width;
int height = img.size.height;


// the pixels will be painted to this array
uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));

// clear the pixels so any transparency is preserved
memset(pixels, 0, width * height * sizeof(uint32_t));

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

// create a context with RGBA pixels
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
                                             kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

// paint the bitmap to our context which will fill in the pixels array
CGContextDrawImage(context, CGRectMake(0, 0, width, height), [img CGImage]);

//allocate pixels array
for(int y = 0; y < height; y++) {
    for(int x = 0; x < width; x++) {
        uint8_t *rgbaPixel1 = (uint8_t *) &pixels[y * width + x];
        uint8_t *rgbaPixel2 = (uint8_t *) &pixels[y * width + x + 1];
        //uint32_t color = r * rgbaPixel[RED] + g * rgbaPixel[GREEN] + b * rgbaPixel[BLUE];
        // set the pixels to the color
        rgbaPixel1[0] = (rgbaPixel1[0] + rgbaPixel2[0] / 2);
        rgbaPixel1[1] = (rgbaPixel1[1] + rgbaPixel2[1] / 2);
        rgbaPixel1[2] = (rgbaPixel1[2] + rgbaPixel2[2] / 2);
        rgbaPixel1[3] = 255;
    }
}

但是我得到的只是一些有趣的结果!

有什么帮助吗? 谢谢 :)

我使用以下代码在图像的左右添加了两条红色细线。 适用于iOS7

-(UIImage*)ModifyImage:(UIImage*) img
{
    UIGraphicsBeginImageContext(img.size);

    [img drawInRect:CGRectMake(0,0,img.size.width,img.size.height) blendMode:kCGBlendModeSourceOut alpha:1.0f];

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    int w =img.size.width;
    int cw,ch;

    cw = img.size.width / 35;
    ch = img.size.height / 35;

    unsigned char* data = CGBitmapContextGetData (ctx);

    for(int y = 0 ; y < img.size.height ; y++)
    {
        for(int x = 0 ; x < img.size.width ; x++)
        {
            //int offset = 4*((w * y) + x);

            int offset = (CGBitmapContextGetBytesPerRow(ctx)*y) + (4 * x);

            int blue    =  data[offset];
            int green   = data[offset+1];
            int red     = data[offset+2];
            //int alpha   = data[offset+3];

            if(x <= (cw * 2) || x >= (cw * 35))
            {
                data[offset]    = 0;
                data[offset+1]  = 0;
                data[offset+2]  = 255;
                data[offset+3]  = 255;
            }
        }
    }

    UIImage *rtimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return rtimg;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM