开发者

UIImage to byte array

开发者 https://www.devze.com 2023-04-02 18:00 出处:网络
I\'m creating an app that uploads an image to a server. It must send the byte arra开发者_如何学Pythony on a XML. How do I get the byte array into a NSString?

I'm creating an app that uploads an image to a server. It must send the byte arra开发者_如何学Pythony on a XML. How do I get the byte array into a NSString?

Thanks!


You can convert the UIImage to a NSData object and then extract the byte array from there. Here is some sample code:

UIImage *image = [UIImage imageNamed:@"image.png"];
NSString *byteArray = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

If you are using a PNG Image you can use the UIImagePNGRepresentation function as shown above or if you are using a JPEG Image, you can use the UIImageJPEGRepresentation function. Documentation is available on the UIImage Class Reference


Here is a simple function for iOS to convert from UIImage to unsigned char* byte array -->

+ (unsigned char*)UIImageToByteArray:(UIImage*)image; {

    unsigned char *imageData = (unsigned char*)(malloc( 4*image.size.width*image.size.height));

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGImageRef imageRef = [image CGImage];
    CGContextRef bitmap = CGBitmapContextCreate( imageData,
                                                image.size.width,
                                                image.size.height,
                                                8,
                                                image.size.width*4,
                                                colorSpace,
                                                kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage( bitmap, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);

    CGContextRelease( bitmap);
    CGColorSpaceRelease( colorSpace);

    return imageData;
}


using NSData *data = UIImagePNGRepresentation(image); you can convert image into data , now convert dat to bytes by using getBytes:length: or getBytes:range:

0

精彩评论

暂无评论...
验证码 换一张
取 消