Created
February 8, 2022 13:37
-
-
Save rok-git/280a2ad2aef915a5b8216eeb6db5dfd8 to your computer and use it in GitHub Desktop.
make a grayscale image using CIFilter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To Compile: cc -fobjc-arc -framework Cocoa -framework CoreImage monochro.m -o monochro | |
#import <Cocoa/Cocoa.h> | |
#import <CoreImage/CoreImage.h> | |
#include <stdio.h> | |
void usage() | |
{ | |
printf("Usage: argv[0] < INPUTFILE > OUTPUTFILE\n"); | |
printf(" argv[0] INPUTFILE > OUTPUTFILE\n"); | |
exit(1); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
@autoreleasepool{ | |
CIImage *image; | |
if(argc == 2){ | |
if(strcmp("-", argv[1])){ | |
NSURL *fileURL = [NSURL fileURLWithPath: [[NSString stringWithUTF8String: argv[1]] stringByExpandingTildeInPath]]; | |
image = [CIImage imageWithContentsOfURL: fileURL]; | |
if(!image){ | |
printf("cannot open file: %s\n", argv[1]); | |
usage(); | |
} | |
}else{ | |
NSFileHandle *fh = [NSFileHandle fileHandleWithStandardInput]; | |
NSData *inputData = [fh readDataToEndOfFileAndReturnError: nil]; | |
image = [CIImage imageWithData: inputData]; | |
} | |
}else if(argc == 1){ | |
NSFileHandle *fh = [NSFileHandle fileHandleWithStandardInput]; | |
NSData *inputData = [fh readDataToEndOfFileAndReturnError: nil]; | |
image = [CIImage imageWithData: inputData]; | |
}else{ | |
usage(); | |
} | |
/* | |
// CIFilter を使いまわす必要がなければ CIFilter をいちいち作るよりも、 | |
// CIImage#imageByApplyingFilter:withInputParameters: を使う方が簡単。 | |
CIFilter *filter = [CIFilter filterWithName: @"CIColorMonochrome"]; | |
[filter setValue: image forKey: kCIInputImageKey]; | |
[filter setValue: [CIColor colorWithString: @"1.0 1.0 1.0"] forKey: kCIInputColorKey]; | |
// [filter setValue: @0.5 forKey: kCIInputIntensityKey]; | |
CIImage *newImage = filter.outputImage; | |
*/ | |
// 単純にモノクロにするなら、CIColorMonochrome よりも | |
// CIPhotoEffectMono の方が良さそう。 | |
// CIImage *newImage = [image imageByApplyingFilter: @"CIColorMonochrome" withInputParameters: @{kCIInputColorKey: [CIColor colorWithString: @"1.0 1.0 1.0"], kCIInputIntensityKey: @1.0}]; | |
CIImage *newImage = [image imageByApplyingFilter: @"CIPhotoEffectMono" withInputParameters: nil]; | |
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCIImage: newImage]; | |
NSData *data = [bitmap representationUsingType: NSBitmapImageFileTypeJPEG | |
properties: [NSDictionary dictionary]]; | |
NSFileHandle *outFH = [NSFileHandle fileHandleWithStandardOutput]; | |
[outFH writeData: data]; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment