Search code examples
iosobjective-cstringuiimageviewpixel

String with comma separated pixel values (int8) to UIImageView


I am doing a small task where I receive a text string (json message) via TCP/IP, and one entry contains one long list of pixel values for a grayscale image, so the values are in the range of 0-255 e.g.

NSString *foo = @"0,0,0,1,1,1,7,7,7,7,7,0,0,1,1,1,1,100,100,100,100,0,0,0,0,0,0,1,1,1";

This string I would like to display in an UIImageView on my iOS device. I know the width and height of the image (part of the json message), so for example the above could be an image with width = 6 and height = 5, which match foo with 30 entries (pixel values).

I tried iterating through the string with a for loop and NSRange for each line in the image (where NSRange is 0,5 for the first line, 6-11 for the next, and so on), but I cannot figure out if this is the correct way to go, and what data format I should transform it into e.g. NSData, NSArray or something else to be able to use it for UIImageView.


Solution

  • Try this code.

    NSString *foo = @"0,0,0,1,1,1,7,7,7,7,7,0,0,1,1,1,1,100,100,100,100,0,0,0,0,0,0,1,1,1";
    NSArray *colors = [foo componentsSeparatedByString:@","];
    int width = 6;
    int height = 5;
    
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //draw pixels
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int index = x + y*width;
            CGFloat val = [[colors objectAtIndex:index] floatValue];
            val = val / 255.0f;
            CGFloat components[4] = {val, val, val, 1.0f};
            CGContextSetFillColor(context, components);
            CGContextFillRect(context, CGRectMake(x, y, 1.0f, 1.0f));
        }
    }
    
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGRect frame = self.imageView.frame;
    frame.size = CGSizeMake(width, height);
    self.imageView.frame = frame;
    
    self.imageView.image = image;