获取图片的metaData

获取简易的metaData较为容易,以下是测试图:

以下是本人提供的源码:

UIImage+MetaData.h

//
//  UIImage+MetaData.h
//  PictureInfo
//
//  Created by YouXianMing on 14-8-27.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIImage (MetaData)

- (NSDictionary *)JPEGmetaData;
- (NSDictionary *)PNGmetaData;

@end

UIImage+MetaData.h

//
//  UIImage+MetaData.m
//  PictureInfo
//
//  Created by YouXianMing on 14-8-27.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "UIImage+MetaData.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <ImageIO/ImageIO.h>

@implementation UIImage (MetaData)

- (NSDictionary *)JPEGmetaData
{
    if (self == nil)
    {
        return nil;
    }

    // 转换成jpegData,信息要多一些
    NSData *jpegData              = UIImageJPEGRepresentation(self, 1.0);
    CGImageSourceRef source       = CGImageSourceCreateWithData((__bridge CFDataRef)jpegData, NULL);
    CFDictionaryRef imageMetaData = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    CFRelease(source);

    NSDictionary *metaDataInfo    = CFBridgingRelease(imageMetaData);
    return metaDataInfo;
}

- (NSDictionary *)PNGmetaData
{
    if (self == nil)
    {
        return nil;
    }

    NSData *pngData               = UIImagePNGRepresentation(self);
    CGImageSourceRef source       = CGImageSourceCreateWithData((__bridge CFDataRef)pngData , NULL);
    CFDictionaryRef imageMetaData = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    CFRelease(source);

    NSDictionary *metaDataInfo    = CFBridgingRelease(imageMetaData);
    return metaDataInfo;
}

@end

使用情况:

//
//  AppDelegate.m
//  GetPictureInfo
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "AppDelegate.h"
#import "UIImage+MetaData.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    NSLog(@"%@", [[UIImage imageNamed:@"IMG_0151.JPG"] JPEGmetaData]);

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

@end

以下是打印信息:

{
    ColorModel = RGB;
    Depth = 8;
    Orientation = 1;
    PixelHeight = 1936;
    PixelWidth = 2592;
    "{Exif}" =     {
        ColorSpace = 1;
        PixelXDimension = 2592;
        PixelYDimension = 1936;
    };
    "{JFIF}" =     {
        DensityUnit = 0;
        JFIFVersion =         (
            1,
            1
        );
        XDensity = 1;
        YDensity = 1;
    };
    "{TIFF}" =     {
        Orientation = 1;
    };
}
几个需要注意的地方:

1. 需要引入两个库

2. 一些需要注意的细节

你以为结束了么?没有呢,你还没取到图片的经纬度信息,对吧,一下给你提供资料自己去尝试:)

http://stackoverflow.com/questions/9766394/get-exif-data-from-uiimage-uiimagepickercontroller

How can we get Exif information from UIImage selected from UIImagePickerController?

I had done much R&D for this and got many replies but still failed to implement this.

I had gone through this this and this link

Please help me to solve this problem.

Thanks in advance..

iphone objective-c ipad exif


share|improve this question

asked Mar 19 ‘12 at 7:22

iOS developer
8,688124776

 

add a comment

5 Answers

active
oldest
votes

up vote
26
down vote

Interesting question! I came up with the following solution working
for images picked from your photo library (note my code is using ARC):

Import AssetsLibrary.framework and ImageIO.framework.

Then include the needed classes inside your .h-file:

#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import <ImageIO/CGImageSource.h>
#import <ImageIO/CGImageProperties.h>

