Exemple #1
0
/**
 * a_geotag_create_waypoint_positioned:
 * @filename: The image file to process
 * @coord:    The location for positioning the Waypoint
 * @name:     Returns a name for the Waypoint (can be NULL)
 *
 * Returns: An allocated Waypoint or NULL if Waypoint could not be generated
 *
 *  Here EXIF processing is used to get non position related information (i.e. just the comment)
 *
 */
VikWaypoint* a_geotag_create_waypoint_positioned ( const gchar *filename, VikCoord coord, gdouble alt, gchar **name )
{
	*name = NULL;
	VikWaypoint *wp = vik_waypoint_new();
	wp->visible = TRUE;
	wp->coord = coord;
	wp->altitude = alt;

	ExifData *ed = exif_data_new_from_file ( filename );

	// Set info from exif values
	if ( ed ) {
		wp->comment = geotag_get_exif_comment ( ed );

		gchar str[128];
		ExifEntry *ee;
		// Name
		ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_TITLE);
		if ( ee ) {
			exif_entry_get_value ( ee, str, 128 );
			*name = g_strdup ( str );
		}

		// Finished with EXIF
		exif_data_free ( ed );
	}

	vik_waypoint_set_image ( wp, filename );


	return wp;
}
// Implementation using libexif
void ImageResolution::readexif(char const *fn) {
  ExifData *ed;
  ed = exif_data_new_from_file(fn);
  if (!ed)
    return;
  ExifByteOrder byte_order = exif_data_get_byte_order(ed);
  
  ExifEntry *xres = exif_content_get_entry(ed->ifd[EXIF_IFD_0],
					   EXIF_TAG_X_RESOLUTION);
  ExifEntry *yres = exif_content_get_entry(ed->ifd[EXIF_IFD_0],
					   EXIF_TAG_Y_RESOLUTION);
  ExifEntry *unit = exif_content_get_entry(ed->ifd[EXIF_IFD_0],
					   EXIF_TAG_RESOLUTION_UNIT);
  if (xres && yres) {
    x_ = exifDouble(xres, byte_order);
    y_ = exifDouble(yres, byte_order);
    if (unit) {
      double u = exifDouble(unit, byte_order);
      if (u==3) {
	x_ *= 2.54;
	y_ *= 2.54;
      }
    }
    ok_ = true;
  }
  exif_data_free(ed);
}
Exemple #3
0
static bool readExif(const char* path, float& shutter)
{
  ExifData* data = exif_data_new_from_file(path);
  if (data == nullptr)
    return false;
  
  ExifEntry *shutterEnt;
  shutterEnt = exif_content_get_entry(data->ifd[EXIF_IFD_EXIF],
                                      EXIF_TAG_EXPOSURE_TIME);
  if(!shutterEnt)
    shutterEnt = exif_content_get_entry(data->ifd[EXIF_IFD_0],
                                        EXIF_TAG_EXPOSURE_TIME);
  if(!shutterEnt)
    shutterEnt = exif_content_get_entry(data->ifd[EXIF_IFD_1],
                                        EXIF_TAG_EXPOSURE_TIME);
  
  if(shutterEnt == NULL){
    fprintf(stderr, "Error: Cannot read photography info.\n");
    exif_data_unref(data);
    return false;
  }
  
  char buf[1024];
  exif_entry_get_value(shutterEnt, buf, sizeof(buf));
  printf("shutter = %s\n", buf);
  
  ExifSRational r;
  r = exif_get_srational(shutterEnt->data, exif_data_get_byte_order(data));
  shutter = (float)r.numerator / (float)r.denominator;
  
  // Close
  exif_data_unref(data);
  return true;
}
///@todo create a dedicated EXIF class
QString ImageImporter::getExifData(const QString& filename, ExifTag tag)
{
    ExifData* ed = exif_data_new_from_file(filename.ascii());
    ExifContent* c0, * c1, * cExif;

    c0    = ed->ifd[EXIF_IFD_0];
    c1    = ed->ifd[EXIF_IFD_1];
    cExif = ed->ifd[EXIF_IFD_EXIF];

    switch (tag) {
    case EXIF_TAG_MAKE:
    case EXIF_TAG_MODEL:
    case EXIF_TAG_SOFTWARE:
        return getEntry(c0, tag);
        break;

    case EXIF_TAG_EXPOSURE_TIME:
    case EXIF_TAG_FNUMBER:
    case EXIF_TAG_PIXEL_X_DIMENSION:
    case EXIF_TAG_PIXEL_Y_DIMENSION:
    case EXIF_TAG_FLASH:
    case EXIF_TAG_FOCAL_LENGTH_IN_35MM_FILM:
    case EXIF_TAG_ISO_SPEED_RATINGS:
    case EXIF_TAG_DATE_TIME_ORIGINAL:
        return getEntry(cExif, tag);
        break;

    default:
        return "";
        break;
    }

    exif_data_free(ed);
}
Exemple #5
0
long GalleryUtil::GetNaturalRotation(const QString &filePathString)
{
    long rotateAngle = 0;

#ifdef EXIF_SUPPORT
    QByteArray filePathBA = filePathString.toLocal8Bit();
    const char *filePath = filePathBA.constData();

    try
    {
        ExifData *data = exif_data_new_from_file(filePath);
        if (data)
        {
            rotateAngle = GetNaturalRotation(data);
            exif_data_free(data);
        }
        else
        {
            LOG(VB_FILE, LOG_ERR, LOC +
                QString("Could not load exif data from '%1'") .arg(filePath));
        }
    }
    catch (...)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to extract EXIF headers from '%1'") .arg(filePath));
    }
#else
    // Shut the compiler up about the unused argument
    (void)filePathString;
#endif

    return rotateAngle;
}
Exemple #6
0
/**
 * a_geotag_get_exif_date_from_file:
 * @filename: The image file to process
 * @has_GPS_info: Returns whether the file has existing GPS information
 *
 * Returns: An allocated string with the date and time in EXIF_DATE_FORMAT, otherwise NULL if some kind of failure
 *
 *  Here EXIF processing is used to get time information
 *
 */
