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;
}
Ejemplo n.º 2
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();
}
Ejemplo n.º 3
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();
}
Ejemplo n.º 4
0
bool imwrite_tiff(matrix<unsigned short> output, string outputfilename,
                  Exiv2::ExifData exifData)
{
    int xsize, ysize;
    xsize = output.nc()/3;
    ysize = output.nr();



    outputfilename = outputfilename + ".tif";
    TIFF *out = TIFFOpen(outputfilename.c_str(),"w");
    if (!out)
    {
        cerr << "Can't open file for writing" << endl;
        return 1;
    }	
    TIFFSetField(out, TIFFTAG_IMAGEWIDTH, xsize);  
    TIFFSetField(out, TIFFTAG_IMAGELENGTH, ysize);
    TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3); //RGB
    TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 16);
    TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);    // set the origin of the image.
    //Magic below
    TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    //End Magic

    tsize_t linebytes = 3 * xsize * 2;//Size in bytes of a line
    unsigned short *buf = NULL;
    buf =(unsigned short *)_TIFFmalloc(linebytes);
    for (int j = 0; j < ysize; j++)
    {
        for(int i = 0; i < xsize; i ++)
        {
            buf[i*3  ] = output(j,i*3  );
            buf[i*3+1] = output(j,i*3+1);
            buf[i*3+2] = output(j,i*3+2);
        }
        if (TIFFWriteScanline(out, buf, j, 0) < 0)
            break;
    }
    (void) TIFFClose(out);

    if (buf)
        _TIFFfree(buf);

    exifData["Exif.Image.Orientation"] = 1;//set all images to unrotated
    exifData["Exif.Image.ImageWidth"] = output.nr();
    exifData["Exif.Image.ImageLength"] = output.nc()/3;

    Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(outputfilename.c_str());
    assert(image.get() != 0);

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

    return 0;
}
Ejemplo n.º 5
0
// *****************************************************************************
// 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;
}
}
Ejemplo n.º 6
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());
    }
}
Ejemplo n.º 7
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();
}
Ejemplo n.º 8
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));
    }
}
Ejemplo n.º 9
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;
}
Ejemplo n.º 10
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();
}
Ejemplo n.º 11
0
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;
        }
    }
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
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;
}
Ejemplo n.º 14
0
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);
}
Ejemplo n.º 15
-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;
}