int populateMetaExif(std::string file, std::string plate)
{
	try 
	{
		Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
		std::string comment = plate + ' '+ "LOT50"; //Add code to get information about lot
	
		if(!image.get())
		{
			throw Exiv2::Error(1, "Failed to open image");
		}
		
		image->readMetadata();
		Exiv2::ExifData &exifData = image->exifData();
	
		
		exifData["Exif.Photo.UserComment"]= comment;
		//std::cout<< "Writing Exiv User Comment "<< exifData["Exif.Image.ImageDescription"] <<"\n";
		image->writeMetadata();
		
	} catch (Exiv2::AnyError& e) {
		std::cout << "Problem Writing Metadata '" << e << "'\n";
		return -1;
	}
	
	return 0;
}
示例#2
0
void ExifReaderWriter::saveExifGps(QString pictureName, double latitude, double longitude, double altitude)
{
    qDebug() << "saveExifGps" << pictureName << latitude << longitude << altitude;
    Exiv2::Image::AutoPtr image = openExif(pictureName);
    if(image.get() == 0)
        return;

    if(image->exifData().empty())
    {
        Exiv2::ExifData exifDataTmp;
        image->setExifData(exifDataTmp);
    }

    Exiv2::ExifData &exifData = image->exifData();

    writeData(exifData, "Exif.GPSInfo.GPSLatitude", exifLatLonString(latitude));
    writeData(exifData, "Exif.GPSInfo.GPSLongitude", exifLatLonString(longitude));

    writeData(exifData, "Exif.GPSInfo.GPSLatitudeRef", (latitude<0 ? "S" : "N"));
    writeData(exifData, "Exif.GPSInfo.GPSLongitudeRef", (longitude<0 ? "W" : "E"));

    if(altitude > -999)
    {
        writeData(exifData, "Exif.GPSInfo.GPSAltitude", (QString("%1/%2").arg(abs(round(altitude * 1000))).arg(1000)));
        writeData(exifData, "Exif.GPSInfo.GPSAltitudeRef", (altitude<0 ? "1" : "0"));
    }
    image->writeMetadata();
}
int main(int argc, char* const argv[])
try {
    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }

    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(argv[1]);
    assert(image.get() != 0);
    image->readMetadata();

    Exiv2::XmpData xmpData;
    Exiv2::copyExifToXmp(image->exifData(), xmpData);

    Exiv2::ExifData exifData;
    Exiv2::copyXmpToExif(xmpData, exifData);

    image->setXmpData(xmpData);
    image->setExifData(exifData);
    image->writeMetadata();
    
    return 0;
}
catch (Exiv2::AnyError& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
示例#4
0
void write(const std::string& file, Exiv2::ExifData& ed)
{
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
    assert (image.get() != 0);
    image->setExifData(ed);
    image->writeMetadata();
}
示例#5
0
void ExifTransfer::copyMetadata() {
    try {
        dst = Exiv2::ImageFactory::open(BasicIo::AutoPtr(new MemIo(data, dataSize)));
        dst->readMetadata();
    } catch (Exiv2::Error & e) {
        std::cerr << "Exiv2 error: " << e.what() << std::endl;
        return;
    }
    try {
        src = Exiv2::ImageFactory::open(srcFile.toLocal8Bit().constData());
        src->readMetadata();
        copyXMP();
        copyIPTC();
        copyEXIF();
    } catch (Exiv2::Error & e) {
        std::cerr << "Exiv2 error: " << e.what() << std::endl;
        // At least we have to set the SubImage1 file type to Primary Image
        dst->exifData()["Exif.SubImage1.NewSubfileType"] = 0;
    }
    try {
        dst->writeMetadata();
        FileIo fileIo(dstFile.toLocal8Bit().constData());
        fileIo.open("wb");
        fileIo.write(dst->io());
        fileIo.close();
    } catch (Exiv2::Error & e) {
        std::cerr << "Exiv2 error: " << e.what() << std::endl;
    }
}
示例#6
0
bool ptImageHelper::TransferExif(const QString ASourceFile, const QString ATargetFile)
{
  if (ASourceFile == ATargetFile      ||
      ASourceFile.trimmed().isEmpty() ||
      ATargetFile.trimmed().isEmpty())
    return false;

  try {
    if (Exiv2::ImageFactory::getType(ASourceFile.toLocal8Bit().data()) == Exiv2::ImageType::none)
      return false;

    Exiv2::Image::AutoPtr hSourceImage = Exiv2::ImageFactory::open(ASourceFile.toLocal8Bit().data());

    if (!hSourceImage.get()) return false;

    hSourceImage->readMetadata();

    Exiv2::Image::AutoPtr hTargetImage = Exiv2::ImageFactory::open(ATargetFile.toLocal8Bit().data());

    hTargetImage->clearMetadata();
    hTargetImage->setMetadata(*hSourceImage);
    hTargetImage->writeMetadata();
    return true;
  } catch (Exiv2::AnyError& Error) {
    if (Settings->GetInt("JobMode") == 0) {
      ptMessageBox::warning(0 ,"Exiv2 Error","No exif data written!\nCaught Exiv2 exception '" + QString(Error.what()) + "'\n");
    } else {
      std::cout << "Caught Exiv2 exception '" << Error << "'\n";
    }
  }
  return false;
}
示例#7
0
文件: metacopy.cpp 项目: obklar/exiv2
// *****************************************************************************
// Main
int main(int argc, char* const argv[])
{
try {
    // Handle command line arguments
    Params params;
    if (params.getopt(argc, argv)) {
        params.usage();
        return 1;
    }
    if (params.help_) {
        params.help();
        return 2;
    }

    // Use MemIo to increase test coverage.
    Exiv2::BasicIo::AutoPtr fileIo(new Exiv2::FileIo(params.read_));
    Exiv2::BasicIo::AutoPtr memIo(new Exiv2::MemIo);
    memIo->transfer(*fileIo);

    Exiv2::Image::AutoPtr readImg = Exiv2::ImageFactory::open(memIo);
    assert(readImg.get() != 0);
    readImg->readMetadata();

    Exiv2::Image::AutoPtr writeImg = Exiv2::ImageFactory::open(params.write_);
    assert(writeImg.get() != 0);
    if (params.preserve_) writeImg->readMetadata();
    if (params.iptc_) {
        writeImg->setIptcData(readImg->iptcData());
    }
    if (params.exif_) {
        writeImg->setExifData(readImg->exifData());
    }
    if (params.comment_) {
        writeImg->setComment(readImg->comment());
    }
    if (params.xmp_) {
        writeImg->setXmpData(readImg->xmpData());
    }

    try {
        writeImg->writeMetadata();
    }
    catch (const Exiv2::AnyError&) {
        std::cerr << params.progname() <<
            ": Could not write metadata to (" << params.write_ << ")\n";
        return 8;
    }

    return 0;
}
catch (Exiv2::AnyError& e) {
    std::cerr << "Caught Exiv2 exception '" << e << "'\n";
    return 10;
}
}
示例#8
0
void Frame::save(std::string dir) {
    std::string path = dir + "/" + id;
    imwrite(path, *img);
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(path);
    image->readMetadata();
    Exiv2::ExifData &exifData = image->exifData();
    std::stringstream ss;
    ss << std::setprecision(12) << data.lat << " " << data.lon << " " << data.altitude << " " << data.heading << " " << data.time;
    exifData["Exif.Photo.UserComment"] = ss.str();
    image->writeMetadata();
}
示例#9
0
int RemoveGPSExif(const char* File, int NoChangeMtime)
{
	struct stat statbuf;
	struct stat statbuf2;
	struct utimbuf utb;
	if (NoChangeMtime)
		stat(File, &statbuf);

	// Open the file and start reading.
	Exiv2::Image::AutoPtr Image;
	
	try {
		Image = Exiv2::ImageFactory::open(File);
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to open file %s.\n", File);
		return 0;
	}
	Image->readMetadata();
	if (Image.get() == NULL)
	{
		// It failed if we got here.
		DEBUGLOG("Failed to read file %s %s.\n",
			 File, Exiv2::strError().c_str());
		return 0;
	}

	Exiv2::ExifData &ExifInfo = Image->exifData();

	if (ExifInfo.count() == 0)
	{
		DEBUGLOG("No EXIF tags in file %s.\n", File);
		return 0;
	}

	EraseGpsTags(ExifInfo);
	
	try {
		Image->writeMetadata();
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to write to file %s.\n", File);
		return 0;
	}

	if (NoChangeMtime)
	{
		stat(File, &statbuf2);
		utb.actime = statbuf2.st_atime;
		utb.modtime = statbuf.st_mtime;
		utime(File, &utb);
	}

	return 1;

}
示例#10
0
// Saves Exifdata to given file
void FlickrUpload::saveExifData(Exiv2::ExifData *exifData, QByteArray *image){
    try {
        Exiv2::Image::AutoPtr destImage = Exiv2::ImageFactory::open(
                    (Exiv2::byte*)image->constData(), (long)image->size());
        destImage->setExifData(*exifData);
        destImage->writeMetadata();
        // get updated image data
        Exiv2::BasicIo&  rawio = destImage->io();
        Exiv2::DataBuf  dbuf = rawio.read( rawio.size() );
        image->clear();
        image->append(QByteArray::fromRawData((char*)dbuf.pData_, dbuf.size_));
    } catch (Exiv2::Error& e) {
        qCritical("[SaveFile] %s", e.what());
    }
}
示例#11
0
void ImageView::saveImage()
{
	Exiv2::Image::AutoPtr image;
	bool exifError = false;

	if (newImage)
	{
		saveImageAs();
		return;
	}

	setFeedback(tr("Saving..."));

	try
	{
		image = Exiv2::ImageFactory::open(currentImageFullPath.toStdString());
		image->readMetadata();
	}
	catch (Exiv2::Error &error)
	{
		exifError = true;
	}

	QImageReader imgReader(currentImageFullPath);
	if (!displayPixmap.save(currentImageFullPath, imgReader.format().toUpper(),
																			GData::defaultSaveQuality))
	{
		QMessageBox msgBox;
		msgBox.critical(this, tr("Error"), tr("Failed to save image."));
		return;
	}

	if (!exifError)
	{
		try
		{
			image->writeMetadata();
		}
		catch (Exiv2::Error &error)
		{
			QMessageBox msgBox;
			msgBox.critical(this, tr("Error"), tr("Failed to save Exif metadata."));
		}
	}

	reload();
	setFeedback(tr("Image saved."));
}
示例#12
0
int main(int argc, char* const argv[])
try {
    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }
    std::string file(argv[1]);

    Exiv2::IptcData iptcData;

    iptcData["Iptc.Application2.Headline"] = "The headline I am";
    iptcData["Iptc.Application2.Keywords"] = "Yet another keyword";
    iptcData["Iptc.Application2.DateCreated"] = "2004-8-3";
    iptcData["Iptc.Application2.Urgency"] = uint16_t(1);
    iptcData["Iptc.Envelope.ModelVersion"] = 42;
    iptcData["Iptc.Envelope.TimeSent"] = "14:41:0-05:00";
    iptcData["Iptc.Application2.RasterizedCaption"] = "230 42 34 2 90 84 23 146";
    iptcData["Iptc.0x0009.0x0001"] = "Who am I?";

    Exiv2::StringValue value;
    value.read("very!");
    iptcData["Iptc.Application2.Urgency"] = value;

    std::cout << "Time sent: " << iptcData["Iptc.Envelope.TimeSent"] << "\n";

    // Open image file
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
    if (image.get() == 0) {
        std::string error(file);
        error += " : Could not read file or unknown image type";
        throw Exiv2::Error(error);
    }

    // Read existing metdata (so that exif will be preserved)
    int rc = image->readMetadata();
    if (rc) {
        std::string error = Exiv2::Image::strError(rc, file);
        throw Exiv2::Error(error);
    }

    // Replace Iptc data and write it back to the file
    image->setIptcData(iptcData);
    return image->writeMetadata();
}
catch (Exiv2::Error& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
示例#13
0
// *****************************************************************************
// Main
int main(int argc, char* const argv[])
try {

    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }

    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(argv[1]);
    assert (image.get() != 0);
    image->readMetadata();
    Exiv2::ExifData &exifData = image->exifData();

    /*
      Exiv2 uses a CommentValue for Exif user comments. The format of the
      comment string includes an optional charset specification at the beginning:

      [charset=["]Ascii|Jis|Unicode|Undefined["] ]comment

      Undefined is used as a default if the comment doesn't start with a charset
      definition.

      Following are a few examples of valid comments. The last one is written to
      the file.
     */
    exifData["Exif.Photo.UserComment"]
        = "charset=\"Unicode\" An Unicode Exif comment added with Exiv2";
    exifData["Exif.Photo.UserComment"]
        = "charset=\"Undefined\" An undefined Exif comment added with Exiv2";
    exifData["Exif.Photo.UserComment"]
        = "Another undefined Exif comment added with Exiv2";
    exifData["Exif.Photo.UserComment"]
        = "charset=Ascii An ASCII Exif comment added with Exiv2";

    std::cout << "Writing user comment '"
              << exifData["Exif.Photo.UserComment"]
              << "' back to the image\n";

    image->writeMetadata();

    return 0;
}
catch (Exiv2::AnyError& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
示例#14
0
void ImageView::saveImageAs()
{
	Exiv2::Image::AutoPtr exifImage;
	Exiv2::Image::AutoPtr newExifImage;
	bool exifError = false;

	setCursorHiding(false);

	QString fileName = QFileDialog::getSaveFileName(this,
		tr("Save image as"),
		currentImageFullPath,
		tr("Images") + " (*.jpg *.jpeg *.jpe *.png *.bmp *.ppm *.pgm *.pbm *.xbm *.xpm)");
		
	if (!fileName.isEmpty()) {
		try {
			exifImage = Exiv2::ImageFactory::open(currentImageFullPath.toStdString());
			exifImage->readMetadata();
		}
		catch (Exiv2::Error &error)	{
			exifError = true;
		}

	
		if (!displayPixmap.save(fileName, 0, GData::defaultSaveQuality)) {
			QMessageBox msgBox;
			msgBox.critical(this, tr("Error"), tr("Failed to save image."));
		} else {
			if (!exifError) {
				try	{
					newExifImage = Exiv2::ImageFactory::open(fileName.toStdString());
					newExifImage->setMetadata(*exifImage);
					newExifImage->writeMetadata();
				}
				catch (Exiv2::Error &error) {
					exifError = true;
				}
			}
		
			setFeedback(tr("Image saved."));
		}
	}
	if (mainWindow->isFullScreen()) {
		setCursorHiding(true);
	}
}
示例#15
0
void ExifTools::copyExif(const QString &sourceStr, const QString &destStr)
{
        Exiv2::Image::AutoPtr sourceImageData =
                Exiv2::ImageFactory::open(QFile::encodeName(sourceStr).data());
        sourceImageData->readMetadata();

        Exiv2::ExifData exifData = sourceImageData->exifData();
        Exiv2::IptcData iptcData = sourceImageData->iptcData();

        Exiv2::ExifThumb exifThumb(exifData);
        exifThumb.erase();

        Exiv2::Image::AutoPtr destImageData =
                Exiv2::ImageFactory::open(QFile::encodeName(destStr).data());
        destImageData->setExifData(exifData);
        destImageData->setIptcData(iptcData);
        destImageData->writeMetadata();
}
示例#16
0
bool ImageTags::writeTagsToImage(QString &imageFileName, QSet<QString> &newTags)
{
	QSet<QString> imageTags;
	Exiv2::Image::AutoPtr exifImage;

	try {
		exifImage = Exiv2::ImageFactory::open(imageFileName.toStdString());
		exifImage->readMetadata();

		Exiv2::IptcData newIptcData;

		/* copy existing data */
		Exiv2::IptcData &iptcData = exifImage->iptcData();
		if (!iptcData.empty()) {
			QString key;
			Exiv2::IptcData::iterator end = iptcData.end();
			for (Exiv2::IptcData::iterator iptcIt = iptcData.begin(); iptcIt != end; ++iptcIt) {
				if (iptcIt->tagName() != "Keywords") {
					newIptcData.add(*iptcIt);
				}
	        }
	    }

		/* add new tags */
		QSetIterator<QString> newTagsIt(newTags);
		while (newTagsIt.hasNext()) {
			QString tag = newTagsIt.next();
		    Exiv2::Value::AutoPtr value = Exiv2::Value::create(Exiv2::string);
		    value->read(tag.toStdString());
		    Exiv2::IptcKey key("Iptc.Application2.Keywords");
		    newIptcData.add(key, value.get());
		}

	    exifImage->setIptcData(newIptcData);
	    exifImage->writeMetadata();
   	}
	catch (Exiv2::Error &error) {
		QMessageBox msgBox;
		msgBox.critical(this, tr("Error"), tr("Failed to save tags to ") + imageFileName);
		return false;
	}

	return true;
}
示例#17
0
int main(int argc, char ** argv) {
    logging::core::get()->set_filter
    (
       logging::trivial::severity >= logging::trivial::info
    );
    if(argc <= 4) {
        BOOST_LOG_TRIVIAL(info) << "Invalid arguments for test";
        return 2;
    }
    string description = argv[1];
    Mat input = imread(argv[2], cv::IMREAD_COLOR);
    BOOST_LOG_TRIVIAL(info) << "Reading " << argv[2] << " of size " << input.rows << "x" << input.cols;
    vector<Point> * contour = new vector<Point>();
    for(int i = 3; i + 1 < argc; i++){
        stringstream ss;
        int x, y;
        ss << argv[i] << " " << argv[i+1];
        ss >> x >> y;
        contour->push_back(Point(x,y));
    }
    

    /************************************************ERIC's SHIT*/	
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(argv[2]);
    image->readMetadata();
    Exiv2::ExifData &exifData = image->exifData();
  
    exifData["Exif.Photo.UserComment"] = "50,-90,90,180,1:23:45";
    image->writeMetadata();
    std::cout << "wrote it";

    /****************************************************/
   
    BOOST_LOG_TRIVIAL(info) << "Read Contour: " << contour; // TODO: figure out why defining operator<< doesn't affect boost logs
    Frame f(&input, "blah", Metadata());
    TargetTest test("Target Identification using KMeans + Canny");
    double result = test.do_test(f, description, contour, 10);
    return !(result < 10 && result > -10); // arbitrary bounds for success of test (false indicates success)
}
示例#18
0
/** \fn     ImageUtils::SetExifValue(const QString &, const QString &, const QString &, bool *)
 *  \brief  Updates the exif tag in a file with the given value
 *  \param  fileName The filename that holds the exif data
 *  \param  exifTag The key that shall be updated
 *  \param  value The new value of the exif tag
 *  \param  ok Will be set to true if the update was ok, otherwise false
 *  \return True if the exif key exists, otherwise false
 */
void ImageUtils::SetExifValue(const QString &fileName,
                              const QString &exifTag,
                              const QString &value,
                              bool *ok)
{
    // Assume the exif writing fails
    *ok = false;

    try
    {
        Exiv2::Image::AutoPtr image =
                Exiv2::ImageFactory::open(fileName.toLocal8Bit().constData());

        if (image.get())
        {
            Exiv2::ExifData exifData;
            Exiv2::Exifdatum &datum = exifData[exifTag.toLocal8Bit().constData()];
            datum.setValue(value.toLocal8Bit().constData());

            image->setExifData(exifData);
            image->writeMetadata();

            *ok = true;
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("Exiv2 error: Could not open file, file %1, tag %2")
                .arg(fileName).arg(exifTag));
        }
    }
    catch (Exiv2::Error& e)
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Exiv2 exception %1, file %2, tag %3, value %4")
            .arg(e.what()).arg(fileName).arg(exifTag).arg(value));
    }
}
示例#19
0
bool JpegContent::save(QIODevice* device)
{
    if (!d->mImage.isNull()) {
        if (!d->updateRawDataFromImage()) {
            return false;
        }
    }

    if (d->mRawData.size() == 0) {
        d->mErrorString = i18nc("@info", "No data to store.");
        return false;
    }

    if (d->mPendingTransformation) {
        applyPendingTransformation();
        d->mPendingTransformation = false;
    }

    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open((unsigned char*)d->mRawData.data(), d->mRawData.size());

    // Store Exif info
    image->setExifData(d->mExifData);
    image->setComment(d->mComment.toUtf8().data());
    image->writeMetadata();

    // Update mRawData
    Exiv2::BasicIo& io = image->io();
    d->mRawData.resize(io.size());
    io.read((unsigned char*)d->mRawData.data(), io.size());

    QDataStream stream(device);
    stream.writeRawData(d->mRawData.data(), d->mRawData.size());

    // Make sure we are up to date
    loadFromData(d->mRawData);
    return true;
}
示例#20
0
void ExifReaderWriter::saveExifTime(QString pictureName, QDateTime *dateTime)
{
    Exiv2::Image::AutoPtr image = openExif(pictureName);
    if(image.get() == 0)
        return;

    if(image->exifData().empty())
    {
        Exiv2::ExifData exifDataTmp;
        image->setExifData(exifDataTmp);
    }

    Exiv2::ExifData &exifData = image->exifData();


    QString str = dateTime->toString(timeFormat.toLatin1());

    writeData(exifData, "Exif.Image.DateTime", str);
    writeData(exifData, "Exif.Image.DateTimeOriginal", str);
    writeData(exifData, "Exif.Photo.DateTimeOriginal", str);
    writeData(exifData, "Exif.Photo.DateTimeDigitized", str);

    image->writeMetadata();
}
示例#21
0
文件: main.cpp 项目: jl2/geotagger
void geotag_worker(wc_work_queue &wq, std::vector<GPXPoint> &gpxData) {
    std::string fname;
    // Grab a file from the work queue
    while ((fname = wq.getFile()) != "") {
        try {
            Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fname.c_str());
            if (image.get() == 0) continue;
            image->readMetadata();

            Exiv2::ExifData &exifData = image->exifData();
            if (exifData.empty()) {
                std::string error = fname;
                error += ": No Exif data found in the file";
                throw Exiv2::Error(1, error);
            }
            std::string tmpTime = exifData["Exif.Photo.DateTimeOriginal"].toString();
            auto tstamp = getImageTimeStamp(tmpTime);

            size_t idx = 0;
            bool foundIt = findClosest(gpxData, tstamp, idx);

            if (!foundIt) {
                std::cout << fname << " is not on the GPX track!\n";
                continue;
            } else {
                std::cout << fname << " was at ("  << std::setprecision(10) << gpxData[idx].lat << ", " << std::setprecision(10) << gpxData[idx].lon << ")\n";
            }
            clearGPSFields(exifData);

            exifData["Exif.GPSInfo.GPSMapDatum"] = "WGS-84";

            exifData["Exif.GPSInfo.GPSAltitude"] = Exiv2::Rational(gpxData[idx].ele * 1000, 1000);
            exifData["Exif.GPSInfo.GPSAltitudeRef"] = Exiv2::byte(0);

            // Convert the latitude to DDD*MM'SS.SSS" and set
            int dd, mm;
            double ss;
            convertToDDMMSS(gpxData[idx].lat, dd, mm, ss);
            if (gpxData[idx].lat<0) {
                exifData["Exif.GPSInfo.GPSLatitudeRef"] = "S";
            } else {
                exifData["Exif.GPSInfo.GPSLatitudeRef"] = "N";
            }

            Exiv2::URationalValue::AutoPtr latitude(new Exiv2::URationalValue);
            latitude->value_.push_back(std::make_pair(dd,1));
            latitude->value_.push_back(std::make_pair(mm,1));
            latitude->value_.push_back(std::make_pair(std::trunc(ss*10000)-1,10000));
            auto latKey = Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude");
            exifData.add(latKey, latitude.get());

            convertToDDMMSS(gpxData[idx].lon, dd, mm, ss);
            Exiv2::URationalValue::AutoPtr longitude(new Exiv2::URationalValue);
            if (gpxData[idx].lon<0) {
                exifData["Exif.GPSInfo.GPSLongitudeRef"] = "W";
            } else {
                exifData["Exif.GPSInfo.GPSLongitudeRef"] = "E";
            }
            longitude->value_.push_back(std::make_pair(dd,1));
            longitude->value_.push_back(std::make_pair(mm,1));
            longitude->value_.push_back(std::make_pair(int(ss*10000)-1,10000));
            auto longKey = Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude");
            exifData.add(longKey, longitude.get());


            Exiv2::URationalValue::AutoPtr timestamp(new Exiv2::URationalValue);
            timestamp->value_.push_back(std::make_pair(gpxData[idx].hour,1));
            timestamp->value_.push_back(std::make_pair(gpxData[idx].minute,1));
            timestamp->value_.push_back(std::make_pair(gpxData[idx].second,1));

            auto timeKey = Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp");
            exifData.add(timeKey, timestamp.get());
            
            exifData["Exif.GPSInfo.GPSDateStamp"] = gpxData[idx].dateStamp.c_str();

            image->setExifData(exifData);
            image->writeMetadata();
        }
        catch (Exiv2::AnyError& e) {
            std::cout << "Caught Exiv2 exception '" << e.what() << "'\n";
            continue;
        }
    }
}
示例#22
0
int WriteFixedDatestamp(const char* File, time_t Time)
{
	// Write the GPS data to the file...

	struct stat statbuf;
	struct stat statbuf2;
	struct utimbuf utb;
	stat(File, &statbuf);

	Exiv2::Image::AutoPtr Image;

	try {
		Image = Exiv2::ImageFactory::open(File);
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to open file %s.\n", File);
		return 0;
	}
	Image->readMetadata();
	if (Image.get() == NULL)
	{
		// It failed if we got here.
		DEBUGLOG("Failed to read file %s %s.\n",
			 File, Exiv2::strError().c_str());
		return 0;
	}
	
	Exiv2::ExifData &ExifToWrite = Image->exifData();
	
	const struct tm TimeStamp = *gmtime(&Time);
	char ScratchBuf[100];

	snprintf(ScratchBuf, sizeof(ScratchBuf), "%04d:%02d:%02d",
			TimeStamp.tm_year + 1900,
			TimeStamp.tm_mon + 1,
			TimeStamp.tm_mday);
	ExifToWrite.erase(ExifToWrite.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSDateStamp")));
	ExifToWrite["Exif.GPSInfo.GPSDateStamp"] = ScratchBuf;

	Exiv2::Value::AutoPtr Value = Exiv2::Value::create(Exiv2::unsignedRational);
	snprintf(ScratchBuf, sizeof(ScratchBuf), "%d/1 %d/1 %d/1",
			TimeStamp.tm_hour, TimeStamp.tm_min,
			TimeStamp.tm_sec);
	Value->read(ScratchBuf);
	ExifToWrite.erase(ExifToWrite.findKey(Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp")));
	ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp"), Value.get());
	
	try {
		Image->writeMetadata();
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to write to file %s.\n", File);
		return 0;
	}
	
	// Reset the mtime.
	stat(File, &statbuf2);
	utb.actime = statbuf2.st_atime;
	utb.modtime = statbuf.st_mtime;
	utime(File, &utb);

	return 1;
}
示例#23
0
int WriteGPSData(const char* File, const struct GPSPoint* Point,
		 const char* Datum, int NoChangeMtime, int DegMinSecs)
{
	// Write the GPS data to the file...

	struct stat statbuf;
	struct stat statbuf2;
	struct utimbuf utb;
	if (NoChangeMtime)
		stat(File, &statbuf);
	Exiv2::Image::AutoPtr Image;

	try {
		Image = Exiv2::ImageFactory::open(File);
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to open file %s.\n", File);
		return 0;
	}
	Image->readMetadata();
	if (Image.get() == NULL)
	{
		// It failed if we got here.
		DEBUGLOG("Failed to read file %s %s.\n",
			 File, Exiv2::strError().c_str());
		return 0;
	}
	
	Exiv2::ExifData &ExifToWrite = Image->exifData();

	// Make sure we're starting from a clean GPS IFD.
	// There might be lots of GPS tags existing here, since only the
	// presence of the GPSLatitude tag causes correlation to stop with
	// "GPS Already Present" error.
	EraseGpsTags(ExifToWrite);

	char ScratchBuf[100];

	// Do all the easy constant ones first.
	// GPSVersionID tag: standard says it should be four bytes: 02 02 00 00
	//  (and, must be present).
	Exiv2::Value::AutoPtr Value = Exiv2::Value::create(Exiv2::unsignedByte);
	Value->read("2 2 0 0");
	ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSVersionID"), Value.get());
	// Datum: the datum of the measured data. The default is WGS-84.
	if (*Datum)
		ExifToWrite["Exif.GPSInfo.GPSMapDatum"] = Datum;
	
	// Now start adding data.
	// ALTITUDE.
	// If no altitude was found in the GPX file, ElevDecimals will be -1
	if (Point->ElevDecimals >= 0) {
		// Altitude reference: byte "00" meaning "sea level".
		// Or "01" if the altitude value is negative.
		Value = Exiv2::Value::create(Exiv2::unsignedByte);
		if (Point->Elev >= 0)
		{
			Value->read("0");
		} else {
			Value->read("1");
		}
		ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSAltitudeRef"), Value.get());
		// And the actual altitude.
		Value = Exiv2::Value::create(Exiv2::unsignedRational);
		// 3 decimal points is beyond the limit of current GPS technology
		int Decimals = MIN(Point->ElevDecimals, 3);
		ConvertToRational(fabs(Point->Elev), Decimals, ScratchBuf, sizeof(ScratchBuf));

		/* printf("Altitude: %f -> %s\n", Point->Elev, ScratchBuf); */
		Value->read(ScratchBuf);
		ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSAltitude"), Value.get());
	}
	
	// LATITUDE
	// Latitude reference: "N" or "S".
	if (Point->Lat < 0)
	{
		// Less than Zero: ie, minus: means
		// Southern hemisphere. Where I live.
		ExifToWrite["Exif.GPSInfo.GPSLatitudeRef"] = "S";
	} else {
		// More than Zero: ie, plus: means
		// Northern hemisphere.
		ExifToWrite["Exif.GPSInfo.GPSLatitudeRef"] = "N";
	}
	// Now the actual latitude itself.
	// The original comment read:
	// This is done as three rationals.
	// I choose to do it as:
	//   dd/1 - degrees.
	//   mmmm/100 - minutes
	//   0/1 - seconds
	// Exif standard says you can do it with minutes
	// as mm/1 and then seconds as ss/1, but its
	// (slightly) more accurate to do it as
	//  mmmm/100 than to split it.
	// We also absolute the value (with fabs())
	// as the sign is encoded in LatRef.
	// Further note: original code did not translate between
	//   dd.dddddd to dd mm.mm - that's why we now multiply
	//   by 60*N - x60 to get minutes, xN to get to mmmm/N.
	//   N is 10^S where S is the number of significant decimal
	//   places.
	//
	// Rereading the EXIF standard, it's quite ok to do DD MM SS.SS
	// Which is much more accurate. This is the new default, unless otherwise
	// set.
	Value = Exiv2::Value::create(Exiv2::unsignedRational);

	if (DegMinSecs)
	{
		ConvertToLatLongRational(Point->Lat, Point->LatDecimals, ScratchBuf, sizeof(ScratchBuf));
	} else {
		ConvertToOldLatLongRational(Point->Lat, ScratchBuf, sizeof(ScratchBuf));
	}
	Value->read(ScratchBuf);
	ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude"), Value.get());
	
	// LONGITUDE
	// Longitude reference: "E" or "W".
	if (Point->Long < 0)
	{
		// Less than Zero: ie, minus: means
		// Western hemisphere.
		ExifToWrite["Exif.GPSInfo.GPSLongitudeRef"] = "W";
	} else {
		// More than Zero: ie, plus: means
		// Eastern hemisphere. Where I live.
		ExifToWrite["Exif.GPSInfo.GPSLongitudeRef"] = "E";
	}
	// Now the actual longitude itself, in the same way as latitude
	Value = Exiv2::Value::create(Exiv2::unsignedRational);

	if (DegMinSecs)
	{
		ConvertToLatLongRational(Point->Long, Point->LongDecimals, ScratchBuf, sizeof(ScratchBuf));
	} else {
		ConvertToOldLatLongRational(Point->Long, ScratchBuf, sizeof(ScratchBuf));
	}
	Value->read(ScratchBuf);
	ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude"), Value.get());

	// The timestamp.
	// Make up the timestamp...
	// The timestamp is taken as the UTC time of the photo.
	// If interpolation occurred, then this time is the time of the photo.
	struct tm TimeStamp = *gmtime(&(Point->Time));

	Value = Exiv2::Value::create(Exiv2::unsignedRational);
	snprintf(ScratchBuf, sizeof(ScratchBuf), "%d/1 %d/1 %d/1",
			TimeStamp.tm_hour, TimeStamp.tm_min,
			TimeStamp.tm_sec);
	Value->read(ScratchBuf);
	ExifToWrite.add(Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp"), Value.get());

	// And we should also do a datestamp.
	snprintf(ScratchBuf, sizeof(ScratchBuf), "%04d:%02d:%02d",
			TimeStamp.tm_year + 1900,
			TimeStamp.tm_mon + 1,
			TimeStamp.tm_mday);
	ExifToWrite["Exif.GPSInfo.GPSDateStamp"] = ScratchBuf;

	// Write the data to file.
	try {
		Image->writeMetadata();
	} catch (Exiv2::Error e) {
		DEBUGLOG("Failed to write to file %s.\n", File);
		return 0;
	}

	if (NoChangeMtime)
	{
		stat(File, &statbuf2);
		utb.actime = statbuf2.st_atime;
		utb.modtime = statbuf.st_mtime;
		utime(File, &utb);
	}

	return 1;
	
}
示例#24
0
int main(int argc, char* const argv[])
try {
    if (argc != 3) {
        std::cout << "Usage: " << argv[0] << " image datafile\n";
        return 1;
    }
    std::string file(argv[1]);
    std::string data(argv[2]);

    // Read data file into data buffer
    Exiv2::FileIo io(data);
    if (io.open() != 0) {
      throw Exiv2::Error(Exiv2::kerDataSourceOpenFailed, io.path(), Exiv2::strError());
    }
    Exiv2::DataBuf buf((long)io.size());
    std::cout << "Reading " << buf.size_ << " bytes from " << data << "\n";
    io.read(buf.pData_, buf.size_);
    if (io.error() || !io.eof()) throw Exiv2::Error(Exiv2::kerFailedToReadImageData);

    // Read metadata from file
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file);
    assert(image.get() != 0);
    image->readMetadata();

    // Set Preview field to the content of the data file
    Exiv2::DataValue value;
    value.read(buf.pData_, buf.size_);
    Exiv2::IptcData& iptcData = image->iptcData();
    std::cout << "IPTC fields: " << iptcData.size() << "\n";
    iptcData["Iptc.Application2.Preview"] = value;
    std::cout << "IPTC fields: " << iptcData.size() << "\n";

    // Set IRB, compare with IPTC raw data
    Exiv2::DataBuf irb = Exiv2::Photoshop::setIptcIrb(0, 0, iptcData);
    std::cout << "IRB buffer : " << irb.size_ << "\n";
    const Exiv2::byte* record;
    uint32_t sizeHdr;
    uint32_t sizeData;
    Exiv2::Photoshop::locateIptcIrb(irb.pData_, irb.size_, &record, &sizeHdr, &sizeData);
    Exiv2::DataBuf rawIptc = Exiv2::IptcParser::encode(iptcData);
    std::cout << "Comparing IPTC and IRB size... ";
    if (static_cast<uint32_t>(rawIptc.size_) != sizeData) {
        std::cout << "not ";
    }
    std::cout << "ok\n";

    std::cout << "Comparing IPTC and IRB data... ";
    if (0 != memcmp(rawIptc.pData_, record + sizeHdr, sizeData)) {
        std::cout << "not ";
    }
    std::cout << "ok\n";

    // Set Iptc data and write it to the file
    image->writeMetadata();

    return 0;
}
catch (Exiv2::AnyError& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
示例#25
0
int main(int argc,const char* argv[])
{
    int result=0;
    const char* program = argv[0];

    const char* types[typeMax];
    types[typeUnknown  ] = "unknown";
    types[typeDirectory] = "directory";
    types[typeImage    ] = "image";
    types[typeXML      ] = "xml";
    types[typeDoc      ] = "doc";
    types[typeCode     ] = "code";
    types[typeFile     ] = "file";

    char const* keywords[kwMAX];
    memset(keywords,0,sizeof(keywords));
    keywords[kwHELP    ] = "help";
    keywords[kwVERSION ] = "version";
    keywords[kwVERBOSE ] = "verbose";
    keywords[kwDRYRUN  ] = "dryrun";
    keywords[kwDST     ] = "dst";
    keywords[kwADJUST  ] = "adjust";
    keywords[kwTZ      ] = "tz";
    keywords[kwDELTA   ] = "delta";

    map<std::string,string> shorts;
    shorts["-?"] = "-help";
    shorts["-h"] = "-help";
    shorts["-v"] = "-verbose";
    shorts["-V"] = "-version";
    shorts["-d"] = "-dst";
    shorts["-a"] = "-adjust";
    shorts["-t"] = "-tz";
    shorts["-D"] = "-delta";
    shorts["-s"] = "-delta";
    shorts["-X"] = "-dryrun";

    Options options ;
    options.help    = sina(keywords[kwHELP   ],argv) || argc < 2;
    options.verbose = sina(keywords[kwVERBOSE],argv);
    options.dryrun  = sina(keywords[kwDRYRUN ],argv);
    options.version = sina(keywords[kwVERSION],argv);
    options.dst     = sina(keywords[kwDST    ],argv);
    options.dryrun  = sina(keywords[kwDRYRUN ],argv);

    for ( int i = 1 ; !result && i < argc ; i++ ) {
        const char* arg   = argv[i++];
        if ( shorts.count(arg) ) arg = shorts[arg].c_str();

        const char* value = argv[i  ];
        int        ivalue = ::atoi(value?value:"0");
        int         key   = ::find(arg,keywords,kwMAX);
        int         needv = key < kwMAX && key > (-kwNOVALUE);

        if (!needv ) i--;
        if ( needv && !value) key = kwNEEDVALUE;

        switch ( key ) {
            case kwDST      : options.dst     = true ; break;
            case kwHELP     : options.help    = true ; break;
            case kwVERSION  : options.version = true ; break;
            case kwDRYRUN   : options.dryrun  = true ; break;
            case kwVERBOSE  : options.verbose = true ; break;
            case kwTZ       : Position::tz_      = parseTZ(value);break;
            case kwADJUST   : Position::adjust_  = ivalue;break;
            case kwDELTA    : Position::deltaMax_= ivalue;break;
            case kwNEEDVALUE: fprintf(stderr,"error: %s requires a value\n",arg); result = resultSyntaxError ; break ;
            case kwSYNTAX   : default:
            {
                int  type   = getFileType(arg,options) ;
                if ( options.verbose ) printf("%s %s ",arg,types[type]) ;
                if ( type == typeImage ) {
                    time_t t    = readImageTime(std::string(arg)) ;
                    char*  path = realpath(arg,NULL);
                    if  ( t && path ) {
                        if ( options.verbose) printf("%s %ld %s",path,(long int)t,asctime(localtime(&t)));
                        gFiles.push_back(path);
                    }
                    if ( path ) :: free((void*) path);
                }
                if ( type == typeUnknown ) {
                    fprintf(stderr,"error: illegal syntax %s\n",arg);
                    result = resultSyntaxError ;
                }
                if ( options.verbose ) printf("\n") ;
            }break;
        }
    }

    if ( options.help    ) ::help(program,keywords,kwMAX,options.verbose);
    if ( options.version ) ::version(program);

    if ( !result ) {
        sort(gFiles.begin(),gFiles.end(),mySort);
        if ( options.dst ) Position::dst_ = 3600;
        if ( options.verbose ) {
            int t = Position::tz();
            int d = Position::dst();
            int a = Position::adjust();
            int A = Position::Adjust();
            int s = A     ;
            int h = s/3600;
                s-= h*3600;
                s = abs(s);
            int m = s/60  ;
                s-= m*60  ;
            printf("tz,dsl,adjust = %d,%d,%d total = %dsecs (= %d:%d:%d)\n",t,d,a,A,h,m,s);
        }
        for ( size_t p = 0 ; !options.dryrun && p < gFiles.size() ; p++ ) {
            std::string arg = gFiles[p] ;
            std::string stamp ;
            try {
                time_t t       = readImageTime(arg,&stamp) ;
                Position* pPos = searchTimeDict(gTimeDict,t,Position::deltaMax_);
                Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(gFiles[p]);
                if ( image.get() ) {
                    image->readMetadata();
                    Exiv2::ExifData& exifData = image->exifData();
#if 0
                    /*
					char* keys[]={ "Exif.Image.GPSTag"
						         , "Exif.GPSInfo.GPSProcessingMethod"
					             , "Exif.GPSInfo.GPSAltitudeRef"
							     , "Exif.GPSInfo.GPSVersionID"
                                 , "Exif.GPSInfo.GPSProcessingMethod"
                                 , "Exif.GPSInfo.GPSVersionID"
                                 , "Exif.GPSInfo.GPSMapDatum"
                                 , "Exif.GPSInfo.GPSLatitude"
                                 , "Exif.GPSInfo.GPSLongitude"
                                 , "Exif.GPSInfo.GPSAltitude"
                                 , "Exif.GPSInfo.GPSAltitudeRef"
                                 , "Exif.GPSInfo.GPSLatitudeRef"
                                 , "Exif.GPSInfo.GPSLongitudeRef"
                                 , "Exif.GPSInfo.GPSDateStamp"
                                 , "Exif.GPSInfo.GPSTimeStamp"
					};
					static int bPrint = true ;
					for ( int k = 0 ; k < 15 ;   k++ ) {
						try {
							if ( bPrint ) printf("erasing %s\n",keys[k]);
							Exiv2::ExifKey  key = Exiv2::ExifKey(keys[k]);
							Exiv2::ExifData::iterator kk = exifData.findKey(key);
							if ( kk != exifData.end() ) exifData.erase(kk);
						} catch (...) {};
					}
					bPrint = false;
                    */
#endif
#if 0
					Exiv2::ExifData::const_iterator end = exifData.end();
					for (Exiv2::ExifData::iterator i = exifData.begin(); i != end; ++i) {
						char name[100];
						strcpy(name,i->key().c_str());
						// std::cout << "sniff " << i->key() << std::endl;
						if ( strstr(name,"GPS") )  {
							Exiv2::ExifData::iterator pos;
							Exiv2::ExifKey exifKey = Exiv2::ExifKey(name);
							pos = exifData.findKey(exifKey);
							while( pos != exifData.end()) {
								exifData.erase(pos);
							}
						}
					}
#endif
					if ( pPos ) {
						/*
						   struct _stat buf;
   int result;
   char timebuf[26];
   char* filename = "crt_stat.c";
   errno_t err;

   // Get data associated with "crt_stat.c":
   result = _stat( filename, &buf );

   int _utime(
   const char *filename,
   struct _utimbuf *times
);
   */

                        exifData["Exif.GPSInfo.GPSProcessingMethod" ] = "65 83 67 73 73 0 0 0 72 89 66 82 73 68 45 70 73 88"; // ASCII HYBRID-FIX
                        exifData["Exif.GPSInfo.GPSVersionID"        ] = "2 2 0 0";
                        exifData["Exif.GPSInfo.GPSMapDatum"         ] = "WGS-84";

                        exifData["Exif.GPSInfo.GPSLatitude"         ] = Position::toExifString(pPos->lat(),true,true);
                        exifData["Exif.GPSInfo.GPSLongitude"        ] = Position::toExifString(pPos->lon(),true,false);
                        exifData["Exif.GPSInfo.GPSAltitude"         ] = Position::toExifString(pPos->ele());

                        exifData["Exif.GPSInfo.GPSAltitudeRef"      ] = pPos->ele()<0.0?"1":"0";
						exifData["Exif.GPSInfo.GPSLatitudeRef"      ] = pPos->lat()>0?"N":"S";
						exifData["Exif.GPSInfo.GPSLongitudeRef"     ] = pPos->lon()>0?"E":"W";

                        exifData["Exif.GPSInfo.GPSDateStamp"        ] = stamp;
                        exifData["Exif.GPSInfo.GPSTimeStamp"        ] = Position::toExifTimeStamp(stamp);
						exifData["Exif.Image.GPSTag"                ] = 4908;

						printf("%s %s % 2d\n",arg.c_str(),pPos->toString().c_str(),pPos->delta());
                    } else {
                        printf("%s *** not in time dict ***\n",arg.c_str());
                    }
                    image->writeMetadata();
				}
            } catch ( ... ) {};
        }
    }

    return result ;
}
void ThreadRemoveExifDatas::run() {
    QTableWidgetItem *item;
 
    Exiv2::ExifData::iterator keyIteratorRemove;
    Exiv2::ExifKey *keyRemove;

    QVector<QString> listErrorRemoveFile;
    QVector<int> listErrorRemoveFilePosition;

    connect(this, SIGNAL(progressBarValue(int)), progressBar, SLOT(setValue(int)));
    connect(this, SIGNAL(progressBarSetVisible(bool)), progressBar, SLOT(setVisible(bool)));
    emit progressBarSetVisible(true);
    progressBar->setRange(0, tableWidgetJpeg->rowCount());

    for (int i = 0; i < tableWidgetJpeg->rowCount(); i++) {
        try {
            emit progressBarValue(i);
            Exiv2::Image::AutoPtr image;

            image = Exiv2::ImageFactory::open(tableWidgetJpeg->item(i, 7)->text().toStdString().c_str());

            if (tableWidgetJpeg->item(i, 3) != 0 || tableWidgetJpeg->item(i, 4) != 0 || tableWidgetJpeg->item(i, 5) != 0) {
                bool exifRemovido = false;
                assert(image.get() != 0);
                image->readMetadata();
                Exiv2::ExifData &exifData = image->exifData();

                Exiv2::ExifKey keyLatitude = Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude");
                keyIteratorRemove = exifData.findKey(keyLatitude);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSDateStamp");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSVersionID");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSMapDatum");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLatitudeRef");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLongitudeRef");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSAltitude");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSAltitudeRef");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSImgDirectionRef");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }
                
                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSImgDirection");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }

                keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSProcessingMethod");
                keyIteratorRemove = exifData.findKey(*keyRemove);
                if (keyIteratorRemove != exifData.end()) {
                    exifData.erase(keyIteratorRemove);
                    exifRemovido = true;
                }                
                
                if (exifRemovido) {
                    QString softwareTag = QApplication::applicationName();
                    softwareTag += " ";
                    softwareTag += QApplication::applicationVersion();
                    exifData["Exif.Image.Software"] = softwareTag.toStdString();
                }
                image->setExifData(exifData);
                image->writeMetadata();
                QString itemStatus = QString::fromUtf8("Dados Removidos");
                item = new QTableWidgetItem();
                item->setText(itemStatus);
                delete tableWidgetJpeg->takeItem(i, 3);
                delete tableWidgetJpeg->takeItem(i, 4);
                delete tableWidgetJpeg->takeItem(i, 5);
                tableWidgetJpeg->setItem(i, 6, item);
            } else {
                QString itemStatus = QString::fromUtf8("Não Há Dados Para Remover");
                item = new QTableWidgetItem();
                item->setText(itemStatus);
                tableWidgetJpeg->setItem(i, 6, item);
            }
        }
        catch (Exiv2::AnyError& e) {
            QString itemMsg;
            switch (e.code()) {
                case 2:
                    itemMsg = QString::fromUtf8("Erro ao Remover Arquivo");
                    // Quando ocorrer erro na remoção do arquivo, ele será colocado numa lista para
                    // que ao fim da execução seja tentado mais uma vez a sua remoção.
                    listErrorRemoveFile.push_back(tableWidgetJpeg->item(i, 7)->text());
                    listErrorRemoveFilePosition.push_back(i);
                    break;
                case 9:
                    itemMsg = QString::fromUtf8("Erro de Acesso ao Arquivo");
                    break;
                case 10:
                    itemMsg = QString::fromUtf8("Arquivo Somente Leitura");
                    break;
                case 11:
                    itemMsg = QString::fromUtf8("Arquivo Inválido");
                    break;
            }
            item = new QTableWidgetItem();
            item->setForeground(QColor(255, 0, 0));
            item->setText(itemMsg);
            tableWidgetJpeg->setItem(i, 6, item);
        }
    }

    for (int i = 0; i < listErrorRemoveFile.size(); i++) {
        //precisa pesquisar no disco se tem outro arquivo com o nome igual mas com a extensão diferente
        // se achar, tem que remover o atual e renomear o outro arquivo.
        QString fileName;
        QString filePath;
        QString itemMsg;
        int pos;

        pos = listErrorRemoveFile.at(i).lastIndexOf("/");
        fileName.operator =(QString::fromUtf8(listErrorRemoveFile.at(i).right(listErrorRemoveFile.at(i).size() - pos - 1).toStdString().c_str()));
        filePath = listErrorRemoveFile.at(i).left(pos);
        QDir directory(filePath);
        QStringList filesOnDirectory = directory.entryList(QDir::Files);
        QString regularExpression(fileName);
        regularExpression.append("[0-9]{1,4}");
        QRegExp fileRegExp(regularExpression, Qt::CaseSensitive, QRegExp::RegExp);
        QStringList filesLocated = filesOnDirectory.filter(fileRegExp);
        for (int j = 0; j < filesLocated.size(); j++) {
            itemMsg = QString::fromUtf8("Não Foi Possível Corrigir o Arquivo, Verifique Manualmente");
            QFileInfo fileTemp(directory, filesLocated.at(j));
            QFileInfo fileCurrent(directory, fileName);
            if (fileTemp.size() > fileCurrent.size()) {
                if (directory.remove(fileName)) {
                    if (directory.rename(filesLocated.at(j), fileName)) {
                        itemMsg = QString::fromUtf8("O Erro no Arquivo foi Corrigido");
                        delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 3);
                        delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 4);
                        delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 5);
                    }
                }
            } else {
                if (directory.remove(filesLocated.at(j)))
                    itemMsg = QString::fromUtf8("O Erro no Arquivo foi Corrigido");
            }
            item = new QTableWidgetItem();
            item->setForeground(QColor(0, 110, 0));
            item->setText(itemMsg);
            tableWidgetJpeg->setItem(listErrorRemoveFilePosition.at(i), 6, item);
        }
    }
    emit progressBarValue(tableWidgetJpeg->rowCount());
    sleep(1);
    emit progressBarSetVisible(false);
}
示例#27
0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool Copy::run()
{
  mStatus = CopyStatusPending;
  
  if (mOutputFile.length() == 0)
  {
    mStatus = CopyStatusError;
    mErrorMessage = "Invalid output url";
    return false;
  }

  std::ifstream src(mInputFile.c_str(),  std::ios::binary);
  std::ofstream dst(mOutputFile.c_str(), std::ios::binary);

  dst << src.rdbuf();

  //--------------------------------
  //  Inherit EXIF data if needed
  //--------------------------------
  if (mpExifData || mpXmpData || mpIptcData)
  {
    try
    {
      // NOTE: writing metadata is split out into separate data types for future
      //       functionality where we may want to inject certain input data into
      //       these formats
      Exiv2::Image::AutoPtr outputExivImage = Exiv2::ImageFactory::open(mOutputFile.c_str());

      if (outputExivImage.get() != 0)
      {
        if (mpExifData)
        {
          // Output image inherits input EXIF data
          outputExivImage->setExifData(*mpExifData);
        }

        if (mpXmpData)
        {
          // Output image inherits input XMP data
          outputExivImage->setXmpData(*mpXmpData);
        }

        if (mpIptcData)
        {
          // Output image inherits input IPTC data
          outputExivImage->setIptcData(*mpIptcData);
        }
      }

      outputExivImage->writeMetadata();

    }
    catch (Exiv2::AnyError& e)
    {
      mStatus = CopyStatusError;
      mErrorMessage = e.what();
      return false;
    }
  }

  mStatus = CopyStatusSuccess;

  return true;
}
示例#28
0
bool KExiv2::Private::saveOperations(const QFileInfo& finfo, Exiv2::Image::AutoPtr image) const
{
    try
    {
        Exiv2::AccessMode mode;
        bool wroteComment = false, wroteEXIF = false, wroteIPTC = false, wroteXMP = false;

        // We need to load target file metadata to merge with new one. It's mandatory with TIFF format:
        // like all tiff file structure is based on Exif.
        image->readMetadata();

        // Image Comments ---------------------------------

        mode = image->checkMode(Exiv2::mdComment);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            image->setComment(imageComments());
            wroteComment = true;
        }

        // Exif metadata ----------------------------------

        mode = image->checkMode(Exiv2::mdExif);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            if (image->mimeType() == "image/tiff")
            {
                Exiv2::ExifData orgExif = image->exifData();
                Exiv2::ExifData newExif;
                QStringList     untouchedTags;

                // With tiff image we cannot overwrite whole Exif data as well, because
                // image data are stored in Exif container. We need to take a care about
                // to not lost image data.
                untouchedTags << "Exif.Image.ImageWidth";
                untouchedTags << "Exif.Image.ImageLength";
                untouchedTags << "Exif.Image.BitsPerSample";
                untouchedTags << "Exif.Image.Compression";
                untouchedTags << "Exif.Image.PhotometricInterpretation";
                untouchedTags << "Exif.Image.FillOrder";
                untouchedTags << "Exif.Image.SamplesPerPixel";
                untouchedTags << "Exif.Image.StripOffsets";
                untouchedTags << "Exif.Image.RowsPerStrip";
                untouchedTags << "Exif.Image.StripByteCounts";
                untouchedTags << "Exif.Image.XResolution";
                untouchedTags << "Exif.Image.YResolution";
                untouchedTags << "Exif.Image.PlanarConfiguration";
                untouchedTags << "Exif.Image.ResolutionUnit";

                for (Exiv2::ExifData::iterator it = orgExif.begin(); it != orgExif.end(); ++it)
                {
                    if (untouchedTags.contains(it->key().c_str()))
                    {
                        newExif[it->key().c_str()] = orgExif[it->key().c_str()];
                    }
                }

                Exiv2::ExifData readedExif = exifMetadata();

                for (Exiv2::ExifData::iterator it = readedExif.begin(); it != readedExif.end(); ++it)
                {
                    if (!untouchedTags.contains(it->key().c_str()))
                    {
                        newExif[it->key().c_str()] = readedExif[it->key().c_str()];
                    }
                }

                image->setExifData(newExif);
            }
            else
            {
                image->setExifData(exifMetadata());
            }

            wroteEXIF = true;
        }

        // Iptc metadata ----------------------------------

        mode = image->checkMode(Exiv2::mdIptc);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            image->setIptcData(iptcMetadata());
            wroteIPTC = true;
        }

        // Xmp metadata -----------------------------------

        mode = image->checkMode(Exiv2::mdXmp);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