gchar* a_geotag_get_exif_date_from_file ( const gchar *filename, gboolean *has_GPS_info )
{
	gchar* datetime = NULL;

	ExifData *ed = exif_data_new_from_file ( filename );

	// Detect EXIF load failure
	if ( !ed )
		return datetime;

	gchar str[128];
	ExifEntry *ee;

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
	if ( ee ) {
		exif_entry_get_value ( ee, str, 128 );
		datetime = g_strdup ( str );
	}

	// Check GPS Info
	*has_GPS_info = FALSE;
	
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
	// Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
	if ( ee && ee->components == 4 )
		*has_GPS_info = TRUE;

	exif_data_free ( ed );

	return datetime;
}
Exemple #7
0
QPixmap ExifPixmap::createPixmap(QString path)
{
    ExifData *exifData = exif_data_new_from_file(path.toStdString().c_str());
    int orientation = 0;
    if(exifData) {
        ExifByteOrder byteOrder = exif_data_get_byte_order(exifData);
        ExifEntry *exifEntry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
        if(exifEntry) {
            orientation = exif_get_short(exifEntry->data, byteOrder);
        }
        exif_data_free(exifData);
    }
    QPixmap pic(path);
    /*
              0th Row      0th Column
           1  top          left side
           2  top          right side
           3  bottom       right side
           4  bottom       left side
           5  left side    top
           6  right side   top
           7  right side   bottom
           8  left side    bottom
        */
    QTransform t;
    switch(orientation) { // TODO : test flips
    case 1:
        break;
    case 2:
        t.scale(-1,1);
        break;
    case 3:
        t.rotate(180);
        break;
    case 4:
        t.rotate(180);
        t.scale(-1,1);
        break;
    case 5:
        t.rotate(90);
        t.scale(-1,1);
        break;
    case 6:
        t.rotate(90);
        break;
    case 7:
        t.rotate(-90);
        t.scale(-1,1);
        break;
    case 8:
        t.rotate(-90);
        break;
    default:
        break;
    }

    return pic.transformed(t);
}
Exemple #8
0
static QImage* reorient_with_exif( producer_qimage self, int image_idx, QImage *qimage )
{
#ifdef USE_EXIF
	mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( &self->parent );
	ExifData *d = exif_data_new_from_file( mlt_properties_get_value( self->filenames, image_idx ) );
	ExifEntry *entry;
	int exif_orientation = 0;
	/* get orientation and rotate image accordingly if necessary */
	if (d) {
		if ( ( entry = exif_content_get_entry ( d->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION ) ) )
			exif_orientation = exif_get_short (entry->data, exif_data_get_byte_order (d));

		/* Free the EXIF data */
		exif_data_unref(d);
	}

	// Remember EXIF value, might be useful for someone
	mlt_properties_set_int( producer_props, "_exif_orientation" , exif_orientation );

	if ( exif_orientation > 1 )
	{
		  // Rotate image according to exif data
		  QImage processed;
		  QMatrix matrix;

		  switch ( exif_orientation ) {
		  case 2:
			  matrix.scale( -1, 1 );
			  break;
		  case 3:
			  matrix.rotate( 180 );
			  break;
		  case 4:
			  matrix.scale( 1, -1 );
			  break;
		  case 5:
			  matrix.rotate( 270 );
			  matrix.scale( -1, 1 );
			  break;
		  case 6:
			  matrix.rotate( 90 );
			  break;
		  case 7:
			  matrix.rotate( 90 );
			  matrix.scale( -1, 1 );
			  break;
		  case 8:
			  matrix.rotate( 270 );
			  break;
		  }
		  processed = qimage->transformed( matrix );
		  delete qimage;
		  qimage = new QImage( processed );
	}
#endif
	return qimage;
}
Exemple #9
0
/**
 * a_geotag_get_exif_date_from_file:
 * @filename: The image file to process
 * @has_GPS_info: Returns whether the file has existing GPS information
 *
 * Returns: An allocated string with the date and time in EXIF_DATE_FORMAT, otherwise NULL if some kind of failure
 *
 *  Here EXIF processing is used to get time information
 *
 */
gchar* a_geotag_get_exif_date_from_file ( const gchar *filename, gboolean *has_GPS_info )
{
	gchar* datetime = NULL;
	*has_GPS_info = FALSE;

#ifdef HAVE_LIBGEXIV2
	GExiv2Metadata *gemd = gexiv2_metadata_new ();
	if ( gexiv2_metadata_open_path ( gemd, filename, NULL ) ) {
		gdouble lat, lon;
		*has_GPS_info = ( gexiv2_metadata_get_gps_longitude(gemd,&lon) && gexiv2_metadata_get_gps_latitude(gemd,&lat) );

		// Prefer 'Photo' version over 'Image'
		if ( gexiv2_metadata_has_tag ( gemd, "Exif.Photo.DateTimeOriginal" ) )
			datetime = g_strdup ( gexiv2_metadata_get_tag_interpreted_string ( gemd, "Exif.Photo.DateTimeOriginal" ) );
		else
			datetime = g_strdup ( gexiv2_metadata_get_tag_interpreted_string ( gemd, "Exif.Image.DateTimeOriginal" ) );
	}
	metadata_free ( gemd );
#else
#ifdef HAVE_LIBEXIF
	ExifData *ed = exif_data_new_from_file ( filename );

	// Detect EXIF load failure
	if ( !ed )
		return datetime;

	gchar str[128];
	ExifEntry *ee;

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
	if ( ee ) {
		exif_entry_get_value ( ee, str, 128 );
		datetime = g_strdup ( str );
	}

	// Check GPS Info

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
	// Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
	if ( ee && ee->components == 4 )
		*has_GPS_info = TRUE;

	// Check other basic GPS fields exist too
	// I have encountered some images which have just the EXIF_TAG_GPS_VERSION_ID but nothing else
	// So to confirm check more EXIF GPS TAGS:
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LATITUDE);
	if ( !ee )
		*has_GPS_info = FALSE;
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LONGITUDE);
	if ( !ee )
		*has_GPS_info = FALSE;

	exif_data_free ( ed );
#endif
#endif
	return datetime;
}
Exemple #10
0
Fichier : exif.c Projet : 0ion9/feh
/* return data structure with exif data if available */
ExifData * exif_get_data(char *path)
{
  ExifData *ed = NULL;

  /* Load an ExifData object from an EXIF file */
  ed = exif_data_new_from_file(path);
  if (ed == NULL)
  {
    D(("File not readable or no Exif data present in %s\n", path));
  }

  return(ed);
}
Exemple #11
0
gboolean
rstto_file_has_exif ( RsttoFile *r_file )
{
    if ( NULL == r_file->priv->exif_data )
    {
        r_file->priv->exif_data = exif_data_new_from_file ( rstto_file_get_path (r_file) );
    }
    if ( NULL == r_file->priv->exif_data )
    {
        return FALSE;
    }
    return TRUE;
}
Exemple #12
0
void Image::load_tags( const gchar * filename )
{
	g_assert( filename );

	if ( ExifData * ed = exif_data_new_from_file( filename ) )
	{
		load_exif_tags( ed , tags );
		exif_data_unref( ed );
	}
	else
	{
		tplog2( "  FAILED TO LOAD TAGS" );
	}
}
Exemple #13
0
//#include "libexif/exif-tag.h"   //EXIF_TAG_ORIENTATION
enum Orientation orient( const char * path) {
    enum Orientation orientation = NOT_AVAILABLE;

