0

I want to take a CGImage, iterate over the pixels and change their alpha values.

I have seen code that change the RGB values of pixels, like this thread Is programmatically inverting the colors of an image possible? It shows how to invert the RGB values of pixels.

But I want to change the alpha values.

Is there any way to do this??

Community
  • 1
  • 1

2 Answers2

1

You can use code from color picker for getting RGBA matrix of image and change alpha. And save to image back.

https://github.com/sakrist/VBColorPicker/blob/master/VBColorPicker/VBColorPicker.m

unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL && data != 0) {
    //offset locates the pixel in the data from x,y. 
    //4 for 4 bytes of data per pixel, w is width of one row of data.
    int offset = 4*((w*round(point.y))+round(point.x));
    int alpha =  data[offset]; 
    int red = data[offset+1]; 
    int green = data[offset+2]; 
    int blue = data[offset+3]; 
    NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
    color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}
Volodymyr B.
  • 3,369
  • 2
  • 30
  • 48
0

Images may or may not have app accessible pixels, or pixels of a known size. However, you can render an image to a bitmap which you created that does. If it's an RGBA (or ABGR) bitmap, then you can change the alpha of any pixel the same way you can change the RGB value. Your app can create a new image from this modified bitmap.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153