And put this inside your imagePickerController:didFinishPickingMediaWithInfo: delegate method:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[info objectForKey:UIImagePickerControllerReferenceURL]
    resultBlock:^(ALAsset *asset) {

        ALAssetRepresentation *image_representation = [asset defaultRepresentation];

        // create a buffer to hold image data
        uint8_t *buffer = (Byte*)malloc(image_representation.size);
        NSUInteger length = [image_representation getBytes:buffer fromOffset: 0.0  length:image_representation.size error:nil];

        if (length != 0)  {

            // buffer -> NSData object; free buffer afterwards
            NSData *adata = [[NSData alloc] initWithBytesNoCopy:buffer length:image_representation.size freeWhenDone:YES];

            // identify image type (jpeg, png, RAW file, ...) using UTI hint
            NSDictionary* sourceOptionsDict = [NSDictionary dictionaryWithObjectsAndKeys:(id)[image_representation UTI] ,kCGImageSourceTypeIdentifierHint,nil];

            // create CGImageSource with NSData
            CGImageSourceRef sourceRef = CGImageSourceCreateWithData((__bridge CFDataRef) adata,  (__bridge CFDictionaryRef) sourceOptionsDict);

            // get imagePropertiesDictionary
            CFDictionaryRef imagePropertiesDictionary;
            imagePropertiesDictionary = CGImageSourceCopyPropertiesAtIndex(sourceRef,0, NULL);

            // get exif data
            CFDictionaryRef exif = (CFDictionaryRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyExifDictionary);
            NSDictionary *exif_dict = (__bridge NSDictionary*)exif;
            NSLog(@"exif_dict: %@",exif_dict);

            // save image WITH meta data
            NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSURL *fileURL = nil;
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(sourceRef, 0, imagePropertiesDictionary);

            if (![[sourceOptionsDict objectForKey:@"kCGImageSourceTypeIdentifierHint"] isEqualToString:@"public.tiff"])
                     {
                         fileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.%@",
                                                           documentsDirectory,
                                                           @"myimage",
                                                           [[[sourceOptionsDict objectForKey:@"kCGImageSourceTypeIdentifierHint"] componentsSeparatedByString:@"."] objectAtIndex:1]
                                                           ]];

                         CGImageDestinationRef dr = CGImageDestinationCreateWithURL ((__bridge CFURLRef)fileURL,
                                                                                     (__bridge CFStringRef)[sourceOptionsDict objectForKey:@"kCGImageSourceTypeIdentifierHint"],
                                                                                     1,
                                                                                     NULL
                                                                                    );
              CGImageDestinationAddImage(dr, imageRef, imagePropertiesDictionary);
              CGImageDestinationFinalize(dr);
              CFRelease(dr);
            }
            else
            {
              NSLog(@"no valid kCGImageSourceTypeIdentifierHint found …");
            }

            // clean up
            CFRelease(imageRef);
            CFRelease(imagePropertiesDictionary);
            CFRelease(sourceRef);
        }
        else {
            NSLog(@"image_representation buffer length == 0");
        }
    }
    failureBlock:^(NSError *error) {
        NSLog(@"couldn‘t get asset: %@", error);
    }
];

One thing I noticed is, that iOS will ask the user to allow location services – if he denies, you won‘t be abled to get the image data …

EDIT

Added code to save the image including its meta data. It‘s a quick approach, so maybe there is a better way, but it works!


share|improve this answer

edited Mar 19 ‘12 at 11:12

answered Mar 19 ‘12 at 8:42

dom
6,80132550

 

    

Can you plz tell me how to save image after getting exif data?
– 
iOS developer
Mar 19 ‘12 at 9:40
    

+1 Cool answer..
– 
iOS developer
Mar 19 ‘12 at 9:44
    

@Marvin Check out my edit :P
– 
dom
Mar 19 ‘12 at 10:54
    

plz tell me what is "__bridge" in your code? :-)
– 
iOS developer
Mar 19 ‘12 at 11:05
    

@Marvin I‘m using ARC. __bridge
is one of a hand full of keywords, which tell ARC about the objects
ownership so it can properly clean them up. The simplest case is a __bridge cast, for which ARC will not do any extra work (it assumes you handle the object‘s memory yourself).
– 
dom
Mar 21 ‘12 at 6:45

