//
//  MBIMImageUtils.m
//  kordophoned
//
//  Created by James Magahern on 12/20/22.
//  Copyright © 2022 James Magahern. All rights reserved.
//

#import "MBIMImageUtils.h"
#import <ImageIO/ImageIO.h>

NSData* MBIMCGImageJPEGRepresentation(CGImageRef imageRef)
{
    if (imageRef == NULL) return nil;
    
    NSNumber *const DPI = @72.0;
    NSNumber *const compressionQuality = @0.9;
    NSDictionary *properties = @{
        (__bridge NSString *)kCGImagePropertyDPIWidth : DPI,
        (__bridge NSString *)kCGImagePropertyDPIHeight : DPI,
        (__bridge NSString *)kCGImageDestinationLossyCompressionQuality : compressionQuality,
    };
    
    bool success = false;
    NSMutableData *data = [NSMutableData data];
    if (data) {
        CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((CFMutableDataRef)data, CFSTR("public.jpeg"), 1/*count*/, NULL/*options*/);
        if (imageDestination != NULL) {
            CGImageDestinationAddImage(imageDestination, imageRef, (__bridge CFDictionaryRef)properties);
            success = CGImageDestinationFinalize(imageDestination);
            CFRelease(imageDestination);
        }
    }

    return success ? data : nil;
}

