How to get the compressed file size of an image received from `UIImagePickerController`?

后端 未结 4 1488
再見小時候
再見小時候 2021-01-14 11:58

I want to know the size of image taken by UIImagePickerController by camara or library. Is there any way to find that ?

Requirement is like,

If

4条回答
  •  星月不相逢
    2021-01-14 12:33

    May this code work for you. It is not giving you image in size like bytes or mb. But this code give you image according to Your custom size like 100x200.

    @implementation UIImage (CS_Extensions)
        - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
    
            UIImage *sourceImage = self;
            UIImage *newImage = nil;
    
            CGSize imageSize = sourceImage.size;
            CGFloat width = imageSize.width;
            CGFloat height = imageSize.height;
    
            CGFloat targetWidth = targetSize.width;
            CGFloat targetHeight = targetSize.height;
    
            CGFloat scaleFactor = 0.0;
            CGFloat scaledWidth = targetWidth;
            CGFloat scaledHeight = targetHeight;
    
            CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
            if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
    
                CGFloat widthFactor = targetWidth / width;
                CGFloat heightFactor = targetHeight / height;
    
                if (widthFactor < heightFactor)
                    scaleFactor = widthFactor;
                else
                    scaleFactor = heightFactor;
    
                scaledWidth  = width * scaleFactor;
                scaledHeight = height * scaleFactor;
    
                // center the image
    
                if (widthFactor < heightFactor) {
                    thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
                } else if (widthFactor > heightFactor) {
                    thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
                }
            }
    
    
            // this is actually the interesting part:
    
            UIGraphicsBeginImageContext(targetSize);
    
            CGRect thumbnailRect = CGRectZero;
            thumbnailRect.origin = thumbnailPoint;
            thumbnailRect.size.width  = scaledWidth;
            thumbnailRect.size.height = scaledHeight;
    
            [sourceImage drawInRect:thumbnailRect];
    
            newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
    
            if(newImage == nil) NSLog(@"could not scale image");
    
    
            return newImage ;
        }
        @end
    

提交回复
热议问题