iOS UIImageJPEGRepresentation error: Not a JPEG file: starts with 0xff 0xd9 - iphone

I am writing a .jpg file to my app's Documents directory like this:
NSData *img = UIImageJPEGRepresentation(myUIImage, 1.0);
BOOL retValue = [img writeToFile:myFilePath atomically:YES];
Later, I load that image back into a UIImage using:
UIImage *myImage = [UIImage imageWithContentsOfFile:path];
I know it works because I can draw the image in a table cell and it is fine. Now if I try to use UIImageJPEGRepresentation(myImage, 1.0), the debugger prints out these lines:
<Error>: Not a JPEG file: starts with 0xff 0xd9
<Error>: Application transferred too few scanlines
And the function returns nil. Does anybody have an idea why this would happen? I haven't done anything to manipulate the UIImage data after it was loaded. I just provided the UIImage to an image view in a cell. I set the image view properties such that all the images in the cells line up and are the same size, but I don't think that should have anything to do with being able to convert the UIImage to NSData.

The images were not corrupt, I was able to display them correctly. The issue is possibly a bug in UIImage, or perhaps the documentation should be more clear about using imageWithContentsOfFile:.
I was able to eliminate the error message by changing
UIImage *myImage = [UIImage imageWithContentsOfFile:path];
to
NSData *img = [NSData dataWithContentsOfFile:path];
UIImage *photo = [UIImage imageWithData:img];

Related

Loaded image in UIImage is pixelated on retina

I parsed the data from a web which also contains jpg image. The problem is that the image looks blurry/pixelated on retina display. Any solution for this? Thanks.
NSData *data = [NSData dataWithContentsOfURL:linkUrl];
UIImage *img = [[UIImage alloc] initWithData:data];
// detailViewController.faces.contentScaleFactor=[UIScreen mainScreen].scale;//Attampt to solve the problem
detailViewController.faces.image=img;
After initializing your image with the data, create a new one from it with the correct scale like this:
img = [UIImage imageWithCGImage:img.CGImage scale:[UIScreen mainScreen].scale orientation:img.imageOrientation];
...but note that the image will now appear half the size on retina displays unless you scale it up, for example by stretching it in an image view.

how to compress image in iphone?

I m taking images from photo library.I have large images of 4-5 mb but i want to compress those images.As i need to store those images in local memory of iphone.for using less memory or for getting less memory warning i need to compress those images.
I don't know how to compress images and videos.So i want to know hot to compress images?
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData* data = UIImageJPEGRepresentation(image,1.0);
NSLog(#"found an image");
NSString *path = [destinationPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpeg", name]];
[data writeToFile:path atomically:YES];
This is the code for saving my image. I dont want to store the whole image as its too big. So, I want to compress it to a much smaller size as I'll need to attach multiple images.
Thanks for the reply.
You can choose a lower quality for JPEG encoding
NSData* data = UIImageJPEGRepresentation(image, 0.8);
Something like 0.8 shouldn't be too noticeable, and should really improve file sizes.
On top of this, look into resizing the image before making the JPEG representation, using a method like this:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Source: The simplest way to resize an UIImage?
UIImageJPEGRepresentation(UIImage,Quality);
1.0 means maximum Quality and 0 means minimum quality.
SO change the quality parameter in below line to reduce file size of the image
NSData* data = UIImageJPEGRepresentation(image,1.0);
NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);
OR
NSData *image_Data=UIImageJPEGRepresentation(image_Name,compressionQuality);
return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compressionQuality is 0(most) & 1(least).

Orientation does not behave correctly with Photo in ALAsset

I current have an app that uses ALAsssetsLibrary to fetch the photos. I have placed the photo to an image view and I am able to upload to the server. When I tested on the real device after taking some photos, I found out the photos that supposed to be taken in Portrait become a landscape.
Therefore, I called different function to get the CGImage like this:
UIImage *image = [UIImage imageWithCGImage:[representation fullResolutionImage] scale:1.0 orientation:(UIImageOrientation)[representation orientation]];
The first tried out, I used this :
UIImage *image = [UIImage imageWithCGImage:[representation fullResolutionImage]]
I thought the one with scale and orientation could give me the right orientation that the photo was taken. But it didn't give me the right solution.
Do I miss anything that is necessary to generate a correct orientation of photo?
The correct orientation handling depends on the iOS version you are using.
On iOS4 and iOS 5 the thumbnail is already correctly rotated, so you can initialize your UIImage without specifying any rotation parameters.
However for the fullScreenImage, the behavior is different for each iOS version. On iOS 5 the image is already rotated on iOS 4 not.
So on iOS4 you should use:
ALAssetRepresentation *defaultRep = [asset defaultRepresentation];
UIImage *_image = [UIImage imageWithCGImage:[defaultRep fullScreenImage]
scale:[defaultRep scale] orientation:(UIImageOrientation)[defaultRep orientation]];
On iOS5 the following code should work correctly:
ALAssetRepresentation *defaultRep = [asset defaultRepresentation];
UIImage *_image = [UIImage imageWithCGImage:[defaultRep fullScreenImage] scale:[defaultRep scale] orientation:0];
Cheers,
Hendrik
Try this code:-
UIImage* img = [UIImage imageWithCGImage:asset.thumbnail];
img = [UIImage imageWithCGImage:img.CGImage scale:1.0 orientation:UIImageOrientationUp];
This may help you.
My experience is limited to IOS 5.x but I can tell you that the thumbnail and fullscreen images are oriented properly. It's the fullresolutionimage that's horizontal when shot vertically. My solution is to use a category on uiimage that I got from here:
http://www.catamount.com/forums/viewtopic.php?f=21&t=967&start=0
It provides a nice rotating method on a UIImage like this:
UIImage *tmp = [UIImage imageWithCGImage:startingFullResolutionImage];
startingFullResolutionImage = [[tmp imageRotatedByDegrees:-90.0f] CGImage];
For fullResolutionImage, I'd like to provide a solution as follows,
ALAssetRepresentation *rep = [asset defaultRepresentation];
// First, write orientation to UIImage, i.e., EXIF message.
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage] scale:rep.scale orientation:(UIImageOrientation)rep.orientation];
// Second, fix orientation, and drop out EXIF
if (image.imageOrientation != UIImageOrientationUp) {
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
[image drawInRect:(CGRect){0, 0, image.size}];
UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
image = normalizedImage;
}
// Third, compression
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
imageData is what you want, and just upload it to your photo server.
By the way, if you think EXIF is useful, you can complement it to normalizedImage as you wish.

