WebView to TIFF representation - image

I'm trying to capture the contents of a WebView and saving it as an image. This is my code right now (cv is the web view):
[cv lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[cv bounds]];
[cv unlockFocus];
NSData *data = [rep TIFFRepresentation];
[data writeToFile:[[save URL] path] atomically:NO];
All I get is a gray image with the correct size. What am I doing wrong?

I don't think you are using correctly NSBitmaImageRep.
Have a look at this post for a couple of ways of doing what you are trying to. Possibly the only one that is working for a web view (which is quite a complex beast) is the screenshot+crop approach.

Related

Is it possible to re-size a image in a uipasteboard xcode 7.2 Objective C?

I’m currently using this code bellow in Xcode 7.2, which takes the image and pastes it in imessages etc. But it’s too large (in dimensions). Is it possible to make this image smaller?
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSData *imgData = UIImagePNGRepresentation(image);
[pasteboard setData:imgData forPasteboardType:[UIPasteboardTypeListImage objectAtIndex:0]];
Not whilst it's in the pasteboard. BUT, if you're worried about it being the wrong size when you paste it somewhere, FEAR NOT, Apple have been kind to us and have built quite a lot of the presentation "resizing" into things for us.
What you need to do if you really HAVE to resize the image is:
1) Be lazy and use code which you can resume... i.e. I found this on here I believe:
- (NSImage *)imageResize:(NSImage*)anImage newSize:(NSSize)newSize {
NSImage *sourceImage = anImage;
[sourceImage setScalesWhenResized:YES];
// Report an error if the source isn't a valid image
if (![sourceImage isValid]){
NSLog(#"Invalid Image");
} else {
NSImage *smallImage = [[NSImage alloc] initWithSize: newSize];
[smallImage lockFocus];
[sourceImage setSize: newSize];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[sourceImage drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, newSize.width, newSize.height) operation:NSCompositeCopy fraction:1.0];
[smallImage unlockFocus];
return smallImage;
}
return nil;
}
then in the bit of code which you've given us:
*pasteboard = [UIPasteboard generalPasteboard];
NSImage *myShinyResizedImage = [self imageResize: oldImage newSize: CGSizeMake(100.0, 100.0)];
NSData *imgData = UIImagePNGRepresentation(myShinyResizedImage);
[pasteboard setData:imgData forPasteboardType:[UIPasteboardTypeListImage objectAtIndex:0]];
And it's been resized before if goes off to get pasted elsewhere.

MacOS: Programmatically add some text to an image?

