Compress Image File Size (iPhone)? - objective-c

I have a simple iPhone app that allows the user to upload images to a server. The problem is, what if they upload a large image file. I want to limit it down to (a max of) 200 KB. I started something but it seems to crash in my while statement.
Here's the code:
NSString *jpgPath = [NSString stringWithFormat:#"Documents/%#",sqlImageUploadPathTwo];
NSString *jpgPathTwo = [NSString stringWithFormat:#"./../Documents/%#",sqlImageUploadPathTwo];
NSString *yourPath = [NSHomeDirectory() stringByAppendingPathComponent:jpgPath];
NSLog(#"yourPath: %#", yourPath);
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
int *result = [attrs fileSize];
NSLog(#"Here's the original size: %d", result);
NSLog(#"jpgPath: %# // jpgPathTwo: %#", jpgPath, jpgPathTwo);
while (result > 9715) {
UIImage *tempImage = [UIImage imageNamed: jpgPath];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(tempImage, 0.9)];
[imageData writeToFile:jpgPathTwo atomically:YES];
NSLog(#"just shrunk it once.");
}
NSLog(#"SIZE AFTER SHRINK: %#", result);
Thanks! Coulton

Something like this:
(also note that you declared result as int* (i.e. a pointer), instead of a number, and the condition should be >, not < (otherwise for large files it won't change them at all). And an extra counter condition is useful to avoid endless loop (basically do it 5 times and then stop doing it, regardless of the size).
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
int result = [attrs fileSize];
int count = 0;
while (result > 9715 && count < 5) {
UIImage *tempImage = [UIImage imageNamed: jpgPath];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(tempImage, 0.9)];
[imageData writeToFile:jpgPathTwo atomically:YES];
NSDictionary *attrs = [man attributesOfItemAtPath: jpgPathTwo error: NULL];
result = [attrs fileSize];
count++;
NSLog(#"just shrunk it once.");
}

Related

Get all Images from Live Photo

I want to get a NSArray with all the UIImage from a Live Photo to create a GIF of that. I tried to make screenshots while animating the live photo but it doesn't work.
Can anyone help me?
Thanks!
First step, you need convert a Live Photo to Video, using this:
PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes,
toFile: fileURL, options: nil, completionHandler:
{
// Video file has been written to path specified via fileURL
}
Finally, using this library to convert this to GIF, or you can search in google for another way: https://github.com/NSRare/NSGIF
Hope this will help you.
This is what I did to achieve the same thing as you requested.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:#"mediaType == %d", PHAssetMediaTypeImage];
options.predicate = [NSPredicate predicateWithFormat:#"mediaSubtype == %d", PHAssetMediaSubtypePhotoLive];
options.includeAllBurstAssets = NO;
PHFetchResult *allLivePhotos = [PHAsset fetchAssetsWithOptions:options];
NSLog(#"Get total live count : %ld",(unsigned long)allLivePhotos.count);
NSMutableArray *arrAllLiveImagesGroups = [NSMutableArray array];
for (PHAsset *asset in allLivePhotos) {
[asset requestContentEditingInputWithOptions:nil
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *urlMov = [contentEditingInput.livePhoto valueForKey:#"videoURL"];
NSMutableArray *arrLive = [NSMutableArray array];
NSMutableArray *arrSingleLiveImagesGroup = [NSMutableArray array];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlMov options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.requestedTimeToleranceAfter = kCMTimeZero;
generator.requestedTimeToleranceBefore = kCMTimeZero;
for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) * 5 ; i++){
#autoreleasepool {
CMTime time = CMTimeMake(i, 5);
NSError *err;
CMTime actualTime;
CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err];
UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image scale:1.0 orientation:UIImageOrientationDown];
[arrLive addObject:generatedImage];
CGImageRelease(image);
}
}
[arrSingleLiveImagesGroup addObject:arrLive];
[arrAllLiveImagesGroups addObject:arrSingleLiveImagesGroup];
}];
}

Loading image from url ios 8 objective c

i´m trying to obtain the imagen from this url[#"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"], but i can´t.
Always is nil.
this is my code:
NSData *data = [NSData dataWithContentsOfURL: #"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"];
UIImage *image = [UIImage imageWithData:data];
self.pruebaTmp.image = image;
i obtain the url with this code:
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
//asignamos el path de la imágen seleccionada en galeria
self.pathImagen = path;
}];
}
if someone could help i would be very grateful, because i can´t load the image with the url obtained.
you can`t not get UIimage or metadata from that url.
you can get UIImage from local Identifier of access
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:#[localIdentifier] options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
//PHImageRequestOptionsDeliveryModeHighQualityFormat
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = NO;
imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;
imageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
NSLog(#"get image from result");
if (result) {
}
}];
imageRequestOptions = nil;
}];

Getting frames though a stream and display on screen

I have a requirement of streaming from server and displaying the streamed content on the screen...Streaming is working fine using NSStream, and NSInputStream and NSOutputStream.How can I display it on the screen?
Stream used looks like #"http://191.168.143.41:1212/;
if(stream == inputStream) {
uint8_t buf[1024];
unsigned int len = 0;
len = [inputStream read:buf maxLength:1024];
if(len > 0) {
NSMutableData* datas=[[NSMutableData alloc] initWithLength:0];
[datas appendBytes: (const void *)buf length:len];
NSString *s = [[NSString alloc] initWithData:datas encoding:NSASCIIStringEncoding];
[self readIn:s];
NSLog(#"ss%#",s);
[self loadMovie:s]; //method for movie player
}
I tried to display this is in a movieplayer as below..
-(void_loadMovie:(NSString*)moviePrefix
{
NSString *path = [NSString stringWithFormat:#"%#.mjpg", moviePrefix];
NSURL *url = [NSURL fileURLWithPath:path];
if (url) {
_moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
_moviePlayer.view.frame = CGRectMake(0, 70, 600, 450);
_moviePlayer.controlStyle = MPMovieControlStyleNone;
_moviePlayer.scalingMode = MPMovieScalingModeNone;
[dic setObject:__moviePlayer forKey:path];
}
}
[_moviePlayer prepareToPlay];
[self.view addSubview: _moviePlayer.view];
[self.view bringSubviewToFront:_moviePlayer.view];
[self.view addSubview: _moviePlayer.view];
[_moviePlayer play];
}
Is NSString *path = [NSString stringWithFormat:#"%#.mjpg", moviePrefix]; correct way??
This displays a black screen.What is wrong?
If this way is not correct,Is there any other way I can display those frames?
Can anyone help me to solve this...
MJPEG are only JPEG sent one after the other.
I worked a few years ago on this.
On a version of iOS (iOS5?), it was easily read with a UIWebView, but an update of iOS broke all this. This broke all my current work.
Maybe a UIWebView could do the trick today again (fix).
Anyway, since it's just bunch of JPEG, you could just read the JPG (detect start/end of JPG file), create the JPG image and show it in a UIImageView.
A work around (not tested), but you should get the whole idea:
//Properties
#property (nonatomic, strong) NSMutableData *data;
#property (nonatomic, weak) IBOutlet UIImageView *streamImageView;
//Initialize somewhere
_data = [[NSMutableData alloc] init];
//In the stream delegate method:
//Start JPG: FFD8 — End JPG: FFD9
UInt8 startJPEGBytes[2];
startJPEGBytes[0] = 0xFF;
startJPEGBytes[1] = 0xD8;
NSData *startData = [NSData dataWithBytes:&startJPEGBytes length:2];
UInt8 endJPEGBytes[2];
endJPEGBytes[0] = 0xFF;
endJPEGBytes[0] = 0xD9;
NSData *endData = [NSData dataWithBytes:&endJPEGBytes length:2];
[_data appendBytes: (const void *)buf length:len];
NSRange startRange = [_data rangeOfData:startData options:0 range:NSMakeRange(0, [_data length])];
if (startRange.location != NSNotFound) //We found the start of a JPEG
{
NSRange endRange = [_data rangeOfData:endData options:0 range:NSMakeRange(startRange.location, [_data length]-startRange.location)];
if (endRange.location != NSNotFound) //We found the end of a JPEG
{
NSRange imageRange = NSMakeRange(startRange.location, endRange.location+endRange.length-startRange.location);
NSData *imageData = [_data subDataWithRange: imageRange];
streamImage = [UIImage imageWithData:imageData];
[_streamImageView setImage:streamImage];
[_data replaceBytesInRange:NSMakeRange(0, imageRange.location+imageRange.length withBytes:NULL length:0]; //We remove the start till the end of JPEG frame. Start at 0, since there could be garbage at the start.
}
}
You are not adding moviePrefix to the string
NSString *path = [NSString stringWithFormat:#".mjpg", moviePrefix, #"movie"];
Change it to
NSString *path = [NSString stringWithFormat:#"%#.mjpg", moviePrefix, #"movie"];
https://github.com/horsson/mjpeg-iphone/tree/55251a85e2c2489014036ddf5a491783f9b1962d
Used this to get the stream and display.It works

VideoData is empty

I'm trying to find a way to upload video from UIImagePickerController.
The below code, it returns back a 0 length for video data but I'm positive that the video path is correct because it returns back something like
/private/var/mobile/Applications/22318D96-B5B5-4C92-A8EB-869311275E40/tmp//trim.‌​AE6xnl.MOV
NSString *videoPath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSData *videoData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:videoPath ofType:#"mov"]];
int videoSize = [videoData length];
NSLog(#"Video path: %d", moviePath);
NSLog(#"Video size: %d", videoSize);
Any idea what is the correct param to put for pathForResource?
thanks
Do this:
NSURL* movieUrl = [info valueForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:movieUrl];
if(videoData)
{
int videoSize = [videoData length];
NSLog(#"Video path: %d", movieUrl);
NSLog(#"Video size: %d", videoSize);
}

Resizing image and saving it to the specified directory path in Cocoa

Using this code I am trying to resize the selected image and then want to save it to a specific path:
-(void)processImage:(NSString*)inputPath:(int)imageWidth:(int)imageHeight:(NSString*)outputPath {
NSImage * img = [NSImage imageNamed:inputPath];
[img setSize: NSMakeSize(imageWidth,imageHeight)];
}
-(void)startProcessingImages {
int i; // Loop counter.
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
inputFilePath = [[files objectAtIndex:i] retain];
NSLog(#"filename::: %#", inputFilePath);
// Do something with the filename.
[selectedFile setStringValue:inputFilePath];
NSLog(#"selectedFile:::: %#", selectedFile);
}
NSLog(#"curdir:::::%#", inputFilePath);
NSString *aString = [[NSString stringWithFormat:#"%#%#%#", thumbnailDirPath , #"/" , fileNameNumber] retain];
fileNameJPG = [[aString stringByAppendingString:#".jpg"] retain];
[self processImage:inputFilePath: 66 :55 :thumbnailDirPath];
[self processImage:inputFilePath: 800 :600 :thumbnailDirPath];
[self processImage:inputFilePath: 320 :240 :thumbnailDirPath];
}
My issue is I am not getting that how to save it to thumbnailDirPath.
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.8] forKey:NSImageCompressionFactor];
NSData *tiffData = [img TIFFRepresentation];
NSData *JPEGData = [[NSBitmapImageRep imageRepWithData:tiffData] representationUsingType:NSJPEGFileType properties:options];
NSError *anError;
if (![JPEGData outputPath options:0 error:&anError])
MyLog(#"Error saving image: %# to: %#", anError, outputPath);
Check the documentation for NSJPEGFileType as it will show you the other foramt options for saving, such as PNG.
you should do export your image into file.
currently I only see how to store the TIFF image.
[[img TIFFRepresentation] writeToFile:outputPathName atomacally:NO];
Where outputPathName is the path with file name for your thumbnail file.