如何将UIImage转换为字节数组或base64encoding?

时间:2011-08-25 07:48:17

标签: iphone objective-c uiimage nsdata

我有一个图像,我想作为字节数组发送到服务器。我想知道如何将uiimage转换为字节数组?我必须发送参数

<byteArrayIn>base64Binary</byteArrayIn>到网络服务

提前致谢

2 个答案:

答案 0 :(得分:2)

UIImage *img = ...;
CGFloat quality = 0.85;
NSData *jpegdata = UIImageJPEGRepresentation(img,quality);

NSData *pngdata = UIImagePNGRepresentation(img);

答案 1 :(得分:0)

这是一个简单的iOS函数,可以将UIImage转换为字节数组 - &gt;

+ (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);
    CGImageRelease( imageRef);
    CGColorSpaceRelease( colorSpace);

    return imageData;
}

一旦你有字节数组数据,base64编码的算法很容易实现,你可以在维基百科上阅读它。可能有一种更简单的方法来base64编码它我也不确定。 http://en.wikipedia.org/wiki/Base64