Bautzi89
Bautzi89

Reputation: 346

iOS: How to create a bitmap from binary data and save it on the device as image?

I'm trying to create an image by using binary data that I received from a server. In my function I parse through the data and get a color code for every pixel of my symbol (usually 16 x 16).

For now I got this far:

- (void)saveSymbol:(Byte *)symbolData WithID:(short)symbolID AndOffset:(int)offset AndLength:(int)length {    

int w, width, h, heigth;

width = [self byteToUShort:symbolData withOffset:offset+6];
heigth = [self byteToUShort:symbolData withOffset:offset+8];

NSLog(@"Symbol with ID:%d\nwidth: %d\nheigth:%d", symbolID, width, heigth);

NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];    
NSLog(@"%@", docDir);

NSString *pngFilePath = [NSString stringWithFormat:@"%@/symbol%d.png", docDir, symbolID];
NSLog(@"%@", pngFilePath);

int pos = 25;

for (h = 0; h < heigth; h++) {
    for (w = 0; w < width; w++) {
        if ((symbolData[pos] & 0xFF) != 255) {
            NSLog(@"set color to %d at point (%d / %d)", symbolData[pos] & 0xFF, w, h);
        }
        else {
            if (symbolID == 9)
                NSLog(@"set color to 253 at point (%d / %d)", w, h);
            else
                NSLog(@"set color to %d at point (%d / %d)", symbolData[pos] & 0xFF, w, h);
        }
        pos += 2;
    }
}

}

I hope this made clear what I'm trying to do.

But I don't really know where to go from here. How can I create a bitmap from that data? Is it better to save it as a bitmap or maybe as a png or jpeg file?

Your help will be much appreciated

Upvotes: 1

Views: 3084

Answers (2)

Brian
Brian

Reputation: 15706

  1. Use either a Bitmap context (or CGLayer).
  2. After you've drawn your pixels, use CGBitmapContextCreateImage to get a CGImageRef.
  3. Convert to a UIImage with [UIImage imageFromCGImage:].
  4. Then use UIImagePNGRepresentation() or UIImageJPEGRepresentation() to get an NSData object.
  5. Finally use [NSData writeToFile:atomically:] to save the file.

Upvotes: 2

danh
danh

Reputation: 62686

With only pixel data, you have a little project ahead of you. The standard formats can be complex, especially something like jpeg that has more sophisticated compression. I think png is probably the simplest.

Upvotes: 0

Related Questions