How to convert data to JPEG format? - objective-c

I have this code:
NSImage * strImage = [[NSImage alloc]initWithContentsOfFile:ImageFilePath] ;
NSData *imageData = [strImage TIFFRepresentation];
What I require is to convert imageData into JPEG format. I want this to work the same as QImage save() does.
So that you can see how save() works, I will give you a link:
http://doc.qt.nokia.com/4.6/qimage.html#save
Please help me.

From CocoaDev... If you do anything with the NSImage after creating it:
NSData *imageData = [image TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSNumber *compressionFactor = [NSNumber numberWithFloat:0.9];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:compressionFactor
forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:filename atomically:YES];
If you don't really do anything else with the NSImage before:
NSArray *representations = [myImage representations];
NSNumber *compressionFactor = [NSNumber numberWithFloat:0.9];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:compressionFactor
forKey:NSImageCompressionFactor];
NSData *bitmapData = [NSBitmapImageRep representationOfImageRepsInArray:representations
usingType:NSJPEGFileType
properties:imageProps];
[bitmapData writeToFile:filename atomically:YES];

Related

Get UIImage from PHAsset (or assets-library://)

I'm trying to generate a UIImage from a PHAsset or assets-library. My code is this:
NSString *path = [self.options valueForKey:#"path"];
NSURL *localurl = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:localurl];
UIImage *image = [[UIImage alloc] initWithData:data];
But the UIImage is nil. I can set the path to be ph:// or assets-library://.
Thanks!
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:NO]];
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
NSMutableArray *arrPhassets=[[NSMutableArray alloc]init];
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//here you will get phassets of images from the device photo library.you have to store it in the mutable array like this.
[arrPhassets addObject:asset];
}];
//here you will have array of phassets for images.
//now we will extract image from the phasset for one phasset.
PHAsset *as1=arrPhassets[0];
PHCachingImageManager *imagemanager=[[PHCachingImageManager alloc]init];
[imagemanager requestImageForAsset:as1 targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//here "result" is the image for asset as1.
UIImage *image=result;
}];

memory leaks issue while saving images to directory

