Home > DeveloperSection > Forums > How to Convert matrix to UIImage?
Pravesh Singh

Total Post:412

Posted on    October-17-2014 11:47 PM

 iPhone iPhone  Ios 

 1 Reply(s)
 943  View(s)
Rate this:

I need to convert a matrix representing a b/w image to UIImage.

For example:

A matrix like this (just the representation). This image would be the symbol '+'




This matrix represents an image in black and white, where black is 0 and white is 1. I need to convert this matrix to UIImage. In this case width would be 3 and height would be 3

Ankita Pandey
Ankita Pandey

Total Post:183

Posted on    October-17-2014 11:48 PM

In order to convert a matrix to UIImage :

CGSize size = CGSizeMake(lines, columns);
UIGraphicsBeginImageContextWithOptions(size, YES, 0);

for (int i = 0; i < lines; i++)
    for (int j = 0; j < columns; j++)
        // Choose color to draw 
        if ( matrixDraw[i*lines + j] == 1 ) {

            [[UIColor whiteColor] setFill];

        } else {

            // Draw black pixel
            [[UIColor blackColor] setFill];            

        // Draw just one pixel in i,j
        UIRectFill(CGRectMake(i, j, 1, 1)); 


// Create UIImage with the current context that we have just created
UIImage *imageFinal = UIGraphicsGetImageFromCurrentImageContext();
Basically what we are doing is :

Create a context with the size of our image

Looping for each pixel to see the value. Black is 0 and white is 1. So depends on the value, we set the color.

The most important function :

This function let us to fill a pixel in the i,j position with width and height (1 both cases for fill one single pixel)

Finally we create an UIImage with the current context and we call to finish the image context.
Hope it helps someone!

Don't want to miss updates? Please click the below button!

Follow MindStick