I want am working on a project where I need to save user typed text as .PNG file through objective-c. I mean when user typed some text I give option to the user to choose font type then save it. After that the file will be saved as .PNG file without background.
How can I achieve this. Please share your views.
Thanks in advance
use this method get image from text:
-(UIImage *)imageFromText:(NSString *)text
{
// set the font type and size
//UIFont *font = [UIFont systemFontOfSize:txtView.font];
CGSize size = [text sizeWithFont:txtView.font]; // label or textview
// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
// iOS is < 4.0
UIGraphicsBeginImageContext(size);
[text drawInRect:CGRectMake(0,0,size.width,size.height) withFont:txtView.font];
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
Now u have image save like this
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir]; // any name u want for image
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; your image here
[data1 writeToFile:pngFilePath atomically:YES];
Related
In my contacts application i used an image view to display the contact persons image,
in this process while saving the data user can save the contact person image as well (in the form of string, image file name).
I copy the images in sand box (Documents directory) and save the file names of images
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
NSString *DirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[[NSUserDefaults standardUserDefaults] setValue:storedPicsDict.contactImage forKey:#"oldContactPic"];
//To SET the NEw IMAGE images from directory path
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef generatedUUIDString = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
NSString* hashKey = [(NSString*)generatedUUIDString autorelease];
self.ContactImageFilePath = [NSString stringWithFormat:#"%#/%#.png",DirectoryPath,hashKey];
storedPicsDict.contactImage = self.ContactImageFilePath;
[contactPicture setImage:image forState:UIControlStateNormal];
isNewContactImage = true;
}
[picker dismissModalViewControllerAnimated:YES];
}
the respective save image will displayed in contact's information.
But w*hen i saved few more images more than 6/7 it causes memory warnings and the and app gets crashed/slow down.*
So i need to save images with LOW RESOUTION and LOW MEMORY SIZE,
How is it possilbe, thanks
1>Save the image in jpeg format so that image size gets reduced
NSData *imgData = UIImageJPEGRepresentation(your_UIImage_to_save, 0.5);
[imgData writeToFile:path_of_doc_dir_with_image_name atomically:YES];
2>
If you want to reduce the quality and size of the image you can use this code
CGSize newSize=CGSizeMake(50,50); // I am giving resolution 50*50 , you can change your need
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Hope this will help you..
how about using this
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];
and save the smaller image to a tmp file path for uploading. Do the images need to be .png?
Otherwise, you may also try UIImageJPEGRepresentation to lower the image's quality.
the screen image link,the savePic image link,You can find the different between screenImg and savePic.
I set the backgroundImageView a very small png. and i want save the backgroundimageview to a Picture。
In the iPhone Simulator Screen, the edge of image is normal, but the edge of savePic is not clear. Anybody can tell me how to save a high definition picture.
- (void)viewDidLoad
{
[super viewDidLoad];
//_backImgView 320*480
self.backImgView.image = [UIImage imageNamed:#"Purple.png"];
[self performSelector:#selector(savePic) withObject:nil afterDelay:0.1];
}
- (void)savePic
{
BOOL isDir;
NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:#"/Documents/Pic"];
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dirPath isDirectory:&isDir]){
BOOL bo = [fm createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
if(!bo){
NSLog(#"-->Create CardSlide Dir Fail!!!");
return;
}
}
UIGraphicsBeginImageContext(_backImgView.bounds.size);
//UIGraphicsBeginImageContextWithOptions(_backImgView.bounds.size, _backImgView.opaque, 2.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
[_backImgView drawRect:_backImgView.bounds];
//[_backImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *bgImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *path = [NSString stringWithFormat:#"save_%#.jpg", #"demo"];
NSString *jpgPath = [dirPath stringByAppendingPathComponent:path];
BOOL isSucc = [UIImageJPEGRepresentation(bgImg, 1.0) writeToFile:jpgPath atomically:YES];
NSLog(#"%# write photo %#!", jpgPath, isSucc?#"SUCC":#"FAIL");
}
Using a small image, is impossible to scale it the correct way to a bigger image, you will always go through blurry, noisy images BUT if you image could have stretchable repetitive parts, you can stretch the interior of the image without creating a new one. There are two API in UIImage called:
– resizableImageWithCapInsets: (Only ios5)
– stretchableImageWithLeftCapWidth:topCapHeight: (Deprecated in iOS 5.0)
If you find the correct inset you can avoid to create a new image, basically is the same system used to create the bubble in message application. The balloon is really small but it has a stretchable area that maintain the aspect ratio.
Since the image is really simple you could also think to draw it using Quartz functions creating a rect path, paths are "almost" res independent just need to scale them the correct size.
I want to convert the contents of NSMutableArray to NSData and then convert it to pdf.
I am using following code to conver NSdata but it gives error .I have searched many article but not getting anything
myArray=[[NSMutableArray alloc]init];
[myArray addObject:#"Jamshed"];
[myArray addObject:#"Imran"];
[myArray addObject:#"Ali"];
[myArray addObject:#"Hussain"];
[myArray addObject:#"Faisal"];
for (int i=0; i<[myArray count]; i++)
{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[myArray objectAtIndex:i]];
NSLog(#"data %#",data);
//create code for pdf file for write b4 read and concatenate readed string with data to write in pdf file.
}
- (NSData*) pdfDataWithSomeText;
{
// For more on generating PDFs, see http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html
// The PDF content will be accumulated into this data object.
NSMutableData *pdfData = [NSMutableData data];
// Use the system default font.
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
// Use the default page size of 612*792.
CGRect pageRect = CGRectMake(0, 0, 612, 792);
// Use the defaults for the document, and no metadata.
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
// Create a page.
UIGraphicsBeginPDFPageWithInfo(pageRect, nil);
// Store some placeholder text.
NSString *topLine = #"PDF Sample from";
NSString *bottomLine = #"http://stackoverflow.com/q/10122216/1318452";
// Draw that placeholder text, starting from the top left.
CGPoint topLeft = CGPointZero;
CGSize lineSize = [topLine sizeWithFont:font];
[topLine drawAtPoint:topLeft withFont:font];
// Move down by the size of the first line before drawing the second.
topLeft.y += lineSize.height;
[bottomLine drawAtPoint:topLeft withFont:font];
// Close the PDF context.
UIGraphicsEndPDFContext();
// The pdfData object has now had a complete PDF file written to it.
return pdfData;
}
Writing strings to a PDF is not as simple as generating NSData from those strings. Look at the Drawing and Printing Guide for iOS - Generating PDF Content. Yes, it is a big document. Read it. Try the examples from it. Try adding your own strings to their example. Then, if you have something that almost works, come back here to ask about it.
Generating the PDF
So here is the code from the link above, made even simpler by drawing with NSString instead of Core Text. It draws the input array, but will probably need to some better arithmetic. Can you make it draw in a more structured way?
- (NSData*) pdfDataWithStrings:(NSArray*) strings;
{
// For more on generating PDFs, see http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html
strings = [strings arrayByAddingObject:#"https://stackoverflow.com/q/10122216/1318452"];
// The PDF content will be accumulated into this data object.
NSMutableData *pdfData = [NSMutableData data];
// Use the system default font.
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
// Use the default page size of 612*792.
CGRect pageRect = CGRectMake(0, 0, 612, 792);
// Use the defaults for the document, and no metadata.
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
// Create a page.
UIGraphicsBeginPDFPageWithInfo(pageRect, nil);
// Add the strings within the space of the pageRect.
// If you want to draw the strings in a column or row, in order, you will need to change this bit.
for (NSString *line in strings)
{
// Hint: you will still need to know the lineSize.
CGSize lineSize = [line sizeWithFont:font];
CGFloat x = pageRect.origin.x + (arc4random_uniform(RAND_MAX)/(CGFloat) RAND_MAX*(pageRect.size.width-lineSize.width));
CGFloat y = pageRect.origin.y + (arc4random_uniform(RAND_MAX)/(CGFloat) RAND_MAX*(pageRect.size.height-lineSize.height));
CGPoint lineTopLeft = CGPointMake(x, y);
// Having worked out coordinates, draw the line.
[line drawAtPoint:lineTopLeft withFont:font];
}
// Close the PDF context.
UIGraphicsEndPDFContext();
// The pdfData object has now had a complete PDF file written to it.
return pdfData;
}
Saving to the Documents Directory
To save a document, you need to find the path where the user's documents are kept:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
You will be saving a file within that path. For your final app, let the user select their own name. For this example, the name will be build into the program.
NSString *pdfFilename = #"StackOverflow.pdf";
NSString has some excellent path manipulation methods, making it easy to construct the path you will be writing to.
NSString *pdfPath = [documentsPath stringByAppendingPathComponent:pdfFilename];
Then get the data you'll be writing to that path. Here I'll call the method declared above.
NSData *pdfData = [self pdfDataWithStrings:myArray];
Write those data to the path. For a better app, you may at some point want to call [pdfData writeToFile:options:error:] so you can display anything that went wrong.
[pdfData writeToFile:pdfPath atomically:NO];
How do you know if this worked? On the simulator, you can log the path you wrote to. Open this path in the Finder, and see if it contains the PDF you expect.
NSLog(#"Wrote PDF to %#", pdfPath);
On actual devices, you can enable iTunes File Sharing. See How to enable file sharing for my app?
You ca convert into json using
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil];
Before doing like
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: myArray];
You convert array in to json string first
NSString *jsonString = [myArray JSONRepresentation];
You must Import json.h api first
myArray=[[NSMutableArray alloc]init];
[myArray addObject:#"Jamshed"];
[myArray addObject:#"Imran"];
[myArray addObject:#"Ali"];
[myArray addObject:#"Hussain"];
[myArray addObject:#"Faisal"];
for (int i=0; i<[myArray count]; i++)
{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[myArray objectAtIndex:i]];
NSLog(#"data %#",data);
//create code for pdf file for write b4 read and concatenate readed string with data to write in pdf file.
}
How might one convert a screenshot, taken on an iPhone for example, into a PDF file. It's easy enough to take the screenshot and put it into a UIImage, but it's the conversion which has me stumped. I took a look at the Quartz framework which is the only one in Xcode that I know to support the PDF format, but couldn't find anything there to make this work. Is there anything native to Xcode that I'm missing? If not, is there a public framework somewhere that could handle a conversion like this?
I figured it out. It involved saving a screenshot as a UIImage, and then using the very helpful tutorial found here to get me going with the PDF conversion. As it turns out, there are functions to handle the making of PDF documents in the Core Graphics class.
You wouldn't convert a screenshot to a pdf. You would create a screenshot, create a pdf and insert the screenshot image into the first page of the pdf.
Untested code to create image:
nameStr = [NSString stringWithFormat:#"myImage.png"];
fileManager = [NSFileManager defaultManager];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
namePath = [documentsDirectory stringByAppendingString:#"/"];
namePath = [thumbnailPath nameStr];
CGRect contextRect = CGRectMake(0, 0, 1024, 768);
UIGraphicsBeginImageContext(contextRect.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(viewImage);
UIImage *myImage = [[UIImage alloc] initWithData:data];
Untested code to add image to a pdf:
pageSize = CGSizeMake(1024, 768);
fileName = #"myFile.pdf";
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
[myImage drawInRect:CGRectMake( 0, 0, 1024, 768];
UIGraphicsEndPDFContext();
p.s. assuming ipad 1024 x 768 above
There seems to be a scatter of info on this topic, but it seems rather a muddle, so I hoe you don't mind me asking.
I have a UIImagePickerController working, letting me either take a photo or pick on from the library and then set a UIImageView of my choice to show that image taken/selected.
However, how can I firstly save the image, then load it back in when the application is reopened? Also, I will be saving multiple images so they need to be uniquely identified.
Any help will be massively appreciated, thanks.
I don't know of a way to get the Photo from the Photo Album a Second time. There does not seem to be a way to retrieve it again. We do a few things to save the Image internally.
We either convert the Image to NSData and save it in CoreData, or we save it off to our sandbox.
here is a snip of code that we use, this is doing one of a few things, I'm getting the Image from a ScreenShot, though its the same once you have the UIImage.
// go get our screenshot
UIImage* screenShot = [self createScreenShotThumbnailWithWidth:200];
// Save screen shot as a png in the documents directory with the UUID of the IoCDScreen
// Saving to Sandbox
[self saveImage:screenShot withName:currentScreen.itemUUID];
// save image to Photo Album - though you can't get a ref back to it
UIImageWriteToSavedPhotosAlbum(screenShot, self, nil, nil);
//convert our screen shot PNG to NSData and store it in a CoreData Managed Object
currentScreen.screenImageDevelopment = [NSData dataWithData: UIImagePNGRepresentation( screenShot )];
Helper Functions used above
//--------------------------------------------------------------------------------------------------------
// saveImage:withName:
// Description: Save the Image with the name to the Documents folder
//
//--------------------------------------------------------------------------------------------------------
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//grab the data from our image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//get a path to the documents Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Add out name to the end of the path with .PNG
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", name]];
//Save the file, over write existing if exists.
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
//--------------------------------------------------------------------------------------------------------
// createScreenShotThumbnailWithWidth
// Description: Grab a screen shot and then scale it to the width supplied
//
//--------------------------------------------------------------------------------------------------------
-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
// Size of our View
CGSize size = self.view.bounds.size;
//First Grab our Screen Shot at Full Resolution
UIGraphicsBeginImageContext(size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Calculate the scal ratio of the image with the width supplied.
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = width / size.width;
} else {
ratio = width / size.height;
}
//Setup our rect to draw the Screen shot into
CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
//Scale the screenshot and save it back into itself
UIGraphicsBeginImageContext(rect.size);
[screenShot drawInRect:rect];
screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Send back our screen shot
return screenShot;
}