show 3 more comments

up vote
15
down vote

accepted

I had found solution and got answer from here

From here We can get GPS info as well..

Amazing and thanks all for helping me to solve this problem.

UPDATE

This is another function that I had created myself, also return Exif
data as well as GPS data and in this function we doesn‘t need any third
party library.. but you have to turn on location services for this. and
use current latitude and longitude for that. so have to use CoreLocation.framework

//FOR CAMERA IMAGE

-(NSMutableData *)getImageWithMetaData:(UIImage *)pImage
{
    NSData* pngData =  UIImagePNGRepresentation(pImage);

    CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)pngData, NULL);
    NSDictionary *metadata = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);

    NSMutableDictionary *metadataAsMutable = [[metadata mutableCopy]autorelease];
    [metadata release];

    //For GPS Dictionary
    NSMutableDictionary *GPSDictionary = [[[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyGPSDictionary]mutableCopy]autorelease];
    if(!GPSDictionary)
        GPSDictionary = [NSMutableDictionary dictionary];

    [GPSDictionary setValue:[NSNumber numberWithDouble:currentLatitude] forKey:(NSString*)kCGImagePropertyGPSLatitude];
    [GPSDictionary setValue:[NSNumber numberWithDouble:currentLongitude] forKey:(NSString*)kCGImagePropertyGPSLongitude];

    NSString* ref;
    if (currentLatitude <0.0)
        ref = @"S";
    else
        ref [email protected]"N";
    [GPSDictionary setValue:ref forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];

    if (currentLongitude <0.0)
        ref = @"W";
    else
        ref [email protected]"E";
    [GPSDictionary setValue:ref forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];

    [GPSDictionary setValue:[NSNumber numberWithFloat:location.altitude] forKey:(NSString*)kCGImagePropertyGPSAltitude];

    //For EXIF Dictionary
    NSMutableDictionary *EXIFDictionary = [[[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy]autorelease];
    if(!EXIFDictionary)
        EXIFDictionary = [NSMutableDictionary dictionary];

    [EXIFDictionary setObject:[NSDate date] forKey:(NSString*)kCGImagePropertyExifDateTimeOriginal];
    [EXIFDictionary setObject:[NSDate date] forKey:(NSString*)kCGImagePropertyExifDateTimeDigitized];

    //add our modified EXIF data back into the image’s metadata
    [metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
    [metadataAsMutable setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];

    CFStringRef UTI = CGImageSourceGetType(source);

    NSMutableData *dest_data = [NSMutableData data];
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)dest_data, UTI, 1, NULL);

    if(!destination)
        dest_data = [[pngData mutableCopy] autorelease];
    else
    {
        CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef) metadataAsMutable);
        BOOL success = CGImageDestinationFinalize(destination);
        if(!success)
            dest_data = [[pngData mutableCopy] autorelease];
    }

    if(destination)
        CFRelease(destination);

    CFRelease(source);

    return dest_data;
}

//FOR PHOTO LIBRARY IMAGE

-(NSMutableData *)getImagedataPhotoLibrary:(NSDictionary *)pImgDictionary andImage:(UIImage *)pImage
{
    NSData* data = UIImagePNGRepresentation(pImage);

    CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)data, NULL);
    NSMutableDictionary *metadataAsMutable = [[pImgDictionary mutableCopy]autorelease];

    CFStringRef UTI = CGImageSourceGetType(source);

    NSMutableData *dest_data = [NSMutableData data];

    //For Mutabledata
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)dest_data, UTI, 1, NULL);

    if(!destination)
        dest_data = [[data mutableCopy] autorelease];
    else
    {
        CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef) metadataAsMutable);
        BOOL success = CGImageDestinationFinalize(destination);
        if(!success)
            dest_data = [[data mutableCopy] autorelease];
    }
    if(destination)
        CFRelease(destination);

    CFRelease(source);

    return dest_data;
}

and We will retrieve that data like this