Please try to understand my question.
i am picking images from phone library and saving into Documents Directory. But When I pick large number of images the utilised memory increases gradually and reach above of 400 mb then my app crash. Please if anybody can solve my problem what should I do? I'm new comer to Objective C. Any response will be appreciated.
here is my code
when Picker finish picking
- (void)agImagePickerController:(AGImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info {
[self ShowLoadingView:#"Files Are Loading...."];
[self performSelectorInBackground:#selector(saveAllSelectedImages:) withObject:info];}
and then I save images to Directory
-(void) saveAllSelectedImages:(NSArray*)imagesArray{
for (int i=0; i<imagesArray.count; i++) {
ALAsset *asset = [imagesArray objectAtIndex:i];
ALAssetRepresentation *alassetRep = [asset defaultRepresentation];
NSDate *currentDate = [NSDate date];
NSString* DucPath = [[AppDelegate GetDocumentDirectoryPath] stringByAppendingPathComponent:#"Media"];
if (![[NSFileManager defaultManager] fileExistsAtPath:DucPath])
[[NSFileManager defaultManager] createDirectoryAtPath:DucPath withIntermediateDirectories:NO attributes:nil error:nil];
if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
{
long long DataSize = [alassetRep size];
Byte *buffer = (Byte*)malloc(DataSize);
NSUInteger buffered = (NSUInteger)[alassetRep getBytes:buffer fromOffset:0.0 length:alassetRep.size error:nil];
NSData *videoData = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
NSString* newVideoName = [NSString stringWithFormat:#"video_%d_%d.mov",(int)currentDate,i];
NSString* newVideoPath = [DucPath stringByAppendingPathComponent:newVideoName];
[videoData writeToFile:newVideoPath atomically:YES];
[pImageMediaArray addObject:newVideoName];
}
else
{
UIImage *image = [UIImage imageWithCGImage:[alassetRep fullResolutionImage]];
/************************************Full Resolution Images ******************************************/
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
image = nil;
NSString *originalPath = [NSString stringWithFormat:#"IMAGE_%d_%d.jpg",(int)currentDate,i];
NSString* pImagePath = [DucPath stringByAppendingPathComponent:originalPath];
[imageData writeToFile:pImagePath atomically:YES];
[pImageMediaArray addObject:originalPath];
}
/************************************Low Resolution Images ******************************************/
UIImage *image = [UIImage imageWithCGImage:[alassetRep fullResolutionImage]];
UIImage *thumbImage = [self imageWithImage:image scaledToSize:CGSizeMake(50, 50)];
NSData *thumbImageData = UIImageJPEGRepresentation(thumbImage, 0.8);
NSString *thumbOriginalPath = [NSString stringWithFormat:#"SMALL_IMAGE_%d_%d.jpg",(int)currentDate,i];
NSString* thumbImagePath = [DucPath stringByAppendingPathComponent:thumbOriginalPath];
NSLog(#"Image path At Save Time:%#",thumbImagePath);
[thumbImageData writeToFile:thumbImagePath atomically:YES];
[pMediaArray addObject:thumbOriginalPath];
}
[appDelegate setPMediaArray:pImageMediaArray];
[pGridView reloadData];
imagesArray = nil;
[imagesArray release];
[pImageMediaArray release];
[self performSelectorOnMainThread:#selector(closeLoadindView) withObject:nil waitUntilDone:YES];}
Byte *buffer = (Byte*)malloc(DataSize);
is not being freed?
I had the same exact same issue. What worked for me was to use an autorelease pool block when you save the image. This will free up the retain count and the garbage collection will release the memory appropriately instead of retaining those objects in memory until the containing loop is finished running.
Example: In the method that you are using to save the images add code that looks like this:
#autoreleasepool {
NSString *filePath = [[NSArray arrayWithObjects:self.imagePath, #"/", GUID, #".png", nil] componentsJoinedByString:#""];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
BOOL res = [imageData writeToFile:filePath atomically:YES];
imageData = nil;
}
You need to add the autoreleasepool for task that perform in the background. In the above code content of the saveAllSelectedImages should be written inside autoreleasepool, Otherwise memory won't be released.

Can't get resized image to save at new size

I have the following code
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
// handle error
}
else if (! [isValidDirectory boolValue]) {
// No error and it’s not a directory; do something with the file
NSString* outP = [url absoluteString];
NSString* extension = [outP substringFromIndex: outP.length-3];
NSString* img = #"png";
if([extension isEqualToString:img]){
NSImage *original = [[NSImage alloc] initWithContentsOfURL: url];
NSSize sizes = NSMakeSize(240, 240);
NSImage *small =original;
[small setSize:sizes];
NSArray* representations = [small representations];
NSInteger* total = [substrings count];
NSData* bitmapData = [NSBitmapImageRep representationOfImageRepsInArray: representations usingType: NSPNGFileType properties:nil];
[bitmapData writeToFile:#"/Users/testuser/downloads/test/test_tn.png" atomically:NO];
}
when I run it it does not resize the image it just gives me a straight copy of the image with the name test_tn.png instead of a smaller image. I'm not sure what I'm doing wrong, this is a mac app also. There is some unused code in there that is for later. Is the problem how I'm passing the NSImage to the NSData after i resize?
edit: ok so i converted the NSData back into an NSImage and it appears the NSData is not getting the sized data but the original data.
edit 2: so this works
ok so this works
if([extension isEqualToString:img]){
NSImage *image = [[NSImage alloc] initWithContentsOfURL: url];
NSData *sourcedata =[image TIFFRepresentation];
NSSize newSize;
newSize.height = 160;
newSize.width = 120;
NSImage *sourceImage =[[NSImage alloc] initWithData: sourcedata];
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(240, 240)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, 240, 240) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSData *resizedPreviewData = [resizedImage TIFFRepresentation];
NSBitmapImageRep *resizedCaptureImageBitmapRep = [[NSBitmapImageRep alloc] initWithData:resizedPreviewData];
NSData* saveData = [resizedCaptureImageBitmapRep representationUsingType:NSPNGFileType properties:nil];
[saveData writeToFile:#"/Users/testuser/downloads/test/test_tn.png" atomically:YES];
count++;
}
This works for me. I am using this code to layer images on top of each other, but it should be easily adapted to your purposes:
CGSize destinationSize = smallSize;
UIGraphicsBeginImageContext(original.size);
[Original1 drawInRect:CGRectMake(0, 0, original.size.width, original.size.height)];
[Original2 drawInRect:CGRectMake(0, 0, original.size.width, original.size.height)];
UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContext(destinationSize);
[returnImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Save NSBItmapImageRep as grayscale png without alpha

I try to save NSBItmapImageRep without alpha channel.
My code is:
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCIImage:img];
NSColorSpace *targetColorSpace = [NSColorSpace genericGrayColorSpace];
NSBitmapImageRep *targetImageRep = [rep bitmapImageRepByConvertingToColorSpace:targetColorSpace
renderingIntent:NSColorRenderingIntentPerceptual];
NSData* PNGData = [targetImageRep representationUsingType:NSPNGFileType properties:nil];
[PNGData writeToURL:url atomically:YES];
[rep release];
But It doesn't work. It saves my image with type GrayScaleAlpha.
How to specify using alpha?

UIImage error with dynamic string

I'm trying to load an image into the cell,
The following code is working correctly :
NSString *imageURL = #"http://localhost/images/image2.jpg";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];
cell.image=rowImage;
but when i change imageURL to be dynamic , the image isn't displayed :
NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
You might be saying the problem is in :
[[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
But it's not , i've tried to log it and the output is as expected :
NSSLog(#"%#",[[stories objectAtIndex:indexPath.row] objectForKey:#"image"]);
//Outputs http://localhost/images/image2.jpg
What could be wrong ?
I am guessing there is space before or after the string. So do this,
NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
imageURL = [imageURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];
While this should mostly fix your issue, I suggest you trim the strings before adding to the dictionary during the XML parsing.
You should also ensure you release both imageData and rowImage. You might be doing it already but its not in the code above so I just wanted to indicate that it could be leaking.
try this one
NSString *imageURL =[NSString stringWithFormat:#"%#",[[stories objectAtIndex:indexPath.row] objectForKey:#"image"]];