Changing UIImage contents

Discussion in 'iOS Programming' started by xArtx, Jan 25, 2013.

  1. macrumors 6502a

    Mar 30, 2012
    You're not supposed to be able to alter the content of a UIImage directly,
    but I wanted to, so I loaded an image file from main bundle into an NSdata array,
    and from there to a C char array, make changes there, and load back to UIImage from there.

    	// Do once at startup… ie. ViewDidLoad
    	unsigned char imgfile[imgbuffersize];
    	int imgfilelength;
    	UIImage *myImage;
    	NSData *mynewData;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"bmp"];
        NSData *myData = [NSData dataWithContentsOfFile:filePath];
        NSUInteger len = [myData length];
        Byte *byteData = (Byte*)malloc(len);
        memcpy(byteData, [myData bytes], len);
        imgfilelength = len;
        for (int ix = 0; ix < len; ix++) {
        imgfile[ix] = byteData[ix];
    endless_loop() {
    	//Access and change bitmap data stored the imgfile array here
    	//for example, make the left half of the image grayscale
            //by finding the mean average of the RGB component of each
            //pixel you want to change, then write that value to all three
            //components of the pixel.
        mynewData = [NSData dataWithBytes:(const void *)imgfile length:sizeof(char)*imgfilelength];
        myImage = [UIImage imageWithData: mynewData];
        CGPoint imagePoint = CGPointMake(5.0,150);
        [myImage drawAtPoint:imagePoint];
    Aside from possible overhead, which I'm not sure about since UIImage is only a
    pointer if I'm not mistaken, I don't think the entire image is being copied
    from one location in memory to another for each instance.

    Is there anything bad happening here memory wise?
    I have recently treated the C bitmap array as a memory buffer,
    and have a program using it to transform the original image from the main bundle.
  2. thread starter macrumors 6502a

    Mar 30, 2012
    Interestingly enough, although iOS doesn't appear to support it,
    it's possible to save a bitmap image file to the photos app with this:
           myData = [NSData dataWithBytes:(const void *)imgfile length:sizeof(char)*imgfilelength];
           myImage = [UIImage imageWithData: myData];
           UIImageWriteToSavedPhotosAlbum(myImage, nil, nil, nil);
    The bmp images work perfectly in the photos app,
    but when transferred to a PC, none of the programs will open them.
    One of the problems is the image height is -568 instead of 568,
    among other problems.

Share This Page