Skip to content

Instantly share code, notes, and snippets.

@vicradon
Forked from mwender/impbcopy.m
Last active September 12, 2024 09:01
Show Gist options
  • Save vicradon/a75cfb2a63067a701e1f41cce327b044 to your computer and use it in GitHub Desktop.
Save vicradon/a75cfb2a63067a701e1f41cce327b044 to your computer and use it in GitHub Desktop.
Command line copy an image file to the clipboard in Mac OS X. See first comment for install instructions.
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <unistd.h>
BOOL copy_to_clipboard(NSString *path)
{
// http://stackoverflow.com/questions/2681630/how-to-read-png-image-to-nsimage
NSImage * image;
if([path isEqualToString:@"-"])
{
// http://caiustheory.com/read-standard-input-using-objective-c
NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
image = [[NSImage alloc] initWithData:[input readDataToEndOfFile]];
}else
{
image = [[NSImage alloc] initWithContentsOfFile:path];
}
// http://stackoverflow.com/a/18124824/148668
BOOL copied = false;
if (image != nil)
{
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *copiedObjects = [NSArray arrayWithObject:image];
copied = [pasteboard writeObjects:copiedObjects];
[pasteboard release];
}
[image release];
return copied;
}
int main(int argc, char * const argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if(argc<2)
{
printf("Usage:\n\n"
"Copy file to clipboard:\n ./impbcopy path/to/file\n\n"
"Copy stdin to clipboard:\n cat /path/to/file | ./impbcopy -");
return EXIT_FAILURE;
}
NSString *path= [NSString stringWithUTF8String:argv[1]];
BOOL success = copy_to_clipboard(path);
[pool release];
return (success?EXIT_SUCCESS:EXIT_FAILURE);
}

Install Instructions

  1. Download this gist or copy it's content to a file. If you download it, the default file name will be copy-to-clipboard-macos.m
  2. Compile the file using the command below:
gcc -Wall -g -O3 -ObjC -framework Foundation -framework AppKit -o imagecopy copy-to-clipboard-macos.m
  1. Move the built executable to a place on $PATH. You can easily move it to /usr/local/bin. Use the command below:
sudo mv imagecopy /usr/local/bin

Usage

imagecopy yourfile.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment