Get size of a UIImage (bytes length) not height and width

后端 未结 10 2125
说谎
说谎 2020-11-28 09:00

I\'m trying to get the length of a UIImage. Not the width or height of the image, but the size of the data.

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 09:51

    I'm not sure your situation. If you need the actual byte size, I don't think you do that. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to get an NSData object of compressed data of the image.

    I think you want to get the actual size of uncompressed image(pixels data). You need to convert UIImage* or CGImageRef to raw data. This is an example of converting UIImage to IplImage(from OpenCV). You just need to allocate enough memory and pass the pointer to CGBitmapContextCreate's first arg.

    UIImage *image = //Your image
    CGImageRef imageRef = image.CGImage;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
    CGContextRef contextRef = CGBitmapContextCreate(iplimage->imageData, iplimage->width, iplimage->height,
                                                    iplimage->depth, iplimage->widthStep,
                                                    colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
    CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
    CGContextRelease(contextRef);
    CGColorSpaceRelease(colorSpace);
    
    IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3);
    cvCvtColor(iplimage, ret, CV_RGBA2BGR);
    cvReleaseImage(&iplimage);
    

提交回复
热议问题