    ExifData * mExifData = exif_data_new_from_file( path);
    if (mExifData) {
        ExifEntry * mOrientationEntry = exif_content_get_entry( mExifData->ifd[ EXIF_IFD_0], EXIF_TAG_ORIENTATION);
        if (mOrientationEntry) {
            ExifByteOrder mByteOrder = exif_data_get_byte_order( mExifData);
            short value=exif_get_short( mOrientationEntry->data, mByteOrder);
            if (value>=NORMAL && value<=ROT_270)
                orientation = value;    //Orientation( value);
        }
        exif_data_unref( mExifData );
    }
    return orientation;
}
Exemple #14
0
/**
 * a_geotag_waypoint_positioned:
 * @filename: The image file to process
 * @coord:    The location for positioning the Waypoint
 * @name:     Returns a name for the Waypoint (can be NULL)
 * @waypoint: An existing waypoint to update (can be NULL to generate a new waypoint)
 *
 * Returns: An allocated waypoint if the input waypoint is NULL,
 *  otherwise the passed in waypoint is updated
 *
 *  Here EXIF processing is used to get non position related information (i.e. just the comment)
 *
 */
VikWaypoint* a_geotag_waypoint_positioned ( const gchar *filename, VikCoord coord, gdouble alt, gchar **name, VikWaypoint *wp )
{
	*name = NULL;
	if ( wp == NULL ) {
		// Need to create waypoint
		wp = vik_waypoint_new();
		wp->visible = TRUE;
	}
	wp->coord = coord;
	wp->altitude = alt;

#ifdef HAVE_LIBGEXIV2
	GExiv2Metadata *gemd = gexiv2_metadata_new ();
	if ( gexiv2_metadata_open_path ( gemd, filename, NULL ) ) {
			wp->comment = geotag_get_exif_comment ( gemd );
			if ( gexiv2_metadata_has_tag ( gemd, "Exif.Image.XPTitle" ) )
				*name = g_strdup ( gexiv2_metadata_get_tag_interpreted_string ( gemd, "Exif.Image.XPTitle" ) );
	}
	metadata_free ( gemd );
#else
#ifdef HAVE_LIBEXIF
	ExifData *ed = exif_data_new_from_file ( filename );

	// Set info from exif values
	if ( ed ) {
		wp->comment = geotag_get_exif_comment ( ed );

		gchar str[128];
		ExifEntry *ee;
		// Name
		ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_TITLE);
		if ( ee ) {
			exif_entry_get_value ( ee, str, 128 );
			*name = g_strdup ( str );
		}

		// Finished with EXIF
		exif_data_free ( ed );
	}
#endif
#endif

	vik_waypoint_set_image ( wp, filename );

	return wp;
}
Exemple #15
0
void exif_auto_orientate(const fileinfo_t *file) {
	ExifData *ed;
	ExifEntry *entry;
	int byte_order, orientation;

	if ((ed = exif_data_new_from_file(file->path)) == NULL)
		return;
	entry = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);
	if (entry != NULL) {
		byte_order = exif_data_get_byte_order(ed);
		orientation = exif_get_short(entry->data, byte_order);
	}
	exif_data_unref(ed);
	if (entry == NULL)
		return;

	switch (orientation) {
		case 5:
			imlib_image_orientate(1);
		case 2:
			imlib_image_flip_vertical();
			break;

		case 3:
			imlib_image_orientate(2);
			break;

		case 7:
			imlib_image_orientate(1);
		case 4:
			imlib_image_flip_horizontal();
			break;

		case 6:
			imlib_image_orientate(1);
			break;

		case 8:
			imlib_image_orientate(3);
			break;
	}
}
Exemple #16
0
ExifEntry *
rstto_file_get_exif ( RsttoFile *r_file, ExifTag id )
{
    /* If there is no exif-data object, try to create it */
    if ( NULL == r_file->priv->exif_data )
    {
        r_file->priv->exif_data = exif_data_new_from_file (
                rstto_file_get_path (r_file) );
    }

    if ( NULL != r_file->priv->exif_data )
    {
        return exif_data_get_entry (
                r_file->priv->exif_data,
                id );
    }

    /* If there is no exif-data, return NULL */
    return NULL;
}
Exemple #17
0
/**
 * a_geotag_get_position:
 *
 * @filename: The (JPG) file with EXIF information in it
 *
 * Returns: The position in LatLon format.
 *  It will be 0,0 if some kind of failure occurs.
 */
struct LatLon a_geotag_get_position ( const gchar *filename )
{
	struct LatLon ll = { 0.0, 0.0 };

#ifdef HAVE_LIBGEXIV2
	GExiv2Metadata *gemd = gexiv2_metadata_new ();
	if ( gexiv2_metadata_open_path ( gemd, filename, NULL ) ) {
		gdouble lat;
		gdouble lon;
		gdouble alt;
		if ( gexiv2_metadata_get_gps_info ( gemd, &lon, &lat, &alt ) ) {
			ll.lat = lat;
			ll.lon = lon;
		}
	}
	metadata_free  ( gemd );
#else
#ifdef HAVE_LIBEXIF
	// open image with libexif
	ExifData *ed = exif_data_new_from_file ( filename );

	// Detect EXIF load failure
	if ( !ed )
		return ll;

	ExifEntry *ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
	// Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
	if ( ! ( ee && ee->components == 4 ) )
		goto MyReturn0;

	ll = get_latlon ( ed );

MyReturn0:
	// Finished with EXIF
	exif_data_free ( ed );
#endif
#endif

