简体   繁体   中英

Efficiently writing NSDictionary with an NSImage to a file

I have an NSMutableDicitionary containing two NSStrings and one NSImage, which I am trying to write to a file. However the output file is huge compared to the input image file (88kB to 1.1MB). The image is loaded via an Image Well drag and drop.

My first try was:

NSImage * image = _imageView.image;
[dictionary setObject:image forKey:@"Image"];
[NSKeyedArchiver archiveRootObject:dictionary toFile:filePath];

Result: 1.1MB

Second try:

NSImage * image = _imageView.image;
NSData * imageData = [image TIFFRepresentation];
NSBitmapImageRep * encodedImage = [NSBitmapImageRep imageRepWithData:imageData];
[dictionary setObject:encodedImage forKey:@"Image"];
[NSKeyedArchiver archiveRootObject:dictionary toFile:filePath];

Result: still 1.1MB

At first I thought that NSBitmapImage would keep the image in a (at least relatively) compressed format, but the file size does not differ one bit.

How should I write the NSMutable dictionary to a file so that it does not exceed the initial image file size by so much? Or how should I store the image efficiently in the dictionary in the first place?

I don't know if it matters, but the original format is png.

When you drop an image into an Image View, it gets loaded into an NSImage as a bitmap (color data for every pixel). It isn't compressed any longer like the original image you dropped into it was (PNG in your case). PNG uses lossless compression and its data footprint will be in most cases less than an uncompressed bitmap or TIFF representation of the image.

Then when you request the TIFF representation of the image, it has nothing to do with the original PNG image you loaded into it anymore except the pixel data itself.

If you want to store back the image in a compressed format or keep the original image, you can try one of the following:

  1. Ask for compressed TIFF representation using TIFFRepresentationUsingCompression:factor: . Will still be different format and you will lose all metadata
  2. Re-compressed the image with your desired format eg PNG, jpeg, etc (ie with Quartz API) and store the compressed format in your dictionary. You will still need to preserve metadata yourself if you need it
  3. Keep reference to the original image file or store its data. By overriding the ImageView's drag/drop methods and keeping track of the original's image URL or load it from the file and store the raw data of the original format. Then save that into your dictionary. You will get the exact copy of the original image and won't have to deal with format conversions and metadata copying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM