Image getting bigger after saving it - ios

I would be grateful if anyone could help me to solve an issue with image saving.
I've got an app which contains recipes with corresponding images. I need to resize them in order to preserve memory and make my app more robust. Everything looks ok the UIImage has proper dimensions. But when I save this image to Documents it appears to become something like twice bigger than it should be.
The code I use for image resizing:
+(UIImage *) createImageFromImage: (UIImage *)image WithName:(NSString *)name Thumbnail: (BOOL)isThumbnail{
CGSize oldSize = image.size;
CGSize newSize;
CGFloat scaleFactor;
if (isThumbnail) {
name = [NSString stringWithFormat:#"t_%#", name];
newSize = CGSizeMake(125, 92);
}
else{
newSize = CGSizeMake(320, 240);
}
if (!CGSizeEqualToSize(newSize, oldSize)) {
CGFloat widthFactor = newSize.width/oldSize.width;
CGFloat heightFactor = newSize.height/oldSize.height;
if (((widthFactor > heightFactor)||(heightFactor > 1))&&(widthFactor < 1)) {
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
newSize.width = scaleFactor*oldSize.width;
newSize.height = scaleFactor*oldSize.height;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *newImage = nil;
newImage = [self drawImage:image InContextWithSize:newSize];
[UIImagePNGRepresentation(newImage) writeToFile:path atomically:YES];
return newImage;
}
+(UIImage *)drawImage: (UIImage *)image InContextWithSize: (CGSize) newSize {
UIImage *newImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

I have just changed few lines of code to get scaleFactor
-(UIImage *) createImageFromImage: (UIImage *)image WithName:(NSString *)name Thumbnail: (BOOL)isThumbnail{
CGSize oldSize = image.size;
CGSize newSize;
CGFloat scaleFactorForWidth = 0.0,scaleFactorForHeight= 0.0;
if (isThumbnail) {
name = [NSString stringWithFormat:#"t_%#", name];
newSize = CGSizeMake(125, 92);
}
else{
newSize = CGSizeMake(320, 240);
}
if (!CGSizeEqualToSize(newSize, oldSize)) {
CGFloat widthFactor = newSize.width/oldSize.width;
CGFloat heightFactor = newSize.height/oldSize.height;
if (widthFactor != 1) {
scaleFactorForWidth = widthFactor;
newSize.width = scaleFactorForWidth*oldSize.width;
}
if (heightFactor != 1) {
scaleFactorForHeight = heightFactor;
newSize.height = scaleFactorForHeight*oldSize.height;
}
}
NSLog(#"New Size : (%f,%f)",newSize.width,newSize.height);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *newImage = nil;
newImage = [self drawImage:image InContextWithSize:newSize];
[UIImagePNGRepresentation(newImage) writeToFile:path atomically:YES];
return newImage;
}

The issue appeared to deal with the standard Xcode PNG compression option. One just needs to set it to NO if he doesn't wan't this to happen. I guess that this was made for the sake of retina displays.

Related

I want to create a PDF file but not save in the device

I am a new iOS developer. I want to complete create a PDF file but problem is that the PDF file does not save in device. When I open the PDF in click open button rather than than display, it is not stored in the original device.
Here is my code.
#import "MTViewController.h"
#define kPadding 20
#interface MTViewController ()
{
CGSize _pageSize;
}
#end
#implementation MTViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)didClickOpenPDF {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"NewPDF.pdf"];
if([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) {
ReaderDocument *document = [ReaderDocument withDocumentFilePath:pdfPath password:nil];
if (document != nil)
{
ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
readerViewController.delegate = self;
readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:readerViewController animated:YES];
}
}
}
- (IBAction)didClickMakePDF {
[self setupPDFDocumentNamed:#"NewPDF" Width:850 Height:1100];
[self beginPDFPage];
NSString *test=#"jigar";
NSString *test1=#"ravi";
CGRect textRect = [self addText:[NSString stringWithFormat:#"%#%#",test,test1]
withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f];
CGRect blueLineRect = [self addLineWithFrame:CGRectMake(kPadding, textRect.origin.y + textRect.size.height + kPadding, _pageSize.width - kPadding*2, 4)
withColor:[UIColor blueColor]];
UIImage *anImage = [UIImage imageNamed:#"tree.jpg"];
CGRect imageRect = [self addImage:anImage
atPoint:CGPointMake((_pageSize.width/2)-(anImage.size.width/2), blueLineRect.origin.y + blueLineRect.size.height + kPadding)];
[self addLineWithFrame:CGRectMake(kPadding, imageRect.origin.y + imageRect.size.height + kPadding, _pageSize.width - kPadding*2, 4)
withColor:[UIColor redColor]];
[self finishPDF];
}
- (void)setupPDFDocumentNamed:(NSString*)name Width:(float)width Height:(float)height {
_pageSize = CGSizeMake(width, height);
NSString *newPDFName = [NSString stringWithFormat:#"%#.pdf", name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
// NSString *resourceDocPath = [[NSString alloc] initWithString:[
// [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
// stringByAppendingPathComponent:#"Documents"]];
//
// NSString *filePath = [resourceDocPath
// stringByAppendingPathComponent:#"myPDF.pdf"];
// [newPDFName writeToFile:filePath atomically:YES];
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
}
- (void)beginPDFPage {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width, _pageSize.height), nil);
}
- (void)finishPDF {
UIGraphicsEndPDFContext();
}
- (CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize {
UIFont *font = [UIFont systemFontOfSize:fontSize];
CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(_pageSize.width - 2*20-2*20, _pageSize.height - 2*20 - 2*20) lineBreakMode:UILineBreakModeWordWrap];
float textWidth = frame.size.width;
if (textWidth < stringSize.width)
textWidth = stringSize.width;
if (textWidth > _pageSize.width)
textWidth = _pageSize.width - frame.origin.x;
CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
[text drawInRect:renderingRect
withFont:font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
return frame;
}
- (CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(currentContext, color.CGColor);
// this is the thickness of the line
CGContextSetLineWidth(currentContext, frame.size.height);
CGPoint startPoint = frame.origin;
CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);
CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathFillStroke);
return frame;
}
- (CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point {
CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[image drawInRect:imageFrame];
return imageFrame;
}
- (void)dismissReaderViewController:(ReaderViewController *)viewController {
[self dismissModalViewControllerAnimated:YES];
}

Converting a UIWebView to PDF/Image gives only one inch wide output

I'm converting a UIWebView to pdf/image with the help of the following code:
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"];
int height = [heightStr intValue];
CGFloat screenHeight = webView.bounds.size.height;
int pages = ceil(height / screenHeight);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
CGRect frame = [webView frame];
NSMutableArray *imageArray= [[NSMutableArray alloc]init];
for (int i = 0; i < pages; i++)
{
// Check to screenHeight if page draws more than the height of the UIWebView
if ((i+1) * screenHeight > height)
{
CGRect f = [webView frame];
f.size.height -= (((i+1) * screenHeight) - height);
[webView setFrame: f];
}
UIGraphicsBeginImageContext(frame.size);
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
[webView.layer renderInContext:currentContext];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
[imageArray insertObject:viewImage atIndex:imageArray.count] ;
UIGraphicsEndImageContext();
}
UIGraphicsEndPDFContext();
[webView setFrame:frame];
//Send all images
NSData *imgData = [self blendImages:imageArray];
//Final Image
UIImage *finalImage = [UIImage imageWithData:imgData];
-(NSData*)blendImages:(NSMutableArray *)arrImage{
// get data from document
CGFloat height=0 ,width=0 ;
UIImage *tempImg = [arrImage objectAtIndex:0] ;
width =tempImg.size.width ;
for (int i = 0 ; i<arrImage.count ; i++){
UIImage *img= [arrImage objectAtIndex:i];
height = img.size.height +height;
}
CGSize size = CGSizeMake(width, height) ;
UIGraphicsBeginImageContext(size);
CGFloat h = 0;
for (int i=0; i<arrImage.count; i++) {
UIImage* uiimage = [arrImage objectAtIndex:i];
[uiimage drawAtPoint:CGPointMake(0, h) blendMode:kCGBlendModeNormal alpha:1.0];
h = uiimage.size.height +h ;
}
NSData *imageData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
UIGraphicsEndImageContext();
return imageData;
}
But I'm getting only one inch wide output. Also the whole contains fits in one page and make it unreadable. How to make A4 sized output?
This creates a PDF of a screenshot of a webpage - might help get you started :)
- (IBAction)makePDF:(id)sender
{
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, webView.scrollView.opaque, 0.0);
webView.scrollView.contentOffset = CGPointZero;
webView.scrollView.frame = CGRectMake(0, 0, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height);
[webView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect imageFrame = CGRectMake(0, 0, image.size.width, image.size.height);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, imageFrame, nil);
//full screenshot
UIGraphicsBeginPDFPage();
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setImage:image];
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndPDFContext();
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf",[NSDate date]];
NSString *path = [documentDirectory stringByAppendingPathComponent:fileName];
// save to disk
[pdfData writeToFile:path atomically:YES];
NSLog(#"pdf in %#", path);
}

How to generate a pdf with multiple pages ios7?

According to my application i have created Pdf file but i need to generate Pdf with multiple pages?This is the code which i used for generating pdf.
-(void)drawPDF
{
pagesize = CGSizeMake(612, 792);
NSString *fileName = #"Report.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[self generatePdfWithFilePath:pdfFileName];
}
-(void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
//Start a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pagesize.width, pagesize.height), nil);
//Draw text fo our header.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);
UIFont *font = [UIFont systemFontOfSize:14.0];
int xOrigin = 20;
int yOrigin = 300;
int rowHeight = 50;
int columnWidth = 140;
int numberOfRows = 7;
int numberOfColumns = 4;
[self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns];
[self drawImageAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth];
[self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:allinfo];
// [self drawTextAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth];
CGSize stringSize = [contents_for_pdf sizeWithFont:font constrainedToSize:CGSizeMake(pagesize.width - 2*kBorderInset-2*kMarginInset, pagesize.height - 2*kBorderInset - 2*kMarginInset) lineBreakMode:NSLineBreakByWordWrapping];
CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pagesize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);
[contents_for_pdf drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
UIGraphicsEndPDFContext();
}
You can see this link for generating pdf in ios
http://www.raywenderlich.com/6818/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial
Also in your code use your [array count+1] for number of rows

Resize an Image Inside a UIImage before saving in directory

I have this code which gets the image inside my UIImage (connected with IB called 'c1_1') and should save in my directory folder:
IBOutlet UIImageView *c1_1;
if (c1_1.image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/ImagensApp/ImagensClientes/%#_%#_Cliente.jpg",list[0],abc]];
NSData* data = UIImageJPEGRepresentation(c1_1.image, 70);
[data writeToFile:path atomically:YES];
}
This code works, but I want to resize the image to scale 200x200, how I can do this before saving?
Scaling an image is just a few lines of code that
creates a memory bitmap
draws the image into that bitmap
and then gets the new image from the bitmap
like this
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake( 0, 0, newSize.width, newSize.height )];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return( result );
}

Convert multiple images as pdf with multiple page

In my application there is a WebView with HTML contents. Contents is of 3 page in WebView .
Now i want to convert WebView content in PDF. I have created 3 image from the WebView content. Now i want to create pdf using these 3 image. Each image should one page of PDF. But it resulting as single page image. So when i am taking print then content is cut off.
I am using this,
CGSize pageSize = CGSizeMake(612, 2324);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();
What i am doing wrong with this code.
THanks
/*For call method*/
[self createPdfWithName:#"sam" array:[NSArray arrayWithObjects:[UIImage imageNamed:#"01.png"],[UIImage imageNamed:#"02.png"], nil]];
/*Create New Pdf*/
- (NSString *)createPdfWithName: (NSString *)name array:(NSArray*)images
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSString *pdfFileName = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf",name]];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
for (int index = 0; index <[images count] ; index++)
{
UIImage *pngImage=[images objectAtIndex:index];;
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height)), nil);
[pngImage drawInRect:CGRectMake(0, 0, (pngImage.size.width), (pngImage.size.height))];
}
UIGraphicsEndPDFContext();
return pdfFileName;
}
func createPDFS(arrImages: [UIImage]) -> NSData? {
var pageHeight = 0.0
var pageWidth = 0.0
for img in arrImages
{
pageHeight = pageHeight+Double(img.size.height)
if Double(img.size.width) > pageWidth
{
pageWidth = Double(img.size.width)
}
}
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: pageWidth, height: pageHeight)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
for img in arrImages
{
var mediaBox2 = CGRect.init(x: 0, y: 0, width: img.size.width, height: img.size.height)
pdfContext.beginPage(mediaBox: &mediaBox2)
pdfContext.draw(img.cgImage!, in: CGRect.init(x: 0.0, y: 0, width: pageWidth, height: Double(img.size.height)))
pdfContext.endPage()
}
return pdfData
}
CGSize pageSize = CGSizeMake(612, 2324);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", index]];
UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
// TODO: See Here
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pngImage.size.height), nil);
[pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
//currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();

Resources