	return ll;
}
Exemple #18
0
int
main (int argc, char **argv)
{
	ExifData *d;
	unsigned int buf_size;
	unsigned char *buf;
	int r;

	if (argc <= 1) {
		fprintf (stderr, "You need to supply a filename!\n");
		return 1;
	}

	fprintf (stdout, "Loading '%s'...\n", argv[1]);
	d = exif_data_new_from_file (argv[1]);
	if (!d) {
		fprintf (stderr, "Could not load data from '%s'!\n", argv[1]);
		return 1;
	}
	fprintf (stdout, "Loaded '%s'.\n", argv[1]);

	fprintf (stdout, "######### Test 1 #########\n");
	r = test_exif_data (d);
	if (r) return r;

	exif_data_save_data (d, &buf, &buf_size);
	exif_data_unref (d);
	d = exif_data_new_from_data (buf, buf_size);
	free (buf);

	fprintf (stdout, "######### Test 2 #########\n");
	r = test_exif_data (d);
	if (r) return r;

	fprintf (stdout, "Test successful!\n");

	return 1;
}
Exemple #19
0
QDateTime Exif2GPX::getTimeFromEXIF(const QString& filename) {
  
  // load the exif data
  ExifData* exifData;
  if (!(exifData = exif_data_new_from_file((const char*)filename))) {
    std::cerr<<"Could not load EXIF data from "<<filename<<std::endl;
    return QDateTime();
  }
  
  // find the timestamp
  ExifEntry* entry;
  entry = exif_content_get_entry(exifData->ifd[EXIF_IFD_0], 
				 EXIF_TAG_DATE_TIME);
  if (!entry)
    entry = exif_content_get_entry(exifData->ifd[EXIF_IFD_EXIF],
				   EXIF_TAG_DATE_TIME_ORIGINAL);
  if (!entry)
    entry = exif_content_get_entry(exifData->ifd[EXIF_IFD_EXIF],
				   EXIF_TAG_DATE_TIME_DIGITIZED);
  if (!entry) {
    std::cerr<<"Could not find a valid timestamp in "<<filename<<std::endl;
    return QDateTime();
  }
  
  // parse it
  int year, month, day, hour, minute, second;
  if (std::sscanf((char*)entry->data, "%d:%d:%d %d:%d:%d", &year, &month, &day,
		  &hour, &minute, &second) != 6) {
    std::cerr<<"Could not find a valid timestamp in "<<filename<<std::endl;
    return QDateTime();
  }
  QDateTime timestamp(QDate(year, month, day), QTime(hour, minute, second));
  
  std::cerr<<filename<<": "<<timestamp.toString()<<std::endl;

  return timestamp;
}
Exemple #20
0
static int
get_file_func (CameraFilesystem *fs, const char *folder, const char *filename,
	       CameraFileType type, CameraFile *file, void *user_data,
	       GPContext *context)
{
        char path[1024];
	int result = GP_OK;
	struct stat stbuf;
	int fd, id;
	unsigned int curread, toread;
	unsigned char *buf;
#ifdef HAVE_LIBEXIF
	ExifData *data;
	unsigned int buf_len;
#endif /* HAVE_LIBEXIF */
	Camera *camera = (Camera*)user_data;

	result = _get_path (camera->port, folder, filename, path, sizeof(path));
	gp_log (GP_LOG_DEBUG, "directory/get_file_func", "%s %s",folder,filename);
	if (result < GP_OK)
		return result;
	gp_log (GP_LOG_DEBUG, "directory/get_file_func", "->%s",path);
	

	switch (type) {
	case GP_FILE_TYPE_NORMAL:
#ifdef DEBUG
	case GP_FILE_TYPE_PREVIEW:
#endif
		fd = open (path,O_RDONLY);
		if (fd == -1)
			return GP_ERROR_IO_READ;
		break;
#ifdef HAVE_LIBEXIF
	case GP_FILE_TYPE_EXIF:
		data = exif_data_new_from_file (path);
		if (!data) {
			gp_context_error (context, _("Could not open '%s'."),
					  path);
			return (GP_ERROR);
		}
		exif_data_save_data (data, &buf, &buf_len);
		exif_data_unref (data);
		gp_file_set_data_and_size (file, buf, buf_len);
		return (GP_OK);
#endif /* HAVE_LIBEXIF */
	default:
		return (GP_ERROR_NOT_SUPPORTED);
	}

	if (-1 == fstat(fd,&stbuf)) {
		close (fd);
		return GP_ERROR_IO_READ;
	}
#define BLOCKSIZE 65536
	/* do it in 64kb blocks */
	buf = malloc(BLOCKSIZE);
	if (!buf) {
		close (fd);
		return GP_ERROR_NO_MEMORY;
	}

	curread = 0;
	id = gp_context_progress_start (context, (1.0*stbuf.st_size/BLOCKSIZE), _("Getting file..."));
	GP_DEBUG ("Progress id: %i", id);
	result = GP_OK;
	while (curread < stbuf.st_size) {
		int ret;

		toread = stbuf.st_size-curread;
		if (toread>BLOCKSIZE) toread = BLOCKSIZE;
		ret = read(fd,buf,toread);
		if (ret == -1) {
			result = GP_ERROR_IO_READ;
			break;
		}
		curread += ret;
		gp_file_append (file, buf, ret);
		gp_context_progress_update (context, id, (1.0*curread/BLOCKSIZE));
		gp_context_idle (context);
		if (gp_context_cancel (context) == GP_CONTEXT_FEEDBACK_CANCEL) {
			result = GP_ERROR_CANCEL;
			break;
		}
#if 0
		/* We could take 2 seconds to download this image. everytime. */
		/* But actually this driver is used in production by some frontends,
		 * so do not delay at all
		 */
		usleep(2000000/(stbuf.st_size/BLOCKSIZE));
#endif
	}
	gp_context_progress_stop (context, id);
	free (buf);
	close (fd);
	return (GP_OK);
}
Exemple #21
0
void ChatImageItem::downloadOrViewImage()
{
    if (retryButton)
    {
        message.status = FMessage::Uploading;
        retryButton = false;
        setButton();

        emit mediaUpload(message);

    } else if (message.media_wa_type == FMessage::Location)
    {
        QString url = (message.media_url.isEmpty())
                ? URL_LOCATION_SHARING +
                    QString::number(message.latitude) + "," +
                    QString::number(message.longitude) + "+(" +
                    message.notify_name.replace("<","&lt;").replace(">","&gt;") + ")"
                : message.media_url;
        QDesktopServices::openUrl(QUrl(url));
    }
    else if (!message.local_file_uri.isEmpty())
    {
        QString uri = "file://" + message.local_file_uri;

        QDBusConnection dbus = QDBusConnection::sessionBus();


        switch (message.media_wa_type)
        {
            case FMessage::Audio:
                if (message.live)
                {
                    AudioPlayer *player = new AudioPlayer(this);

                    connect(player,SIGNAL(progress(int)),this,SLOT(updateTime(int)));
                    connect(player,SIGNAL(finished()),this,SLOT(finishedAudioPlay()));

                    ui->viewImageButton->setEnabled(false);

                    player->play(uri);

                    // We need to notificate the sender that we played the audio
                    emit voiceNotePlayed(message);
                    break;
                }

            case FMessage::Video:
                {
                    DBusNokiaMediaPlayerIf *mediaPlayerBus =
                            new DBusNokiaMediaPlayerIf(NOKIA_MEDIAPLAYER_DBUS_NAME,
                                                       NOKIA_MEDIAPLAYER_DBUS_PATH,
                                                       dbus,this);

                    mediaPlayerBus->mime_open(uri);
                }
                break;

            case FMessage::Image:
                {
                    // The following is to avoid an Image Viewer bug where files without
                    // EXIF data can't be opened.

                    QImageReader image(message.local_file_uri);

                    if (image.format() == "jpeg")
                    {
                        ExifData *ed = exif_data_new_from_file(message.local_file_uri.toUtf8().constData());

                        if (!ed)
                        {
                            ed = exif_data_new();
                            if (ed)
                            {
                                Utilities::logData("Creating default Exif data.");
                                ExifEntry *entry = exif_entry_new();

                                exif_content_add_entry(ed->ifd[EXIF_IFD_0], entry);

                                exif_entry_initialize(entry, EXIF_TAG_IMAGE_DESCRIPTION);
                                entry->data = (unsigned char *) YAPPARI_APPLICATION_NAME;

                                JPEGData *jpeg = jpeg_data_new_from_file(message.local_file_uri.toUtf8().constData());

                                jpeg_data_set_exif_data(jpeg, ed);

                                jpeg_data_save_file(jpeg, message.local_file_uri.toUtf8().constData());
                                jpeg_data_unref(jpeg);
                            }
                        }

                        if (ed)
                            exif_data_unref(ed);
                    }

                    DBusNokiaImageViewerIf *imageViewerBus =
                    new DBusNokiaImageViewerIf(NOKIA_IMAGEVIEWER_DBUS_NAME,
                                               NOKIA_IMAGEVIEWER_DBUS_PATH,
                                               dbus,this);

                    imageViewerBus->mime_open(uri);
                }
                break;
        }
Exemple #22
0
/**
 * Analyzes a file and copies it if it contains image data.
 * @param fpath The filename of the current entry.
 * @param sb A pointer to the stat structure.
 * @param typeflag The current entry type.
 */
static int
_ftw_callback(char const* fpath, struct stat const* sb, int typeflag)
{
  int rc;
  ExifData* exif_data;
  ExifEntry* exif_entry;
  char exif_entry_val[20];
  struct tm tm;

  // The current entry is not a file. Skip it.
  if (!S_ISREG(sb->st_mode)) {
    return 0;
  }

  // The current entry has no EXIF data. Skip it.
  exif_data = exif_data_new_from_file(fpath);
  if (exif_data == NULL) {
    return 0;
  }

  rc = 0;
  exif_entry = exif_content_get_entry(*(exif_data->ifd), EXIF_TAG_DATE_TIME);

  if (exif_entry != NULL
      && exif_entry_get_value(exif_entry, exif_entry_val, 20) != NULL
      && strptime(exif_entry_val, "%Y:%m:%d %H:%M:%S", &tm) != 0) {
    size_t dst_size;
    char* dst;

    dst_size = strlen(_DST) + 12;
    dst = (char*) malloc(dst_size);

    // Create the destination path.
    if (snprintf(dst, dst_size, "%s/%d/%02d/%02d", _DST, tm.tm_year + 1900,
                 tm.tm_mon + 1, tm.tm_mday) >= 0
        && _mkdir_recursive(dst) == 0) {
      size_t offset;
      char* dst_fpath;

      offset = strlen(fpath);
      while (offset > 0 && fpath[offset - 1] != '/') {
        --offset;
      }

      // Copy the file.
      dst_fpath = (char*) malloc(strlen(dst) + strlen(fpath + offset) + 2);
      sprintf(dst_fpath, "%s/%s", dst, fpath + offset);
      rc = _cp(dst_fpath, fpath);
      free(dst_fpath);

      if (rc == -1 && errno == EEXIST) {
        rc = 0;
      }
    }

    free(dst);
  }

  exif_data_unref(exif_data);
  return rc;
}
Exemple #23
0
QDateTime GalleryUtil::GetTimestamp(const QString &filePath)
{
    QDateTime timestamp;

    try
    {
#ifdef EXIF_SUPPORT
#if NEW_LIB_EXIF
        char *exifvalue = new char[20];
#endif
        ExifData *data = exif_data_new_from_file(
            filePath.toLocal8Bit().constData());
        if (data)
        {
            for (int i = 0; i < EXIF_IFD_COUNT; i++)
            {
                ExifEntry *entry = exif_content_get_entry (data->ifd[i],
                    EXIF_TAG_DATE_TIME_ORIGINAL);
                if (entry)
                {
#if NEW_LIB_EXIF
                    exif_entry_get_value(entry, exifvalue, 20);
                    QString formatted = exifvalue;
#else
                    QString formatted = exif_entry_get_value(entry);
#endif
                    timestamp = QDateTime::fromString(formatted,
                        "yyyy:MM:dd hh:mm:ss");
                    if (timestamp.isValid())
                    {
                        // Found one, done
                        break;
                    }
                    else
                    {
                        LOG(VB_FILE, LOG_ERR, LOC +
                            QString("Could not parse exif timestamp from '%1'")
                            .arg(filePath));
                    }
                }
            }
            exif_data_free(data);
        }
        else
        {
           LOG(VB_FILE, LOG_ERR, LOC +
               QString("Could not load exif data from '%1'") .arg(filePath));
        }
#if NEW_LIB_EXIF
        delete [] exifvalue;
#endif
#endif // EXIF_SUPPORT
    }
    catch (...)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to extract EXIF headers from '%1'") .arg(filePath));
    }

    return timestamp;
}
Exemple #24
0
QString GalleryUtil::GetCaption(const QString &filePath)
{
    QString caption("");

    try
    {
#ifdef EXIF_SUPPORT
#if NEW_LIB_EXIF
        char *exifvalue = new char[1024];
#endif
        ExifData *data = exif_data_new_from_file(
            filePath.toLocal8Bit().constData());
        if (data)
        {
            for (int i = 0; i < EXIF_IFD_COUNT; i++)
            {
                ExifEntry *entry = exif_content_get_entry (data->ifd[i],
                                                    EXIF_TAG_USER_COMMENT);
                if (entry)
                {
#if NEW_LIB_EXIF
                    exif_entry_get_value(entry, exifvalue, 1024);
                    caption = exifvalue;
#else
                    caption = exif_entry_get_value(entry);
#endif
                    // Found one, done
                    if(!caption.trimmed().isEmpty())
                       break;
                }

                entry = exif_content_get_entry (data->ifd[i],
                                                EXIF_TAG_IMAGE_DESCRIPTION);
                if (entry)
                {
#if NEW_LIB_EXIF
                    exif_entry_get_value(entry, exifvalue, 1024);
                    caption = exifvalue;
#else
                    caption = exif_entry_get_value(entry);
#endif
                    // Found one, done
                    if(!caption.trimmed().isEmpty())
                       break;
                }
            }
            exif_data_free(data);
        }
        else
        {
           LOG(VB_FILE, LOG_ERR, LOC +
               QString("Could not load exif data from '%1'") .arg(filePath));
        }
#if NEW_LIB_EXIF
        delete [] exifvalue;
#endif
#endif // EXIF_SUPPORT
    }
    catch (...)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to extract EXIF headers from '%1'") .arg(filePath));
    }

    return caption;
}
LocImageContainer ImageProcessor::process (QString filename)
{
	QImage image (m_data);

	if (!image.isNull()) {
		image = image.scaled(720, 500, Qt::KeepAspectRatioByExpanding);
	}

	LocImageContainer locImageContainer(image);

	locImageContainer.setAltitude(3000.00);

	//get exif data
	ExifData *ed = exif_data_new_from_file (filename.toLocal8Bit().constData());

	if (!ed) {
		locImageContainer.setLocationAvailable(false);
		locImageContainer.setExifDataAvailable(false);

		return locImageContainer;
	}

	locImageContainer.setExifDataAvailable(true);

	//save temp
	char value[256]={0,};

	// Retrieve make
	QString make;
	ExifEntry *ee = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);
	if (!ee) {
		make = "";
	} else {
		exif_entry_get_value(ee, value, sizeof(value));
		locImageContainer.setMake (QString(value));
	}

	// Retrieve model
	ee = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_MODEL);
	if (!ee) {
		locImageContainer.setCameraModel ("");
	} else {
		exif_entry_get_value(ee, value, sizeof(value));
		locImageContainer.setCameraModel ("Taken with the "+QString(value));
	}

	// Retrieve time
	ee = exif_content_get_entry(ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
	if (!ee) {
		locImageContainer.setDateTaken ("");
	} else {
		exif_entry_get_value(ee, value, sizeof(value));
		QString dateTime(value);

		QDateTime dateTaken = QDateTime::fromString (dateTime, "yyyy:MM:dd HH:mm:ss");
		locImageContainer.setDateTaken (dateTaken.toString("'on 'dddd d, MMMM yyyy 'at' HH:mm"));
	}

	// Retrieve LATITUDE
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], (ExifTag)EXIF_TAG_GPS_LATITUDE);
	if (!ee) {
		locImageContainer.setLocationAvailable(false);
		locImageContainer.setLatitude(-9999.99);
	} else {
		if ( ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
		{
			double lat = Rational2Double ( ee->data,
					exif_format_get_size(ee->format),
					exif_data_get_byte_order(ed) );

			ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], (ExifTag)EXIF_TAG_GPS_LATITUDE_REF);
			if ( ee ) {
				exif_entry_get_value ( ee, value, 128 );
				if ( value[0] == 'S' )
					lat = -lat;
			}

			locImageContainer.setLocationAvailable(true);
			locImageContainer.setLatitude (lat);
		}
	}

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], (ExifTag)EXIF_TAG_GPS_LONGITUDE);
	if (!ee) {
		locImageContainer.setLocationAvailable(false);
		locImageContainer.setLongitude(-9999.99);
	} else {
		if ( ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
		{
			double lon = Rational2Double ( ee->data,
					exif_format_get_size(ee->format),
					exif_data_get_byte_order(ed) );

			ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], (ExifTag)EXIF_TAG_GPS_LONGITUDE_REF);
			if ( ee ) {
				exif_entry_get_value ( ee, value, 128 );
				if ( value[0] == 'W' )
					lon = -lon;
			}

			locImageContainer.setLocationAvailable(true);
			locImageContainer.setLongitude (lon);
		}
	}

	exif_data_free(ed);

	return locImageContainer;
}
void ThumbGenerator::loadFile(QImage& image, const QFileInfo& fi)
{
    static int sequence = 0;

    if (GalleryUtil::IsMovie(fi.filePath()))
    {
        bool thumbnailCreated = false;
        QDir tmpDir("/tmp/mythgallery");
        if (!tmpDir.exists())
        {
            if (!tmpDir.mkdir(tmpDir.absolutePath()))
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Unable to create temp dir for movie thumbnail creation: " +
                    tmpDir.absolutePath());
            }
        }

        if (tmpDir.exists())
        {
            QString thumbFile = QString("%1.png")
                .arg(++sequence,8,10,QChar('0'));

            QString cmd = "mythpreviewgen";
            QStringList args;
            args << logPropagateArgs.split(" ", QString::SkipEmptyParts);
            args << "--infile" << '"' + fi.absoluteFilePath() + '"';
            args << "--outfile" << '"' + tmpDir.filePath(thumbFile) + '"';

            MythSystemLegacy ms(cmd, args, kMSRunShell);
            ms.SetDirectory(tmpDir.absolutePath());
            ms.Run();
            if (ms.Wait() == GENERIC_EXIT_OK)
            {
                QFileInfo thumb(tmpDir.filePath(thumbFile));
                if (thumb.exists())
                {
                    QImage img(thumb.absoluteFilePath());
                    image = img;
                    thumbnailCreated = true;
                }
            }
        }

        if (!thumbnailCreated)
        {
            QImage *img = GetMythUI()->LoadScaleImage("gallery-moviethumb.png");
            if (img)
            {
                image = *img;
            }
        }
    }
    else
    {
#ifdef EXIF_SUPPORT
        // Try to get thumbnail from exif data
        ExifData *ed = exif_data_new_from_file(fi.absoluteFilePath()
                                               .toLocal8Bit().constData());
        if (ed && ed->data)
        {
            image.loadFromData(ed->data, ed->size);
        }

        if (ed)
            exif_data_free(ed);

        if (image.width() > m_width && image.height() > m_height)
            return;
#endif

#ifdef DCRAW_SUPPORT
        QString extension = fi.suffix();
        QSet<QString> dcrawFormats = DcrawFormats::getFormats();
        int rotateAngle;

        if (dcrawFormats.contains(extension) &&
            (rotateAngle = DcrawHandler::loadThumbnail(&image,
                                               fi.absoluteFilePath())) != -1 &&
            image.width() > m_width && image.height() > m_height)
        {
            if (rotateAngle != 0)
            {
                QMatrix matrix;
                matrix.rotate(rotateAngle);
                image = image.transformed(matrix);
            }

            return;
        }
#endif

        image.load(fi.absoluteFilePath());
    }
}
void FileSystemScanner::readEXIF(File* file)
{
    static QString EXIFIFD_NAME_EXIF = exif_ifd_get_name(EXIF_IFD_EXIF);

    int maxDataLength = 255;
    char* charData = new char[maxDataLength];

    ExifData* exifData = exif_data_new_from_file(file->fileInfo()->absFilePath().ascii());
//    exif_data_dump(exifData);

    for (int i = 0; i < EXIF_IFD_COUNT; i++) {
        ExifContent* content = exifData->ifd[i];

        QString group = QString(exif_ifd_get_name((ExifIfd) i));
        if (group == EXIFIFD_NAME_EXIF) {

            for (unsigned int e = 0; e < content->count; e++) {
                ExifEntry* entry = content->entries[e];

                ExifTag exifTagType = entry->tag;
                QString title = QString(exif_tag_get_title(entry->tag));
                QString name = QString(exif_tag_get_name(entry->tag));

                exif_entry_get_value(entry, charData, maxDataLength);
                QString data = QString(charData);

                QString description = QString(exif_tag_get_description(entry->tag));
//                tracer->sdebug(__func__) << "    - " << title << " / " << name << " = " << data << " (" << description << ")" << endl;

                // get the exif tagnode title and the tagnode representing this tag from the engine
                TagNode* exifTagNodeTitle = m_engine->exifTagNodeTitle();
                TagNode* exifTagNodeEntry = exifTagNodeTitle->child(title);

                switch (exifTagType) {
                    case EXIF_TAG_DATE_TIME_ORIGINAL:
                    case EXIF_TAG_DATE_TIME_DIGITIZED: {
                        QDateTime dateTime = readExifDateTime(data);
                        TagNodeDateTime* exifTagNodeEntryDateTime = dynamic_cast<TagNodeDateTime*>(exifTagNodeEntry);
                        if (exifTagNodeEntryDateTime == 0) {
                            // tagnode for this EXIF entry does not exist --> create it
                            exifTagNodeEntryDateTime = dynamic_cast<TagNodeDateTime*>(m_engine->createTag(exifTagNodeTitle, TagNode::TYPE_DATETIME, title, description, QString::null));
                            exifTagNodeEntryDateTime->setReadonly(true);
                        }
                        if (dateTime.isValid()) {
                            // create new assoc
                            new FileTagNodeAssocDateTime(file, exifTagNodeEntryDateTime, dateTime);
                        }

                        break;
                    }
                    default: {
                        TagNodeString* exifTagNodeEntryString = dynamic_cast<TagNodeString*>(exifTagNodeEntry);
                        if (exifTagNodeEntryString == 0) {
                            // tagnode for this EXIF entry does not exist --> create it
                            exifTagNodeEntryString = dynamic_cast<TagNodeString*>(m_engine->createTag(exifTagNodeTitle, TagNode::TYPE_STRING, title, description, QString::null));
                            exifTagNodeEntryString->setReadonly(true);
                        }
                        // create new assoc
                        new FileTagNodeAssocString(file, exifTagNodeEntryString, data);
                    }
                }
            }
        }
    }

    exif_data_free(exifData);
    delete charData;
}
Exemple #28
0
/**
 * a_geotag_write_exif_gps:
 * @filename: The image file to save information in
 * @coord:    The location
 * @alt:      The elevation
 *
 * Returns: A value indicating success: 0, or some other value for failure
 *
 */