//FOR CAMERA IMAGE
NSData *originalImgData = [self getImageWithMetaData:imgOriginal];

//FOR PHOTO LIBRARY IMAGE
[self getImagedataPhotoLibrary:[[myasset defaultRepresentation] metadata] andImage:imgOriginal];

For all of this you should have to Import AssetsLibrary.framework and ImageIO.framework.


share|improve this answer

edited Oct 15 ‘12 at 12:50

answered Mar 27 ‘12 at 13:26

iOS developer
8,688124776

 

    

where is currentLatitude
coming from? Are you setting this from the standard CoreLocation calls
before you invoke the UIImagePicker or are you reading it directly from
the image that was returned?
– 
Paul Cezanne
Apr 24 ‘12 at 14:55
    

CoreLoation calls before invoking UIImagePickerController
– 
iOS developer
Apr 25 ‘12 at 4:17
    

ahhh, it can be inaccurate
then. You call CoreLocation, invoke UIImagePicker and then physically
move the device a distance before taking the image. You will now have
inaccurate latitude and longitude. Drat...
– 
Paul Cezanne
Apr 25 ‘12 at 8:48
    

But you can also put distance filter for 5 meters so If use moves then It will automatically take its current location..
– 
iOS developer
Apr 25 ‘12 at 9:44
    

but you‘ll never know the
location when the shutter button is pressed, just the current location.
(You can keep on moving after the shutter button is pressed.)
– 
Paul Cezanne
Apr 25 ‘12 at 9:54

show 4 more comments

up vote
15
down vote

These answers all seem extremely complex. If the image has been saved
to the Camera Roll, and you have the ALAsset (either from UIImagePicker
or ALAssetLibrary) you can get the metadata like so:

asset.defaultRepresentation.metadata;

If you want to save that image from camera roll to another location (say in Sandbox/Documents) simply do:

CGImageDestinationRef imageDestinationRef   = CGImageDestinationCreateWithURL((__bridge CFURLRef)urlToSaveTo, kUTTypeJPEG, 1, NULL);
CFDictionaryRef imagePropertiesRef          = (__bridge CFDictionaryRef)asset.defaultRepresentation.metadata;

CGImageDestinationAddImage(imageDestinationRef, asset.defaultRepresentation.fullResolutionImage, imagePropertiesRef);
if (!CGImageDestinationFinalize(imageDestinationRef)) NSLog(@"Failed to copy photo on save to %@", urlToSaveTo);

CFRelease(imageDestinationRef);

share|improve this answer

answered Mar 13 ‘13 at 23:19

Andrew Theis
829512

 

1  

This is a far superior way to do this than the answers from 2012.
– 
broughten
Oct 18 ‘13 at 6:13
1  

It also return much more info than the other ways: They won‘t return infos Stored in {TIFF} like Model, Make, Copyright, Artist and so on. This should be marked as answer!
– 
Benedikt Mokroß
Dec 7 ‘13 at 17:02

add a comment

up vote
1
down vote

You need ALAssetsLibrary to actually retrieve the EXIF info from an
image. The EXIF is added to an image only when it is saved to the Photo
Library. Even if you use ALAssetLibrary to get an image asset from the
library, it will lose all EXIF info if you set it to a UIImage.


share|improve this answer

answered Dec 13 ‘12 at 13:24

ATOzTOA
9,17042158

 

add a comment

up vote
0
down vote

I have tried to insert GPS coordinates into image metadata picked by iPad Camera as it was suggested by Mehul.
It Works, Thank you for your post.

P.S.
Who intends to use that code, just substitude the two geolocations at
the top of the function -(NSMutableData *)getImageWithMetaData:(UIImage
*)pImage {

double currentLatitude = [locationManager location].coordinate.latitude;
double currentLongitude = [locationManager location].coordinate.longitude;

...

By supposing that you have already initializied somewhere locationManager in your code, like this:

    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager setDelegate:self]; // Not necessary in this case
    [locationManager startUpdatingLocation]; // Not neccessary in this case

