In Cocoa: How to open image, resize it and save it with a new name - cocoa

I am trying to open an image with open dialog, resize it and save it with a new name, I found some code in other posts and putting 2 or 3 things togheter I finished having this code, but it doesn't work... here is my code:
-(IBAction)apriFileImmagine:(id)sender
{
[pannelloHome makeKeyAndOrderFront:self];
int i; // Loop counter.
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths objectAtIndex:0];
NSURL *myUrl = [NSURL fileURLWithPath:documentsDirectory2];
[openDlg setDirectoryURL:myUrl];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModal] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* files = [openDlg URLs];
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSURL* fileName = [files objectAtIndex:i];
[self scaleIcons:documentsDirectory2 :fileName];
}
}
}
- (void)scaleIcons:(NSString *)outputPath :(NSURL *)nomeImmagine
{
NSImage *image = [NSImage imageNamed:[NSString stringWithFormat:#"%#",nomeImmagine]];
NSSize outputSize = NSMakeSize(512.0f,512.0f);
NSImage *anImage = [self scaleImage:image toSize:outputSize];
NSString *finalPath = [outputPath stringByAppendingString:#"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}
- (NSImage *)scaleImage:(NSImage *)image toSize:(NSSize)targetSize
{
if ([image isValid])
{
NSSize imageSize = [image size];
float width = imageSize.width;
float height = imageSize.height;
float targetWidth = targetSize.width;
float targetHeight = targetSize.height;
float scaleFactor = 0.0;
float scaledWidth = targetWidth;
float scaledHeight = targetHeight;
NSPoint thumbnailPoint = NSZeroPoint;
if (!NSEqualSizes(imageSize, targetSize))
{
float widthFactor = targetWidth / width;
float heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
{
scaleFactor = widthFactor;
}
else
{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if (widthFactor < heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor > heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
newImage = [[NSImage alloc] initWithSize:targetSize];
[newImage lockFocus];
NSRect thumbnailRect;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[image drawInRect:thumbnailRect
fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:1.0];
[newImage unlockFocus];
}
}
return newImage;
}
as you can see I'm trying to save in the same directory where the image has been taken... but all I'm getting is an error:
: ImageIO: CGImageSourceCreateWithData data parameter is nil
Anyone knows what I am doing wrong? Any help will be very much appreciated... thanks Massy

The problem with your image only, image is nil, So I have modified this method:
- (void)scaleIcons:(NSString *)outputPath :(NSURL *)nomeImmagine
{
//NSImage *image = [NSImage imageNamed:[NSString stringWithFormat:#"%#",nomeImmagine]]; commented this part
//start modification
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[[nomeImmagine path] autorelease]];
if (!image)
image = [[NSWorkspace sharedWorkspace] iconForFile:[nomeImmagine path]];
//end modification
NSSize outputSize = NSMakeSize(512.0f,512.0f);
NSImage *anImage = [self scaleImage:image toSize:outputSize];
NSString *finalPath = [outputPath stringByAppendingString:#"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}
Try This , it worked for me..

Yes that's wrong. Try:
NSImage *image = [[NSImage alloc] initWithContentsOfFile:nomeImage];
NSAssert(image, #"Image is NOT valid");
This should then return a valid NSImage.... ? Depending on if you're using ARC you may want to release/auto release as you have 'alloc'd.

Related

NSMutableArray causing crash

I am sorry for the long post but I am at my wits end and have been stumped for days over this. Here's the scenario. My app loads a response from core data, converts the values to NSStrings so that I can add them to an NSDictionary. Then the NSDictionary is converted to NSData so I can attach it as a file to email. The purpose of this is so I can create a database of information including images, videos, etc. I was able to get everything to work except I am having an issue with an NSMutableArray. Here's the process:
I create an event and then load the data for exporting with this code.
EventDB *per = [[EventDB alloc]init];
per.customLayoutArray = [record.customLayoutArray description] ?
[record.customLayoutArray description] : #"";
NSDictionary *dict = [per dictionaryWithValuesForKeys:#[#"customLayoutArray"];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
Then I email the data using MFMailComposer. Then I have a custom UTI that allows me the open the url from the email and then I import the data and load it into my coredata entity with this
if([[url pathExtension] isEqualToString:#"ipix"]) {
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"TSPItem"
inManagedObjectContext:self.managedObjectContext];
TSPItem *record = (TSPItem *)[[NSManagedObject alloc] initWithEntity:entity
insertIntoManagedObjectContext:self.managedObjectContext];
if (record) {
NSString *datetime = [jsonData objectForKey:#"customLayoutArray"];
record.customLayoutArray = [[datetime propertyList] mutableCopy];
}
That works fine. It does import the way I want but when I launch the event I get this crash message
** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFString apply]: unrecognized selector sent to instance 0x1c81a5f60
Now here's the code where it crashes.
NSMutableArray *archiveArray = self.record.customLayoutArray;
NSString *mycustom = [NSString stringWithFormat:#"%#_customlayout",
self.record.eventname];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:archiveArray];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:mycustom];
self.customLayoutArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(#"BOOTH EVENT ID %#", self.customLayoutArray);
[self.customLayoutArray makeObjectsPerformSelector:#selector(apply)];
This is the log from BOOTH EVENT ID
BOOTH EVENT ID (
"<Rectangle:0x102d38cb0self.scaleValue=1.842393\n, self.rotateValue=0.000000\n, self.width=368.478516\n, self.height=368.478516\n, self.radius=0\n, self.frame={{104, 113.5}, {200, 200}}\n, self.isApplied=NO\n>",
"<Rectangle:0x102d393c0self.scaleValue=1.000000\n, self.rotateValue=0.000000\n, self.width=200.000000\n, self.height=200.000000\n, self.radius=0\n, self.frame={{253, 273.5}, {200, 200}}\n, self.isApplied=NO\n>"
)
The app crashes here. Now if I load the original event on my iPad (the one that I didn't export) the app works perfect and the NSLog response for BOOTH EVENT ID is identical.
The "apply" section refers to this file.
#import "Rectangle.h"
#import "DeviceSize.h"
#implementation Rectangle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.clipsToBounds = YES;
self.userInteractionEnabled = YES;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:[NSNumber numberWithFloat:self.scaleValue] forKey:#"ScaleValue"];
[coder encodeObject:[NSNumber numberWithFloat:self.rotateValue] forKey:#"RotateValue"];
[coder encodeObject:[NSNumber numberWithFloat:self.width] forKey:#"Width"];
[coder encodeObject:[NSNumber numberWithFloat:self.height] forKey:#"Height"];
[coder encodeObject:[NSNumber numberWithInteger:self.radius] forKey:#"Radius"];
[coder encodeObject:[NSNumber numberWithBool:self.isApplied] forKey:#"isApplied"];
[coder encodeObject:self.image forKey:#"Image"];
[coder encodeObject:self.backgroundColor forKey:#"BackgroundColor"];
[coder encodeObject:[NSValue valueWithCGPoint:self.center] forKey:#"CenterPoint"];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
self.scaleValue = [[coder decodeObjectForKey:#"ScaleValue"] floatValue];
self.rotateValue = [[coder decodeObjectForKey:#"RotateValue"] floatValue];
self.width = [[coder decodeObjectForKey:#"Width"] floatValue];
self.height = [[coder decodeObjectForKey:#"Height"] floatValue];
self.radius = [[coder decodeObjectForKey:#"Radius"] integerValue];
self.isApplied = [[coder decodeObjectForKey:#"isApplied"] boolValue];
[self.layer setCornerRadius:self.radius];
self.image = [coder decodeObjectForKey:#"Image"];
[self setBackgroundColor:[coder decodeObjectForKey:#"BackgroundColor"]];
//
if (self.width == self.height)
{
CGRect rect = CGRectMake(0, 0,200, 200);
self.frame = rect;
}
if (self.width > self.height)
{
CGRect rect = CGRectMake(0, 0,200, 150);
self.frame = rect;
}
if (self.width < self.height)
{
CGRect rect = CGRectMake(0, 0,150, 200);
self.frame = rect;
}
self.center = [[coder decodeObjectForKey:#"CenterPoint"] CGPointValue];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
/* Set UIView Border */
// Get the contextRef
CGContextRef contextRef = UIGraphicsGetCurrentContext();
// Set the border width
CGContextSetLineWidth(contextRef, 5.0);
// Set the border color to RED
CGContextSetRGBStrokeColor(contextRef, 255.0, 0.0, 0.0, 1.0);
// Draw the border along the view edge
CGContextStrokeRect(contextRef, rect);
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (NSString *)description {
NSMutableString *description = [NSMutableString stringWithFormat:#"<%#:%p", NSStringFromClass([self class]), self];
[description appendFormat:#"self.scaleValue=%f\n", self.scaleValue];
[description appendFormat:#", self.rotateValue=%f\n", self.rotateValue];
[description appendFormat:#", self.width=%f\n", self.width];
[description appendFormat:#", self.height=%f\n", self.height];
[description appendFormat:#", self.radius=%li\n", (long)self.radius];
[description appendFormat:#", self.frame=%#\n", NSStringFromCGRect(self.frame)];
[description appendFormat:#", self.isApplied=%#\n", self.isApplied ? #"YES" : #"NO"];
[description appendString:#">"];
return description;
}
- (id)copyWithZone:(NSZone *)zone {
Rectangle *copy = [[[self class] allocWithZone:zone] init];
if (copy != nil) {
copy.scaleValue = self.scaleValue;
copy.rotateValue = self.rotateValue;
copy.width = self.width;
copy.height = self.height;
copy.radius = self.radius;
copy.frame = self.frame;
copy.isApplied = self.isApplied;
}
return copy;
}
#end
#implementation Rectangle(ApplyRotate)
#pragma mark -
- (Rectangle *)apply {
if (self.isApplied) {
return self;
}
Rectangle *rectangle = self;
CGPoint centerPoint = rectangle.center;
CGAffineTransform rotate = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(rectangle.rotateValue));
CGAffineTransform scale = CGAffineTransformMakeScale(rectangle.scaleValue, rectangle.scaleValue);
CGAffineTransform scaleAndRotate = CGAffineTransformConcat(rotate, scale);
rectangle.transform = scaleAndRotate;
rectangle.center = centerPoint;
rectangle.isApplied = YES;
return rectangle;
}
#end

writing image to the destination path throwing an error in mac os x 10.11

I am trying to write an image into a specific path. for that the code I written was:
- (void)thumbnailWithDataProvider:(CGDataProviderRef)dataProvider url:(NSURL *)url guid:(NSString *)guid {
// The caller of this method typically releases this strait after calling.
// We therefore retain it and release it at the end of the block.
CGDataProviderRetain(dataProvider);
// Dispatch the generation in a block on a queue sutable for this guid
dispatch_async([self queueForGuid:guid], ^{
NRLog(#"PDFORDER: Generate start %# %#", guid, url);
CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithProvider(dataProvider);
size_t numPages = CGPDFDocumentGetNumberOfPages(documentRef);
if ( numPages ) {
CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
CGRect cropBox = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);
for ( size_t i = 0; i < NRMThumbnailCount; i++ ) {
size_t scale = NRMThumbnailSizes[i];
NSString *path = [url path];
path = [NSString stringWithFormat:#"%#%lu.png", path, scale];
NSURL *outurl = [NSURL fileURLWithPath:path];
CGImageRef imageRef;
CGFloat scaleX = scale/cropBox.size.width;
CGFloat scaleY = scale/cropBox.size.height;
CGFloat pdfScale = ( scaleX < scaleY ? scaleX : scaleY );
CGFloat width = (CGFloat)ceil((double) pdfScale*cropBox.size.width);
CGFloat height = (CGFloat)ceil((double) pdfScale*cropBox.size.height);
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width*4, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextScaleCTM(context, pdfScale, pdfScale);
CGContextSetFillColor(context, NRMPDFBackgroundColorComponents);
CGContextFillRect(context, cropBox);
CGContextDrawPDFPage( context, pageRef );
imageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGImageDestinationRef imageDest = CGImageDestinationCreateWithURL((CFURLRef)outurl, THUMBNAIL_TYPE, 1, NULL);//Getting error at this line as " <Error>: ImageIO: CGImageDestinationSetProperties image destination parameter is nil " and the app getting crashed.
if(!imageDest) {
NSLog(#"***Could not create image destination ***");
}
CFStringRef keys[1];
keys[0] = kCGImageDestinationLossyCompressionQuality;
CFNumberRef values[1];
CGFloat compression = (CGFloat)THUMBNAIL_COMPRESSION;
CFNumberRef compressionNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &compression);
values[0] = compressionNumber;
CFDictionaryRef properties = CFDictionaryCreate(kCFAllocatorDefault, (void *)keys, (void *)values, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CGImageDestinationSetProperties(imageDest, properties);
CGImageDestinationAddImage(imageDest, imageRef, NULL);
CGImageDestinationFinalize(imageDest);
CGImageRelease(imageRef);
CFSafeRelease(imageDest);
CFSafeRelease(compressionNumber);
CFSafeRelease(properties);
}
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:kNRMPDFThumbnailImageChangeNotification object:guid];
}
CGPDFDocumentRelease(documentRef);
CGDataProviderRelease(dataProvider);
NRLog(#"PDFORDER: Generate end %# %#", guid, url);
});
}
All the parameters I passed into the method has values still destination value becoming nil.
This happening only with Mac OS X 10.11
can anyone suggest on this.
I strongly suspect this code:
NSString *path = [url path];
path = [NSString stringWithFormat:#"%#%lu.png", path, scale];
NSURL *outurl = [NSURL fileURLWithPath:path];
Better is:
NSString *filename = [NSString stringWithFormat:#"%lu.png", scale];
NSURL *outurl = [url URLByAppendingPathComponent:filename];

IOS: How to split an UIImage into parts

In one of my application I need to split UIImage into multiple parts. The following was the code I am using to split. Here my problem is I am unable to load the image view by adding the image to UIImageView.
- (void)viewDidLoad
{
UIImage* image = [UIImage imageNamed:#"monalisa.png"];
NSMutableArray* splitImages = [self splitImageIntoRects:(__bridge CGImageRef)(image)];
printf("\n count; %d",[splitImages count]);
CALayer *layer = [splitImages objectAtIndex:5];
CGImageRef imgRef = (__bridge CGImageRef)(layer.contents);
UIImage *img = [[UIImage alloc] initWithCGImage:imgRef];
UIImageView* imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
imageview.image = img;
imageview.backgroundColor = [UIColor redColor];
[self.view addSubview:imageview];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (NSMutableArray*)splitImageIntoRects:(CGImageRef)anImage
{
CGSize imageSize = CGSizeMake(CGImageGetWidth(anImage), CGImageGetHeight(anImage));
NSMutableArray *splitLayers = [NSMutableArray array];
int kXSlices = 3;
int kYSlices = 3;
for(int x = 0;x < kXSlices;x++) {
for(int y = 0;y < kYSlices;y++) {
CGRect frame = CGRectMake((imageSize.width / kXSlices) * x,
(imageSize.height / kYSlices) * y,
(imageSize.width / kXSlices),
(imageSize.height / kYSlices));
CALayer *layer = [CALayer layer];
layer.frame = frame;
CGImageRef subimage = CGImageCreateWithImageInRect(anImage, frame);
layer.contents = (__bridge id)subimage;
[splitLayers addObject:layer];
}
}
return splitLayers;
}
And the output is like follows,
Try This:
- (void)viewDidLoad
{
[super viewDidLoad];
[self getSplitImagesFromImage:[UIImage imageNamed:#"Image1.png"] withRow:4 withColumn:4];
}
-(NSMutableArray *)getSplitImagesFromImage:(UIImage *)image withRow:(NSInteger)rows withColumn:(NSInteger)columns
{
NSMutableArray *aMutArrImages = [NSMutableArray array];
CGSize imageSize = image.size;
CGFloat xPos = 0.0, yPos = 0.0;
CGFloat width = imageSize.width/rows;
CGFloat height = imageSize.height/columns;
for (int aIntY = 0; aIntY < columns; aIntY++)
{
xPos = 0.0;
for (int aIntX = 0; aIntX < rows; aIntX++)
{
CGRect rect = CGRectMake(xPos, yPos, width, height);
CGImageRef cImage = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *aImgRef = [[UIImage alloc] initWithCGImage:cImage];
UIImageView *aImgView = [[UIImageView alloc] initWithFrame:CGRectMake(aIntX*width, aIntY*height, width, height)];
[aImgView setImage:aImgRef];
[aImgView.layer setBorderColor:[[UIColor blackColor] CGColor]];
[aImgView.layer setBorderWidth:1.0];
[self.view addSubview:aImgView];
[aMutArrImages addObject:aImgRef];
xPos += width;
}
yPos += height;
}
return aMutArrImages;
}
for more info see this and you can also download demo from here.
We can enhance more the Yasika Patel Answer. Below function will give you exact peice of image which fits to your view.
- (void)splitImage :(UIImage *)image withColums:(int)columns WithRows: (int)rows ViewToIntegrate : (UIView *)view
{
CGSize imageSize = _imgSplit.image.size;
CGFloat xPos = 0.0, yPos = 0.0;
CGFloat width = imageSize.width/rows;
CGFloat height = imageSize.height/columns;
for (int aIntY = 0; aIntY < columns; aIntY++)
{
xPos = 0.0;
for (int aIntX = 0; aIntX < rows; aIntX++)
{
CGRect rect = CGRectMake(xPos, yPos, width, height);
CGImageRef cImage = CGImageCreateWithImageInRect([ image CGImage], rect);
UIImage *aImgRef = [[UIImage alloc] initWithCGImage:cImage];
UIImageView *aImgView = [[UIImageView alloc] initWithFrame:CGRectMake(aIntX*(view.frame.size.width/rows), aIntY*( view.frame.size.height/columns), view.frame.size.width/rows, view.frame.size.height/columns)];
[aImgView setImage:aImgRef];
[aImgView.layer setBorderColor:[[UIColor blackColor] CGColor]];
[aImgView.layer setBorderWidth:0.5];
[view addSubview:aImgView];
xPos += width;
}
yPos += height;
}
[self.view addSubview:view];
}
This will give you the image in 9parts . here you just need to pass the row and colums.

How to convert PDF to CGImage and then save to a high DPI JPG image?

I know there is a way to save the PDF pages to NSImage and then output to JPG like this:
NSData *pdfData = [NSData dataWithContentsOfFile:pathToUrPDF];
NSPDFImageRep *pdfImg = [NSPDFImageRep imageRepWithData:pdfData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSInteger pageCount = [pdfImg pageCount];
for(int i = 0 ; i < pageCount ; i++) {
[pdfImg setCurrentPage:i];
NSImage *temp = [[NSImage alloc] init];
[temp addRepresentation:pdfImg];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:#"Page_%ld.jpg", (long)[pdfImg currentPage]];
[fileManager createFileAtPath:[NSString stringWithFormat:#"%#/%#", #"pathWrUWantToSave", pageName] contents:finalData attributes:nil];
}
However the "TIFFRepresetation" can only output as 72 DPI highest. So I think the best way to get the high DPI image from a PDF is using CGImage on Mac OS X. How to do this? My destination application is for Mac OS X, not iOS...
Thanks alot
Finally I got the solution:
Since OS X 10.8, NSImage has a block based initialiser to draw vector based content into a bitmap.
The idea is to provide a drawing handler that is called whenever a representation of the image is requested.
The relation between points and pixels is expressed by passing a NSSize (in points) to the initialiser and to explicitly set the pixel dimensions for the representation:
NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString* pdfPath = [localDocuments stringByAppendingPathComponent:#"1.pdf"];
NSData* pdfData = [NSData dataWithContentsOfFile:pdfPath];
NSPDFImageRep* pdfImageRep = [NSPDFImageRep imageRepWithData:pdfData];
CGFloat factor = 300/72;
NSInteger pageCount = [pdfImageRep pageCount];
for(int i = 0 ; i < pageCount ; i++) {
[pdfImageRep setCurrentPage:i];
NSImage* scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
[pdfImageRep drawInRect:dstRect];
return YES;
}];
NSImageRep* scaledImageRep = [[scaledImage representations] firstObject];
/*
* The sizes of the PDF Image Rep and the [NSImage imageWithSize: drawingHandler:]-context
* are define in terms of points.
* By explicitly setting the size of the scaled representation in in Pixels, you
* define the relation between ponts & pixels.
*/
scaledImageRep.pixelsWide = pdfImageRep.size.width * factor;
scaledImageRep.pixelsHigh = pdfImageRep.size.height * factor;
NSBitmapImageRep* pngImageRep = [NSBitmapImageRep imageRepWithData:[scaledImage TIFFRepresentation]];
NSData* finalData = [pngImageRep representationUsingType:NSJPEGFileType properties:nil];
NSString* pageName = [NSString stringWithFormat:#"Page_%ld.jpg", (long)[pdfImageRep currentPage]];
[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:#"%#%#", pdfPath, pageName] contents:finalData attributes:nil];
}

Is it possible to print IKImageBrowserView In Cocoa programmatically?

I want to take print of IKImageBrowserView with (content) images. I tried the following code
if (code == NSOKButton) {
NSPrintInfo *printInfo;
NSPrintInfo *sharedInfo;
NSPrintOperation *printOp;
NSMutableDictionary *printInfoDict;
NSMutableDictionary *sharedDict;
sharedInfo = [NSPrintInfo sharedPrintInfo];
sharedDict = [sharedInfo dictionary];
printInfoDict = [NSMutableDictionary dictionaryWithDictionary: sharedDict];
[printInfoDict setObject:NSPrintSaveJob
forKey:NSPrintJobDisposition];
[printInfoDict setObject:[sheet filename] forKey:NSPrintSavePath];
printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
[printInfo setHorizontalPagination: NSAutoPagination];
[printInfo setVerticalPagination: NSAutoPagination];
[printInfo setVerticallyCentered:NO];
printOp = [NSPrintOperation printOperationWithView:imageBrowser
printInfo:printInfo];
[printOp setShowsProgressPanel:NO];
[printOp runOperation];
}
because IKImageBrowserView is Inherits from NSView but print preview is showing null image. Please help me to over come this problem. Thanks in advance.....
/*
1) allocate a c buffer at the size of the visible rect of the image
browser
*/
NSRect vRect = [imageBrowser visibleRect];
NSSize size = vRect.size;
NSLog(#"Size W = %f and H = %f", size.width, size.height);
void *buffer = malloc(size.width * size.height * 4);
//2) read the pixels using openGL
[imageBrowser lockFocus];
glReadPixels(0,
0,
size.width,
size.height,
GL_RGBA,
GL_UNSIGNED_BYTE,
buffer);
[imageBrowser unlockFocus];
//3) create a bitmap with those pixels
unsigned char *planes[2];
planes[0] = (unsigned char *) (buffer);
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:planes pixelsWide:size.width
pixelsHigh:size.height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES
isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bitmapFormat:0
bytesPerRow:size.width*4 bitsPerPixel:32];
/*
4) create a temporary image with this bitmap and set it flipped
(because openGL and the AppKit don't have the same pixels coordinate
system)
*/
NSImage *img = [[NSImage alloc] initWithSize:size];
[img addRepresentation:imageRep];
[img setFlipped:YES];
[imageRep release];
/*
5) draw this temporary image into another image so that we get an
image without any reference to our "buffer" buffer so that we can
release it after that
*/
NSImage *finalImage = [[NSImage alloc] initWithSize:size];
[finalImage lockFocus];
[img drawAtPoint:NSZeroPoint
fromRect:NSMakeRect(0,0,size.width,size.height)
operation:NSCompositeCopy fraction:1.0];
[finalImage unlockFocus];
//[NSString stringWithFormat:#"/tmp/%#.tiff", marker]
NSData *imageData = [finalImage TIFFRepresentation];
NSString *writeToFileName = [NSString stringWithFormat:#"/Users/Desktop/%#.png", [NSDate date]];
[imageData writeToFile:writeToFileName atomically:NO];
//6) release intermediate objects
[img release];
free(buffer);
After this I send imageData for print, which works great for me.

Resources