gint a_geotag_write_exif_gps ( const gchar *filename, VikCoord coord, gdouble alt, gboolean no_change_mtime )
{
	gint result = 0; // OK so far...

	// Save mtime for later use
	struct stat stat_save;
	if ( no_change_mtime )
		stat ( filename, &stat_save );

	/*
	  Appears libexif doesn't actually support writing EXIF data directly to files
	  Thus embed command line exif writing method within Viking
	  (for example this is done by Enlightment - http://www.enlightenment.org/ )
	  This appears to be JPEG only, but is probably 99% of our use case
	  Alternatively consider using libexiv2 and C++...
	*/

	// Actual EXIF settings here...
	JPEGData *jdata;

	/* Parse the JPEG file. */
	jdata = jpeg_data_new ();
	jpeg_data_load_file (jdata, filename);

	// Get current values
	ExifData *ed = exif_data_new_from_file ( filename );
	if ( !ed )
		ed = exif_data_new ();

	// Update ExifData with our new settings
	ExifEntry *ee;
	//
	// I don't understand it, but when saving the 'ed' nothing gets set after putting in the GPS ID tag - so it must come last
	// (unless of course there is some bug in the setting of the ID, that prevents subsequent tags)
	//

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_ALTITUDE, EXIF_IFD_GPS);
	convert_to_entry ( NULL, alt, ee, exif_data_get_byte_order(ed) );

	// byte 0 meaning "sea level" or 1 if the value is negative.
	ee = my_exif_create_value (ed, EXIF_TAG_GPS_ALTITUDE_REF, EXIF_IFD_GPS);
	convert_to_entry ( alt < 0.0 ? "1" : "0", 0.0, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_PROCESSING_METHOD, EXIF_IFD_GPS);
	// see http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/GPS.html
	convert_to_entry ( "MANUAL", 0.0, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_MAP_DATUM, EXIF_IFD_GPS);
	convert_to_entry ( "WGS-84", 0.0, ee, exif_data_get_byte_order(ed) );

	struct LatLon ll;
    vik_coord_to_latlon ( &coord, &ll );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_LATITUDE_REF, EXIF_IFD_GPS);
	// N or S
	convert_to_entry ( ll.lat < 0.0 ? "S" : "N", 0.0, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_LATITUDE, EXIF_IFD_GPS);
	convert_to_entry ( NULL, ll.lat, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_LONGITUDE_REF, EXIF_IFD_GPS);
	// E or W
	convert_to_entry ( ll.lon < 0.0 ? "W" : "E", 0.0, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_LONGITUDE, EXIF_IFD_GPS);
	convert_to_entry ( NULL, ll.lon, ee, exif_data_get_byte_order(ed) );

	ee = my_exif_create_value (ed, EXIF_TAG_GPS_VERSION_ID, EXIF_IFD_GPS);
	//convert_to_entry ( "2 0 0 0", 0.0, ee, exif_data_get_byte_order(ed) );
	convert_to_entry ( "2 2 0 0", 0.0, ee, exif_data_get_byte_order(ed) );

	jpeg_data_set_exif_data (jdata, ed);

	if ( jdata ) {
		/* Save the modified image. */
		result = jpeg_data_save_file (jdata, filename);

		// Convert result from 1 for success, 0 for failure into our scheme
		result = !result;
		
		jpeg_data_unref (jdata);
	}
	else {
		// Epic fail - file probably not a JPEG
		result = 2;
	}

	if ( no_change_mtime ) {
		// Restore mtime, using the saved value
		struct stat stat_tmp;
		struct utimbuf utb;
		stat ( filename, &stat_tmp );
		utb.actime = stat_tmp.st_atime;
		utb.modtime = stat_save.st_mtime;
		utime ( filename, &utb );
	}

	return result;
}
Exemple #29
0
static int ypfs_write(const char *path, const char *buf, size_t size, off_t offset,
		      struct fuse_file_info *fi)
{
	char* full_path;
	FILE* logfile;
	int f;
	ExifData *ed;
	ExifEntry *entry;
	(void) fi;
	sqlite3_stmt *stmt;
	int year = -1;
	int month = -1;

#ifdef DEBUG
	if(1){
		FILE *f2 = fopen("/opfs/log2.txt", "a");
		fprintf(f2, "WRITE: %s\n", path);
		fclose(f2);
	}

#endif
	full_path = build_path(path);

