LazyOranger
LazyOranger

Reputation: 11

UIImageJPEGRepresentation get wrong size

I want to compress UIImage. However,I get a wrong size. I'm sure UIImageJPEGRepresentation is wrong.how to fix sorry for my poor English

 + (NSData *)compressDataWithImg:(UIImage *)originalImage compression:(CGFloat)compression size:(CGFloat)size {
    NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(originalImage, compression)];
    if ((data.length / 1024.0) > size)
    {
        compression = compression - 0.1;
        if (compression > 0) {
            return [[self class] compressDataWithImg:originalImage compression:compression size:(CGFloat)size];
        }else{
            return data;
        }
    }else{
        return data;
    }
    return data;
}

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *fullImage = info[UIImagePickerControllerOriginalImage];
    fullImage = [fullImage fixOrientationToUp];

    UIImage *imgData = [fullImage scaleToSizeWithLimit:0];
    NSData *data = [Util compressDataWithImg:imgData compression:0.9 size:256]; // this is right:size:2M
    UIImage *image = [UIImage imageWithData:data];//i use this UIImage

    NSData *xxx = [NSData dataWithData: UIImageJPEGRepresentation(image,1) ];// wrong size:7~8M WHY?...

    if (self.imageSelectBlock) {
        self.imageSelectBlock(image);
    }

    [picker dismissViewControllerAnimated:YES completion:NULL] ;
}

thanks for helping me

Upvotes: 1

Views: 860

Answers (1)

tomfriwel
tomfriwel

Reputation: 2635

I found when I use UIImageJPEGRepresentation and imageWithData deal a image again and again. the length of image's data gradually increase.

Test code:

UIImage *image = [UIImage imageNamed:@"test.png"];

NSLog(@"first: %lu", UIImageJPEGRepresentation(image, 1.0).length);
NSLog(@"second: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0).length);
NSLog(@"third: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0)], 1.0).length);

Logs:

first: 361586
second: 385696
third: 403978

I think this problem is caused by UIImageJPEGRepresentation.

Just a test.

And I found a related question:

When i am using UIImagePNGRepresentation or UIImageJPEGRepresentation for converting UIImage into NSdata, the image size is too much increased

Upvotes: 1

Related Questions