UIImage created from CGImageRef fails with UIImagePNGRepresentation

前端 未结 4 1406
栀梦
栀梦 2021-01-01 23:00

I\'m using the following code to crop and create a new UIImage out of a bigger one. I\'ve isolated the issue to be with the function CGImageCreateWithImageInRect() which see

4条回答
  •  一个人的身影
    2021-01-01 23:31

    It seems the soultion you are trying should work, but i recommend to use this:

    CGImageRef image = [stillView.image CGImage];
    CGRect cropZone;
    
    size_t cWitdh = cropZone.size.width;
    size_t cHeight = cropZone.size.height;
    size_t bitsPerComponent = CGImageGetBitsPerComponent(image);
    size_t bytesPerRow = CGImageGetBytesPerRow(image) / CGImageGetWidth(image) * cWidth;
    
    //Now we build a Context with those dimensions.
    CGContextRef context = CGBitmapContextCreate(nil, cWitdh, cHeight, bitsPerComponent, bytesPerRow, CGColorSpaceCreateDeviceRGB(), CGImageGetBitmapInfo(image));
    
    CGContextDrawImage(context, cropZone, image);
    
    CGImageRef result  = CGBitmapContextCreateImage(context);
    UIImage * cropUIImage = [[UIImage alloc] initWithCGImage:tmp];
    
    CGContextRelease(context);
    CGImageRelease(mergeResult);
    NSData * imgData = UIImagePNGRepresentation ( cropUIImage);
    

    Hope it helps.

提交回复
热议问题