	f = fi->fh;

	write(f, buf, size);

	if (offset == 0) {
		logfile = fopen("log.txt", "a");
		ed = exif_data_new_from_file(full_path);
		if (ed) {
			entry = exif_content_get_entry(ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
			if (entry) {
				char buf[1024];
		        exif_entry_get_value(entry, buf, sizeof(buf));
		        fprintf(logfile, "%s had date %s\n", full_path, buf);
		        buf[4] = 0;
		        buf[7] = 0;
		        year = atoi(buf);
		        month = atoi(buf+5);
			} else {
				fprintf(logfile,"%s had exif data, but no date\n", full_path);
			}
		} else {
			fprintf(logfile,"%s had no exif data\n", full_path);
		}
		exif_data_unref(ed);
		fclose(logfile);

		if ( year == -1 || month == -1) {
			time_t cur_time;
			struct tm * full_time;
			time(&cur_time);
			full_time = localtime(&cur_time);
			if (year == -1)
				year = 1900 + full_time->tm_year;
			if (month == -1)
				month = full_time->tm_mon+1;
		}

		sqlite3_prepare_v2(conn, "insert into pictures values(?, ?, ?, ?)", -1, &stmt, NULL);
		sqlite3_bind_text(stmt, 1, path + last_index_of(path, '/'), -1, SQLITE_TRANSIENT);
		sqlite3_bind_int(stmt, 2, year);
		sqlite3_bind_int(stmt, 3, month);
		sqlite3_bind_int(stmt, 4, CURRENT->uid);
		sqlite3_step(stmt);
		sqlite3_finalize(stmt);

	}
	
	free(full_path);
	return size;
}
Exemple #30
0
/**
 * a_geotag_create_waypoint_from_file:
 * @filename: The image file to process
 * @vcmode:   The current location mode to use in the positioning of Waypoint
 * @name:     Returns a name for the Waypoint (can be NULL)
 *
 * Returns: An allocated Waypoint or NULL if Waypoint could not be generated (e.g. no EXIF info)
 *
 */
VikWaypoint* a_geotag_create_waypoint_from_file ( const gchar *filename, VikCoordMode vcmode, gchar **name )
{
	// Default return values (for failures)
	*name = NULL;
	VikWaypoint *wp = NULL;

	// TODO use log?
	//ExifLog *log = NULL;

	// open image with libexif
	ExifData *ed = exif_data_new_from_file ( filename );

	// Detect EXIF load failure
	if ( !ed )
		// return with no Waypoint
		return wp;

	struct LatLon ll;

	gchar str[128];
	ExifEntry *ee;

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_VERSION_ID);
	// Confirm this has a GPS Id - normally "2.0.0.0" or "2.2.0.0"
	if ( ! ( ee && ee->components == 4 ) )
		goto MyReturn;
	// Could test for these versions explicitly but may have byte order issues...
	//if ( ! ( ee->data[0] == 2 && ee->data[2] == 0 && ee->data[3] == 0 ) )
	//	goto MyReturn;


	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_MAP_DATUM);
	if ( ! ( ee && ee->components > 0 && ee->format == EXIF_FORMAT_ASCII ) )
		goto MyReturn;

	// If map datum specified - only deal in WGS-84 - the defacto standard
	if ( ee && ee->components > 0 ) {
		exif_entry_get_value ( ee, str, 128 );
		if ( strncmp (str, "WGS-84", 6) )
			goto MyReturn;
	}

	//
	// Lat & Long is necessary to form a waypoint.
	//
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LATITUDE);
	if ( ! ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
		goto MyReturn;
  
	ll.lat = Rational2Double ( ee->data,
							   exif_format_get_size(ee->format),
							   exif_data_get_byte_order(ed) );

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LATITUDE_REF);
	if ( ee ) {
		exif_entry_get_value ( ee, str, 128 );
		if ( str[0] == 'S' )
			ll.lat = -ll.lat;
	}

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LONGITUDE);
	if ( ! ( ee && ee->components == 3 && ee->format == EXIF_FORMAT_RATIONAL ) )
		goto MyReturn;

	ll.lon = Rational2Double ( ee->data,
							   exif_format_get_size(ee->format),
							   exif_data_get_byte_order(ed) );

	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_LONGITUDE_REF);
	if ( ee ) {
		exif_entry_get_value ( ee, str, 128 );
		if ( str[0] == 'W' )
			ll.lon = -ll.lon;
	}

	//
	// Not worried if none of the other fields exist, as can default the values to something
	//

	gdouble alt = VIK_DEFAULT_ALTITUDE;
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_ALTITUDE);
	if ( ee && ee->components == 1 && ee->format == EXIF_FORMAT_RATIONAL ) {
		alt = Rational2Double ( ee->data,
								0,
								exif_data_get_byte_order(ed) );

		ee = exif_content_get_entry (ed->ifd[EXIF_IFD_GPS], EXIF_TAG_GPS_ALTITUDE_REF);
		if ( ee && ee->components == 1 && ee->format == EXIF_FORMAT_BYTE && ee->data[0] == 1 )
			alt = -alt;
	}

	// Name
	ee = exif_content_get_entry (ed->ifd[EXIF_IFD_0], EXIF_TAG_XP_TITLE);
	if ( ee ) {
		exif_entry_get_value ( ee, str, 128 );
		*name = g_strdup ( str );
	}

	//
	// Now create Waypoint with acquired information
	//
	wp = vik_waypoint_new();
	wp->visible = TRUE;
	// Set info from exif values
	// Location
	vik_coord_load_from_latlon ( &(wp->coord), vcmode, &ll );
	// Altitude
	wp->altitude = alt;

	wp->comment = geotag_get_exif_comment ( ed );

	vik_waypoint_set_image ( wp, filename );

MyReturn:
	// Finished with EXIF
	exif_data_free ( ed );

	return wp;
}