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

血红的双手。 提交于 2019-12-03 03:57:12

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);

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!