#ifdef _XMP_SUPPORT_
            image->setXmpData(xmpMetadata());
            wroteXMP = true;
#endif
        }

        if (!wroteComment && !wroteEXIF && !wroteIPTC && !wroteXMP)
        {
            kDebug() << "Writing metadata is not supported for file" << finfo.fileName();
            return false;
        }
        else if (!wroteEXIF || !wroteIPTC || !wroteXMP)
        {
            kDebug() << "Support for writing metadata is limited for file" << finfo.fileName()
                     << "EXIF" << wroteEXIF << "IPTC" << wroteIPTC << "XMP" << wroteXMP;
        }

        if (!updateFileTimeStamp)
        {
            // Don't touch access and modification timestamp of file.
            struct stat st;
            ::stat(QFile::encodeName(filePath), &st);

            struct utimbuf ut;
            ut.modtime = st.st_mtime;
            ut.actime  = st.st_atime;

            image->writeMetadata();

            ::utime(QFile::encodeName(filePath), &ut);
        }
        else
        {
            image->writeMetadata();
        }

        return true;
    }
    catch( Exiv2::Error& e )
    {
        printExiv2ExceptionError("Cannot save metadata using Exiv2 ", e);
    }

    return false;
}
示例#29
0
// *****************************************************************************
// Main
int main(int argc, char* const argv[])
try {

    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }

    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(argv[1]);
    if (image.get() == 0) {
        std::string error(argv[1]);
        error += " : Could not read file or unknown image type";
        throw Exiv2::Error(error);
    }

    // Load existing metadata
    int rc = image->readMetadata();
    if (rc) {
        std::string error = Exiv2::Image::strError(rc, argv[1]);
        throw Exiv2::Error(error);
    }

    Exiv2::ExifData &exifData = image->exifData();

    /*
      There are two pitfalls that we need to consider when setting the Exif user
      comment (Exif.Photo.UserComment) of an image:

      First, the type of the Exif user comment tag is "undefined" (and not
      ASCII) according to the Exif standard. This means that in Exiv2, we have
      to deal with a DataValue (and not an AsciiValue). DataValue has the usual
      two read methods, however, the one taking a const std::string& buf expects
      the string to contain a series of integers (e.g., "0 1 2") and not a text
      string. Thus, we need to use the read function that reads the value from a
      character buffer of a given length.

      Second, the Exif comment field starts with an eight character area that
      identifies the used character set. For ASCII, these eight characters are
      "ASCII\0\0\0". The actual comment follows after this code.

      Note: There is a more simple Exif tag for the title of an image. It is a
      20 byte string (type ASCII) and does not store two-byte characters.
      (Exif.Image.ImageDescription)
     */

    // Initialise a data value with the character set and comment
    std::string charset("ASCII\0\0\0", 8);
    std::string comment("A comment added to the Exif metadata through Exiv2");
    Exiv2::DataValue value;
    value.read(reinterpret_cast<const Exiv2::byte*>((charset + comment).data()), 
                8 + static_cast<long>(comment.size()));

    // Set the Exif comment
    Exiv2::ExifKey key("Exif.Photo.UserComment");
    Exiv2::ExifData::iterator pos = exifData.findKey(key);
    if (pos != exifData.end()) {
        // Use the existing Exif UserComment metadatum if there is one
        pos->setValue(&value);
    }
    else {
        // Otherwise add a new UserComment metadatum
        exifData.add(key, &value);
        pos = exifData.findKey(key);
    }

    // Now we should have a valid iterator in any case. We use the metadatum
    // output operator to print the formatted value
    std::cout << "Writing user comment '" << *pos << "' back to the image\n";

    rc = image->writeMetadata();
    if (rc) {
        std::string error = Exiv2::Image::strError(rc, argv[1]);
        throw Exiv2::Error(error);
    }

    return rc;
}
catch (Exiv2::Error& e) {
    std::cout << "Caught Exiv2 exception '" << e << "'\n";
    return -1;
}
bool tag_location( const std::string &filename, const location &loc)
{
    bool result = false;
    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open( filename);
    if (!image.get()) throw std::runtime_error( "could not open image file " + filename + " for metadata tags\n");
    image->readMetadata();
    Exiv2::ExifData data = image->exifData();

    if (data.findKey( Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude")) == data.end())
    {
        add_exif_coordinate( data, "Exif.GPSInfo.GPSLatitude", std::abs( loc.latitude));
        add_exif_coordinate( data, "Exif.GPSInfo.GPSLongitude", std::abs( loc.longitude));
        data["Exif.GPSInfo.GPSLatitudeRef"] = loc.latitude < 0 ? "S":"N";
        data["Exif.GPSInfo.GPSLongitudeRef"] = loc.longitude < 0 ? "W":"E";
        Exiv2::byte version[] = { 2, 0, 0, 0};
        data["Exif.GPSInfo.GPSVersionID"].getValue()->read( version, 4, Exiv2::invalidByteOrder);
        image->setExifData( data);
        image->writeMetadata();
        result = true;
    }

    return result;
}