and by importing CoreLocation/CoreLocation.h and ImageIO/ImageIO.h headers with associated frameworks.

时间: 2024-10-16 18:33:46

获取图片的metaData的相关文章

JS获取图片的缩略图,并且动态的加载多张图片

找了好多资料也没有找到该死的ie的解决办法,最后放弃了ie <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js获取缩略图</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <st

怎样从server获取图片

今天写了安卓程序与server通信.当中须要从server获取图片.本来以为下载流.处理文件流非常复杂.结果几句话就轻松搞定了.如今记在这里. // (2014.5.1第一种方法)通过server返回的图片url,再次向server请求,加入动态新闻图片 // 读取Bitmap图片 try { Bitmap bm; URL url; url = new URL(map.get("activityPhoto").toString()); HttpURLConnection conn =

UIImagePickerController从拍照、图库、相册获取图片

iOS 获取图片有三种方法: 1. 直接调用摄像头拍照 2. 从相册中选择 3. 从图库中选择 UIImagePickerController 是系统提供的用来获取图片和视频的接口: 用UIImagePickerController 类来获取图片视频,大体分为以下几个步骤: 1. 初始化UIImagePickerController 类: 2. 设置UIImagePickerController 实例的数据来源类型(下面解释): 3. 设置设置代理: 4. 如果需要做图片修改的话设置allows

如何通过js和jquery获取图片真实的宽度和高度

在做pc网页的时候,有时候会考虑按照插入的图片的尺寸来判断图片是横图还是竖图.然后判断过后给予不同的展示方式! 另外一种就是在手机页面上,在新闻页插入的图片往往都是按照图片的原尺寸来展示,如果手机屏幕太小,太大的图就会超出去!这时候有两种解决办法 1.给所有的图片加上这样的样式 .news img{margin:5px auto; display:block;width:100%; height:auto;} 但是这种方式有另外一个问题就是,如果插入的图片本身就很小的话,也会被直接拉伸成100%

Android图片系列(1)-------调用系统相册与相机获取图片

Android开发过程中,我们经常需要获取图片,你可以通过获取手机相册的图片,也可以调用相机拍照获取图片.这里主要讲这两个获取图片的方式,并记录其中遇到的小问题. 调用相册获取图片 这个功能非常简单,这里不多说了,这里贴出关键代码 Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT); openAlbumIntent.setType("image/*"); startActivityForResult(openAl

android获取图片的旋转角度

public static int getExifOrientation(String filepath) { int degree = 0; ExifInterface exif = null; try { exif = new ExifInterface(filepath); } catch (IOException ex) { Log.d(TAG, "cannot read exif" + ex); } if (exif != null) { int orientation =

添加资源图片,获取图片实例并绘制到窗体

项目右键属性——资源——添加资源展开——添加现有文件 paint方法中: private void Form1_Paint(object sender, PaintEventArgs e) { using (Graphics g = e.Graphics) { g.DrawImage((Image)zhbImgConvert.Properties.Resources.ResourceManager.GetObject("_001"), 10, 70); } } 添加资源图片,获取图片实

积跬步,聚小流------java获取图片的尺寸

在一篇文章中获取到通过例如以下两种方式进行获取: 1.使用ImageReader进行获取: 2.使用BufferedImage进行获取: 而且经过验证ImageReader进行操作的耗时远远低于BufferedImage操作的耗时,详情可查看链接查看原文 然后依据应用我自己在项目中略做修改,在这里记录下: <span style="font-size:14px;">package com.jzba.utils; import java.awt.image.BufferedI

JavaScript获取图片的原始尺寸

页面里的img元素,想要获取它的原始尺寸,以宽度为例可能首先想到的就是width,如下 1 2 3 4 5 <img src=" http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg"> <script> var img = document.getElementsByTagName('img')[0] var width =