desktop wallpaper [duplicate] - cocoa

I am trying to change the desktop image; the procedure I've come up with is below. The first time this code is run, the resized image is displayed on screen as wallpaper, but the next time there is no reaction. What am I doing wrong?
-(IBAction)click:(id)sender
{
NSData *sourceData;
NSError *error;
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
screenArray = [NSScreen screens];
screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
screenz = [screenArray objectAtIndex: index];
screenRect = [screenz visibleFrame];
}
NSLog(#"%fx%f",screenRect.size.width, screenRect.size.height);
arrCatDetails = [strCatDetails componentsSeparatedByString:appDelegate.strColDelimiter];
NSString *imageURL = [NSString stringWithFormat:#"upload/product/image/%#_%#_%d.jpg",[arrCatDetails objectAtIndex:0],appDelegate.str104by157Name,iSelectedImgIndex];
NSString *ima = [imageURL lastPathComponent];
NSString *str = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *dataFilePath = [str stringByAppendingPathComponent:ima];
NSString *imagePath = [NSString stringWithFormat:#"file://localhost%#",dataFilePath];
NSURL *url = [[NSURL alloc] init];
url = [NSURL URLWithString:imagePath];
sourceData = [NSData dataWithContentsOfURL:url];
sourceImage = [[NSImage alloc] initWithData: sourceData];
resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(screenRect.size.width, screenRect.size.height)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, screenRect.size.width, screenRect.size.height) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep imageRepWithData:resizedData];
newimage = #"editwall.jpg";
newFilePath = [str stringByAppendingPathComponent:newimage];
NSData* theImageData = [theImageRepresentation representationUsingType:NSJPEGFileType properties:nil];
[theImageData writeToFile: newFilePath atomically: YES];
if([filemgr fileExistsAtPath:newFilePath] == YES)
{
imagePath1 = [NSString stringWithFormat:#"file://localhost%#",newFilePath];
urlz = [NSURL URLWithString:imagePath1];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:nil, NSWorkspaceDesktopImageFillColorKey, [NSNumber numberWithBool:NO], NSWorkspaceDesktopImageAllowClippingKey, [NSNumber numberWithInteger:NSImageScaleProportionallyUpOrDown], NSWorkspaceDesktopImageScalingKey, nil];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:urlz forScreen:[[NSScreen screens] lastObject] options:options error:&error];
}
else
{
NSLog(#"No");
}
[sourceImage release];
[resizedImage release];
}

Why not try -[NSWorkspace setDesktopImageURL:forScreen:options:error:]? Apple has a sample project called DesktopImage to give you some idea how to use it.
Edit (after reading your code more carefully):
The problem you're having may be because of your call to +[NSDictionary dictionaryWithObjectsAndKeys:] See the nil at the end of the list of arguments? That's how you tell NSDictionary that your argument list is done. You can't put nil in the list, because it will stop reading the list at that point. If you want to specify a key that has no value, you have to use [NSNull null].
An aside: you've got a memory management issue in your code:
// allocates memory for an NSURL
NSURL * url = [[NSURL alloc] init];
// allocates more memory for an NSURL, and leaks
// the earlier allocation
url = [NSURL URLWithString:imagePath];
Just do one or the other:
// If you do it this way, you will have to call
// [url release] later
NSURL * url = [[NSURL alloc] initWithString:imagePath];
// This memory will be released automatically
NSURL * otherUrl = [NSURL URLWithString:imagePath];

Related

Cannot apply filter to image