I'm converting some code from linux to mac.
How can I programatically overlay an image with text, similar to the ImageMagick convert command? For various reasons I can't depend on having ImageMagick installed.
convert -draw 'text 50,800 "hello world"' f1.png f2.png
You can use the NSImage and NSString drawing APIs to create the edited image, and then use NSBitmapImageRep to get PNG data for the image. Example:
NSString *text = #"hello world";
NSImage *f1 = [[NSImage alloc] initWithContentsOfFile:#"/path/to/f1.png"];
NSImage *f2 = [NSImage imageWithSize:f1.size flipped:YES drawingHandler:^BOOL(NSRect dstRect) {
[f1 drawInRect:dstRect];
// Attributes can be customized to change font, text color, etc.
NSDictionary *attributes = #{NSFontAttributeName: [NSFont systemFontOfSize:17]};
[text drawAtPoint:NSMakePoint(50, 800) withAttributes:attributes];
return YES;
}];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:[f2 CGImageForProposedRect:NULL context:nil hints:nil]];
NSData *data = [rep representationUsingType:NSPNGFileType properties:nil];
[data writeToFile:#"/path/to/f2.png" atomically:YES];

Xcode save and load image in Xcode iOS

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. Thanks so much!
Here is my save code:
-(IBAction)save123456 {
NSBitmapImageRep *rep;
NSData *data;
NSImage *noteview;
[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];
}
And my load:
-(IBAction)load123456 {
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
}
I get so many error codes in my save. My image is called noteview. Thanks!!
Try use instead
[data writeToFile: #"asd.png" atomically: NO];
a code line
[data writeToFile: #"asd.png" atomically: YES];
Some open source examples:
AGSimpleImageEditorView
image editors in iOS
projects with work with Pictures

Convert PDF pages to images with COCOA

I am having problem with PDF conversion to images. I would like to create an image file for every page in PDF document.
This is the code I am using and works fine. Every page gets converted into the image, but I have problem with image resolution. I don't know how to set the resolution of the output images. Can someone help me out?
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost/test/test.pdf"]];
NSPDFImageRep *img = [NSPDFImageRep imageRepWithData:pdfData];
NSFileManager *fileManager = [NSFileManager defaultManager];
int count = [img pageCount];
for(int i = 0 ; i < count ; i++) {
[img setCurrentPage:i];
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:#"Page_%d.jpg", [img currentPage]];
[fileManager createFileAtPath:[NSString stringWithFormat:#"%#/%#", #"/Users/mac/Desktop/", pageName] contents:finalData attributes:nil];
}
Thanks a lot!
Since NSPDFImageRep is a subclass of NSImageRep, couldn't you use the [NSImageRep drawInRect:] method?
Link: http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSImageRep_Class/Reference/Reference.html#//apple_ref/doc/uid/20000346-drawInRect_
The simplest way would be to use the ImageIO framework. Feed the PDF data to an image source to get a CGImage; feed that object to an image destination to generate (and optionally save in the same step) the JPEG data. In the latter step, you can specify the resolution among the image properties; see “Individual Image Properties” in the documentation.
Don't forget to finalize your destination. It's vital.

Strange artifacts after CILanczosScaleTransform

I'm trying to do image scaling using Core Image, using Lanczos Scale Transform filter.
It is fine when I'm doing scaleup. But on scaledown and saving to JPEG I found a class of images which produces strange noise artifacts and behavior.
For inputScale multiples to 0.5: 0.5, 0.25, 0.125 etc it is always fine.
For others inputScale values,it's broken.
When I'm saving to TIFF,PNG,JPEG2000 or draw on screen - it's fine.
When I'm saving to JPG or BMP - it's broken.
I uploaded sample images:
(original, 4272x2848, 3.4Mb)
[http://www.zoomfoot.com/get/package/517e2423-7795-4239-a166-03d507ec51d8]
(scaled with noise, 1920x1280, 2.2Mb)
[http://www.zoomfoot.com/get/package/6eb64d33-3a30-4e8d-9953-67ce1e7d7ef9]
It also, pretty good reproducible on 'sunset' images.
I've tried couple more ways to scale images. Using CIAffineTransform and drawing using NSImage itself. Both provides results without any noise.
Here is the code I was using for scaling & saving:
================= Lanczos ==============
- (NSImage *) scaleLanczosImage:(NSString *)path
Width:(int) desiredWidth
Height:(int) desiredHeight
{
CIImage *image=[CIImage imageWithContentsOfURL:
[NSURL fileURLWithPath:path]];
CIFilter *scaleFilter = [CIFilter filterWithName:#"CILanczosScaleTransform"];
int originalHeight=[image extent].size.height;
int originalWidth=[image extent].size.width;
float yScale=(float)desiredHeight / (float)originalHeight;
float xScale=(float)desiredWidth / (float)originalWidth;
float scale=fminf(yScale, xScale);
[scaleFilter setValue:[NSNumber numberWithFloat:scale]
forKey:#"inputScale"];
[scaleFilter setValue:[NSNumber numberWithFloat:1.0]
forKey:#"inputAspectRatio"];
[scaleFilter setValue: image
forKey:#"inputImage"];
image = [scaleFilter valueForKey:#"outputImage"];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCIImage:image];
NSMutableDictionary *options=[NSMutableDictionary dictionaryWithObject:[NSDecimalNumber numberWithFloat:1.0]
forKey:NSImageCompressionFactor];
[options setValue:[NSNumber numberWithBool:YES] forKey:NSImageProgressive];
NSData* jpegData = [rep representationUsingType:NSJPEGFileType
properties:options];
[jpegData writeToFile:#"/Users/dmitry/tmp/img_4389-800x600.jpg" atomically:YES];
}
================= NSImage ==============
- (void) scaleNSImage:(NSString *)path
Width:(int) desiredWidth
Height:(int) desiredHeight
{
NSImage *sourceImage = [[NSImage alloc] initWithContentsOfFile:path];
NSImage *resizedImage = [[NSImage alloc] initWithSize:
NSMakeSize(desiredWidth, desiredHeight)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, desiredWidth, desiredHeight)
fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height)
operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSMutableDictionary *options=[NSMutableDictionary dictionaryWithObject:[NSDecimalNumber numberWithFloat:1.0]
forKey:NSImageCompressionFactor];
[options setValue:[NSNumber numberWithBool:YES] forKey:NSImageProgressive];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithData:[resizedImage TIFFRepresentation]];
NSData* jpegData = [rep representationUsingType:NSJPEGFileType
properties:options];
[jpegData writeToFile:#"~/nsimg_4389-800x600.jpg" atomically:YES];
}
If anyone can explain or suggest something here, i'm really appreciate this.
Thanks.
There are some quirks with scaling with CIImage. Will this post by Dan Wood help?
My understanding is that due to its nature, the hardware Core Image renderer has some odd quirks when rendering for anything but on-screen display. So, you are recommended to use the software renderer for other situations.
http://developer.apple.com/mac/library/qa/qa2005/qa1416.html
That's definitely a CoreImage bug. File it at bugreport.apple.com

Resources