Search code examples
objective-cimagemacosscreenshotresolution

How to take a screenshot with low quality


Is there a way to a take a screenshot (low level quality) on osx programmatically?

I developed a function like below:

CGImageRef resizeImage(CGImageRef imageRef) {
    CGRect thumRect;
    CGPoint point;
    point.x = 0;
    point.y = 0;
    thumRect.origin = point;
    thumRect.size.height = 225;
    thumRect.size.width = 360;

    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);

    if (aplhaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;

   CGContextRef bitmap = CGBitmapContextCreate(NULL, thumRect.size.width, thumRect.size.height, CGImageGetBitsPerComponent(imageRef), 4 * thumRect.size.width, CGImageGetColorSpace(imageRef), alphaInfo);

   CGContextDrawImage(bitmap, thumRect, imageRef);
   imageRef = CGBitmapContextCreateImage(bitmap);
   CGContextRelease(bitmap);

return imageRef;
}

When I runned this function, I took an between 150KB and 600KB image. If I decrease thumRect size, I cant read any characters in the image. But, I want to decrease these images as low as possible. Is there any suggestion or another possible solution?

Thanks.


Solution

  • I found a solution like below: First af all, resize your image with code in my question.

    Then Compress it :)

    //imageRef is CGImageRef
    NSImage * image = [[NSImage alloc] initWithCGImage:imageRef size:NSZeroSize];
    NSBitmapImageRep *bmpImageRep = [NSBitmapImageRep imageRepWithData [image TIFFRepresentation]];
    
    CGFloat compressionFactor = 1.0 //Read it : (1)
    NSDictionary *jpgProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithDouble:compressionFactor], NSImageCompressionFactor, [NSNumber numberWithBool:NO], NSImageProgressive, nil];
    
    NSData *jpgData = [bmpImageRep representationUsingType:NSJPEGFileType properties:jpgProperties];
    

    (1):https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBitmapImageRep_Class/index.html#//apple_ref/doc/constant_group/Bitmap_image_properties