How to display the UIImageJPEGRepresentation image in iphone sdk

I want to use UIImageJPEGRepresentation to add the image in iphone, in below code i am missing some thing I don't know how to add
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:gameObj.gameThumbnails]];
UIImage *myImage=[UIImage imageWithData:data];
imageView.image=UIImageJPEGRepresentation(myImage, 90);// I am missing something here
[elementView addSubview:imageView];
[imageView release];
/*gameObj.gameThumbnails is an url like http://static.gamesradar.com/images/mb/GamesRadar/us/Games/X/X-Men%20Arcade/Bulk%20Viewer/360%20PS3/2010-10-11/192.168.30.167-image36_bmp_jpgcopy--game_thumbnail.jpg
*/
Please help me out of this
u are setting comparison quality to 90. it should be between 0.0 to 1.0
The UIImageJPEGRepresentation function returns an NSData (array of bytes) which represents a content of the image if compressed in JPEG.
To display it, you just need to use the UIImage directly.
imageView.image = myImage;
Make sure that you:
Set your compression quality to 0.9(it MUST be between 0.0 - 1.0)
Set the frame of the UIImageView correctly
Don't make that UIImageView hidden
And if it still doesn't work then try the following:
[elementView bringSubviewToFront:imageView];
Hope it helps

How can I save a Bitmap Image, represented by a CGContextRef, to the iPhone's hard drive?

I have a little sketch program that I've managed to throw together using Quartz2D, but I'm very new to the iOS platform and I'm having trouble figuring out how to allow the user to save their sketch. I have a CGContextRef that contains the sketch, how can I save it so that it can later be retrieved? Once it's saved, how can I retrieve it?
Thanks so much in advance for your help! I'm going to continue reading up on this now...
There are different types of CGContexts. You are most likely having a screen based context, but you would need either a bitmapContext or a pdfContext, to create a bitmap or a pdf file.
See the UIKit Functions Reference. Functions that should be of interest are:
UIGraphicsBeginImageContext()
UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageJPEGRepresentation()
UIImageWriteToSavedPhotosAlbum()
UIGraphicsBeginPDFContextToFile()
UIGraphicsEndPDFContext()
Here's how I did it...
Saving
CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
Retrieving
UIImage* image = [UIImage imageWithContentsOfFile:filePath];
CGImageRef imageRef = [image CGImage];