I need to apply CIZoomBlur with default values to image. I'm doing it with the following code:
NSURL * url = [NSURL fileURLWithPath: #"galaxy.png"];
CIImage * image = [CIImage imageWithContentsOfURL: url];
CIContext *context = [[CIContext alloc] init];
CIFilter *filter = [CIFilter filterWithName:#"CIZoomBlur"];
[filter setValue:image forKey:kCIInputImageKey];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGRect extent = [result extent];
CGImageRef cgImage = [context createCGImage:result fromRect:extent];
NSImage *image2 = [[NSImage alloc] initWithCGImage:cgImage size:NSSizeFromCGSize(CGSizeMake(640, 1136))];
self.imageView.image = image2;
In log I can see:
/SourceCache/CoreImage/CoreImage-9.2.8/API/CIFilter.mm:594: CIZoomBlur apply:: Caught exception: CIZoomBlur: id: nil value for argument #0 (src)
Image is located inside project. Any ideas?
The right code is:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"galaxy" ofType:#"png"];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
CIImage * image = [CIImage imageWithData:data];
CIContext *context = [[CIContext alloc] init];
CIFilter *filter = [CIFilter filterWithName:#"CIZoomBlur"];
[filter setValue:image forKey:kCIInputImageKey];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGRect extent = [result extent];
CGImageRef cgImage = [context createCGImage:result fromRect:extent];
NSImage *image2 = [[NSImage alloc] initWithCGImage:cgImage size:NSSizeFromCGSize(CGSizeMake(640, 1136))];
self.imageView.image = image2;
If the file is located within the app bundle then using NSURL fileURLWithPath will not locate it. The image must be nil. Thanks to trojanfoe

How to take a screenshot when a webview finished rending

I want to take a screenshot when a webview finished rending.The follow is my code:
-(void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
if (frame != [sender mainFrame]) {
return;
}
NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:[sender bounds]] autorelease];
if (rep){
NSImage *img = [[NSImage alloc] initWithData:[rep TIFFRepresentation]];
NSData* imgData = [img TIFFRepresentation];
NSArray* deskTopArrayPaths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString* deskTopPath = [deskTopArrayPaths objectAtIndex:0];
NSString* pngPath = [NSString stringWithFormat:#"%#/SaveWebPage.png",deskTopPath];
[[NSFileManager defaultManager] createFileAtPath:pngPath contents:imgData attributes:nil];
}
}
The normal image is that:
But my image is this:
Anyone tell me why and how could i improve this situation! Thank u!

How to save and load a picture in Xcode

Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3.
NSImageView is what your looking for.
This contains info on saving the file (look at the answer with code): Implement drag from NSImageView and save image to a file
The Code:
-(IBAction)saveImageButtonPushed:(id)sender
{
NSBitmapImageRep *rep;
NSData *data;
NSImage *image;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
//......
#end
To load an image:
The Code:
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate *date = [[NSDate date] dateByAddingTimeInterval:1];
profile_img = [NSString stringWithFormat:#"%#.png",[dateFormatter stringFromDate:date]];
[profile_img retain];
NSLog(#"formattedDateString: %#",profile_img);
NSData *imageToUpload = UIImagePNGRepresentation(Img_View.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerPath]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"Upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:profile_img mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject)
{
NSString *response = [operation2 responseString];
NSLog(#"response: [%#]",response);
NSString *post = [NSString stringWithFormat:#"Images=%#",profile_img];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Gallery.php",ServerPath]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"POST"];
NSLog(#"%#", post);
[request1 setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *responseString = [[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding] autorelease];
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",responseString);
if([responseString isEqualToString:#"Entered data successfully"])
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Image Share" message:#"Image Share SuccessFully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
else
{
}
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"error: %#", [operation2 error]);
}];
[operation2 start];

How do I convert an annotated PDF to an image?

I have an annotated PDF and want to convert it to image. The pdf is successfully getting converted to an image but annotations are missing in the conversion.
This is the code:
NSPDFImageRep *img = [NSPDFImageRep imageRepWithContentsOfFile:PdfFilePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
[img setCurrentPage:0];
NSImage *temp = [[NSImage alloc] init];
[temp addRepresentation:img];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:#"Page1_%d.jpeg", 0];
NSString *imgFilePath = [NSString stringWithFormat:#"%#/%#",#"/Users/Desktop/PDFImages", pageName];
[fileManager createFileAtPath:imgFilePath contents:finalData attributes:nil];
Is there a different way to store the annotated pdf to image?
The issue is resolved using image lock and unlock feature.
NSSize pageBounds1;
pageBounds1 = [page1 boundsForBox: [_pdfView displayBox]].size;
NSImage *temp = [[NSImage alloc] initWithSize:pageBounds1];
[temp lockFocus];
[page1 drawWithBox:kPDFDisplayBoxMediaBox];
[temp unlockFocus];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:#"Page1_%d.jpg", pageIndex];
NSString *imgFilePath = [NSString stringWithFormat:#"%#/%#",pathForImages, pageName];
[fileManager createFileAtPath:imgFilePath contents:finalData attributes:nil];

How to add a jpg or png image to an UIImage and then display in a UIImageView?

UIImage *img = [[UIImage alloc] initWithContentsOfFile:#"contactHeader.png"];
_headersView = [[UIImageView alloc] initWithImage:img];
I have already hooked up the connections for the UIImageView (_headersView) in IB. The image I want to load is in my project tree structure as well.
Am I creating the UIImage the right way?
If the file is in your bundle you can just use
UIImage *img = [UIImage imageNamed:#"contactHeader"];
_headersView = [[UIImageView alloc] initWithImage:img];
If the image is in your documents directory you can use
// Get the path to your documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Add the file to the end of the documents path
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"contactHeader.png"];
UIImage *img = [[UIImage alloc] imageWithContentsOfFile:filePath];
_headersView = [[UIImageView alloc] initWithImage:img];
[img release]; img = nil;
try this
-(NSString *)getPath:(NSString *)filename
{
self.path = [[NSBundle mainBundle]pathForResource:filename ofType:#"png"];
return path;
path = nil;
}
self.youImageView.image = [UIImage imageWithContentsOfFile:[self getPath:#"123"]];

Resources