How to convert image into hexa decimal bytes array to send it to output stream in iOS sdk

后端 未结 2 1906
醉酒成梦
醉酒成梦 2021-02-06 17:53

I wan to print an image on a bluetooth printer. I got some sample code by the printer manufacturer. Here is the code -

unsigned char buffer3[796]={
                     


        
相关标签:
2条回答
  • 2021-02-06 18:31

    I guess, the printer will not take any image format? However, here is how you can convert an image to a byte array, hope this will help:

    NSData *data = [NSData dataWithContentsOfFile:imagePath];
    NSUInteger length = [data length];
    Byte *bytes = (Byte*)malloc(length);
    memcpy(bytes, [data bytes], length);
    
    0 讨论(0)
  • 2021-02-06 18:57

    Try this:

    CGImageRef image = [yourUIImage CGImage];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    NSUInteger width = CGImageGetWidth(image);
    NSUInteger height = CGImageGetHeight(image);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    int size = height*width*bytesPerPixel;
    printf("Size:%d\n",size);   
    unsigned char *rawData = malloc(size); 
    CGContextRef context = CGBitmapContextCreate(rawData,width,height,bitsPerComponent,bytesPerRow,colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0,0,width,height),image);
    CGContextRelease(context);
    

    Now, rawData is the data you need.

    Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/21806-convert-cgimage-uiimage.html

    Edit: you have maxLength:796 in your code, but I'm pretty sure this depends on the particular image, you should probably replace 796 by something like sizeof(rawData).

    0 讨论(0)
提交回复
热议问题