Example usage for org.apache.commons.imaging.formats.tiff.write TiffOutputDirectory removeField

List of usage examples for org.apache.commons.imaging.formats.tiff.write TiffOutputDirectory removeField

Introduction

In this page you can find the example usage for org.apache.commons.imaging.formats.tiff.write TiffOutputDirectory removeField.

Prototype

public void removeField(final int tag) 

Source Link

Usage

From source file:net.mozq.picto.core.ProcessCore.java

private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData,
        Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException {

    ProcessDataStatus status;//from ww w.ja v a2 s .  co  m

    Path destParentPath = processData.getDestPath().getParent();
    if (destParentPath != null) {
        Files.createDirectories(destParentPath);
    }

    if (processCondition.isCheckDigest()
            || (processCondition.isChangeExifDate() && processData.getBaseDate() != null)
            || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) {
        Path destTempPath = null;
        try {
            destTempPath = Files.createTempFile(processData.getDestPath().getParent(),
                    processData.getDestPath().getFileName().toString(), null);

            if (processCondition.isCheckDigest()) {
                String algorithm = FILE_DIGEST_ALGORITHM;

                MessageDigest srcMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) {
                    Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE);
                }
                byte[] srcDigest = srcMD.digest();

                MessageDigest destMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) {
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                    }
                }
                byte[] destDigest = destMD.digest();

                if (!isSame(srcDigest, destDigest)) {
                    throw new PictoFileDigestMismatchException(
                            Messages.getString("message.error.digest.mismatch"));
                }
            } else if (processCondition.isRemveExifTagsAll()) {
                ExifRewriter exifRewriter = new ExifRewriter();
                try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                    exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os);
                } catch (ImageReadException | ImageWriteException e) {
                    throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                }
            } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) {
                ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath());
                TiffOutputSet outputSet = getOutputSet(imageMetadata);
                if (outputSet == null) {
                    Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE);
                } else {
                    if (processCondition.isChangeExifDate()) {
                        SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN);
                        exifDateFormat.setTimeZone(processCondition.getTimeZone());
                        String exifBaseDate = exifDateFormat.format(processData.getBaseDate());

                        DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN);
                        String exifBaseSubsec = exifSubsecFormat
                                .format((int) (processData.getBaseDate().getTime() / 10) % 100);

                        try {
                            TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
                            TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                            if (rootDirectory != null) {
                                rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME);
                                rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate);
                            }
                            if (exifDirectory != null) {
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
                                        exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
                                        exifBaseSubsec);
                            }
                        } catch (ImageWriteException e) {
                            throw new PictoFileChangeException(Messages.getString("message.error.edit.file"),
                                    e);
                        }
                    }

                    if (processCondition.isRemveExifTagsGps()) {
                        outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO);
                    }

                    ExifRewriter exifRewriter = new ExifRewriter();
                    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                        exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os,
                                outputSet);
                    } catch (ImageReadException | ImageWriteException e) {
                        throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                    }
                }
            }

            Path destPath;
            if (processCondition.getOperationType() == OperationType.Overwrite) {
                destPath = processData.getSrcPath();
            } else {
                destPath = processData.getDestPath();
            }
            try {
                Files.move(destTempPath, destPath, OPTIONS_MOVE);
                if (processCondition.getOperationType() == OperationType.Move) {
                    Files.deleteIfExists(processData.getSrcPath());
                }
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    // Overwrite
                    Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE);
                    if (processCondition.getOperationType() == OperationType.Move) {
                        Files.deleteIfExists(processData.getSrcPath());
                    }
                    status = ProcessDataStatus.Success;
                }
            }
        } finally {
            if (destTempPath != null) {
                Files.deleteIfExists(destTempPath);
            }
        }
    } else {
        switch (processCondition.getOperationType()) {
        case Copy:
            try {
                Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Move:
            try {
                Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Overwrite:
            // NOP
            status = ProcessDataStatus.Success;
            break;
        default:
            throw new IllegalStateException(processCondition.getOperationType().toString());
        }
    }

    if (status == ProcessDataStatus.Success) {
        FileTime creationFileTime = processData.getSrcFileAttributes().creationTime();
        FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime();
        FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime();
        if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate()
                || processCondition.isChangeFileAccessDate()) {
            if (processData.getBaseDate() != null) {
                FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime());
                if (processCondition.isChangeFileCreationDate()) {
                    creationFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileModifiedDate()) {
                    modifiedFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileAccessDate()) {
                    accessFileTime = baseFileTime;
                }
            }
        }
        BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(),
                BasicFileAttributeView.class);
        attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime);
    }

    return status;
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

private void updateUserComments(TiffOutputDirectory exifDirectory)
        throws IOException, ImageReadException, ImageWriteException {
    exifDirectory.removeField(AllTagConstants.EXIF_TAG_USER_COMMENT);

    exifDirectory.add(AllTagConstants.EXIF_TAG_USER_COMMENT, USER_COMMENTS);
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

public void modifyXpTitle(File fileIn, File fileOut, String newValue) throws Exception {
    TiffImageMetadata exif;//from   w  w w.j  a  v a2s . co m
    ImageMetadata meta = Imaging.getMetadata(fileIn);
    if (meta instanceof JpegImageMetadata) {
        exif = ((JpegImageMetadata) meta).getExif();
    } else if (meta instanceof TiffImageMetadata) {
        exif = (TiffImageMetadata) meta;
    } else {
        return;
    }
    TiffOutputSet outputSet = exif.getOutputSet();
    TiffOutputDirectory exifDir = outputSet.findDirectory(TiffDirectoryConstants.DIRECTORY_TYPE_EXIF);
    exifDir.removeField(AllTagConstants.EXIF_TAG_XPTITLE);
    exifDir.add(AllTagConstants.EXIF_TAG_XPTITLE, newValue);

    ExifRewriter rewriter = new ExifRewriter();
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(fileOut);
        rewriter.updateExifMetadataLossy(fileIn, fos, outputSet);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

private void updateImageUniqueId(TiffOutputDirectory exifDirectory, String newId)
        throws IOException, ImageReadException, ImageWriteException {
    exifDirectory.removeField(TiffConstants.EXIF_TAG_IMAGE_UNIQUE_ID);

    TiffOutputField idField = new TiffOutputField(TiffConstants.EXIF_TAG_IMAGE_UNIQUE_ID, FieldType.ASCII,
            newId.getBytes("UTF-8").length, newId.getBytes("UTF-8"));

    exifDirectory.add(idField);// ww  w . ja  v  a2  s .c  o  m
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

private void updateDocumentName(TiffOutputDirectory exifDirectory, String documentName)
        throws IOException, ImageReadException, ImageWriteException {

    exifDirectory.removeField(AllTagConstants.TIFF_TAG_DOCUMENT_NAME);
    exifDirectory.add(AllTagConstants.TIFF_TAG_DOCUMENT_NAME, documentName);

}

From source file:com.hygenics.imaging.ImageCleanup.java

public byte[] writeMetaData(String data, byte[] ibytes) {
    // write metadata based on the metadata columns list
    TiffOutputSet outset = null;//from w ww.java2s .com
    BufferedImage bi;
    ImageMetadata metadata;
    ByteArrayOutputStream bos = null;
    try {

        // get the buffered image to write to
        bi = Imaging.getBufferedImage(ibytes);
        metadata = Imaging.getMetadata(ibytes);
        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        if (null != jpegMetadata) {
            // get the image exif data
            TiffImageMetadata exif = jpegMetadata.getExif();
            outset = exif.getOutputSet();
        }

        if (outset == null) {
            // get a new set (directory structured to write to)
            outset = new TiffOutputSet();
        }

        TiffOutputDirectory exdir = outset.getOrCreateExifDirectory();
        exdir.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT);

        exdir.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, data.trim());

        bos = new ByteArrayOutputStream();
        ByteArrayInputStream bis = new ByteArrayInputStream(ibytes);

        ExifRewriter exrw = new ExifRewriter();

        // read to a byte stream
        exrw.updateExifMetadataLossy(bis, bos, outset);

        // read the input from the byte buffer
        ibytes = bos.toByteArray();
        bis.close();
        bos.close();

    } catch (ImageReadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ImageWriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return ibytes;
}

From source file:joachimeichborn.geotag.io.jpeg.PictureMetadataWriter.java

private void setAltitude(final double aAltitude, final TiffOutputSet aOutputSet) throws ImageWriteException {
    final TiffOutputDirectory gpsDirectory = aOutputSet.getOrCreateGPSDirectory();

    final byte altitudeRef = (byte) (aAltitude < 0 ? 1 : 0);
    final double altitude = Math.abs(aAltitude);

    gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
    gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF, altitudeRef);

    gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_ALTITUDE);
    gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_ALTITUDE, RationalNumber.valueOf(altitude));
}

From source file:at.ac.tuwien.qse.sepm.dao.repo.impl.JpegSerializer.java

@Override
public void update(InputStream is, OutputStream os, PhotoMetadata metadata) throws DAOException {
    if (is == null)
        throw new IllegalArgumentException();
    if (os == null)
        throw new IllegalArgumentException();
    if (metadata == null)
        throw new IllegalArgumentException();
    LOGGER.debug("updating photo metadata {}", metadata);

    String tags = "travelimg";

    for (Tag element : metadata.getTags()) {
        tags += "/" + element.getName();
    }/*from w  w  w .  j av  a 2s  .c  o  m*/

    Rating rating = metadata.getRating();
    tags += "/rating|" + rating;

    Place place = metadata.getPlace();
    if (place != null) {
        tags += "/place|" + place.getCity() + "|" + place.getCountry() + "|" + place.getLatitude() + "|"
                + place.getLongitude();
    }

    Journey journey = metadata.getJourney();
    if (journey != null) {
        tags += "/journey|" + journey.getName() + "|" + journey.getStartDate().format(DATE_FORMATTER) + "|"
                + journey.getEndDate().format(DATE_FORMATTER);
    }

    Photographer photographer = metadata.getPhotographer();
    if (photographer != null) {
        tags += "/photographer|" + photographer.getName();
    }

    try {
        is.mark(Integer.MAX_VALUE);
        ImageMetadata imageData = Imaging.getMetadata(is, null);
        if (imageData == null) {
            LOGGER.debug("could not find image metadata");
            throw new DAOException("No metadata found.");
        }
        if (!(imageData instanceof JpegImageMetadata)) {
            LOGGER.debug("metadata is of unknown type");
            throw new DAOException("Metadata is of unknown type.");
        }

        JpegImageMetadata jpegData = (JpegImageMetadata) imageData;
        TiffOutputSet outputSet = new TiffOutputSet();
        TiffImageMetadata exifData = jpegData.getExif();
        if (exifData != null) {
            outputSet = exifData.getOutputSet();
        }

        TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();
        outputSet.setGPSInDegrees(metadata.getLongitude(), metadata.getLatitude());

        exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
        exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
                DATE_FORMATTER.format(metadata.getDatetime()));

        exifDirectory.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT);
        exifDirectory.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, tags);

        is.reset();
        new ExifRewriter().updateExifMetadataLossless(is, os, outputSet);

    } catch (IOException | ImageReadException | ImageWriteException ex) {
        LOGGER.warn("failed updating metadata");
        throw new DAOException(ex);
    }

    LOGGER.debug("updated photo metadata");
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

private void updateImageDescription(TiffOutputDirectory exifDirectory, String imageDescription)
        throws IOException, ImageReadException, ImageWriteException {

    // Note that you should first remove the field/tag if it already
    // exists in this directory, or you may end up with duplicate tag.
    // This method won't fail if the field does not exist.
    exifDirectory.removeField(AllTagConstants.TIFF_TAG_IMAGE_DESCRIPTION);

    exifDirectory.add(AllTagConstants.TIFF_TAG_IMAGE_DESCRIPTION, imageDescription);
}

From source file:adams.flow.transformer.exiftagoperation.ApacheCommonsExifTagRemove.java

/**
 * Processes the incoming data.//ww w . jav  a2s  .c o  m
 *
 * @param input   the input to process
 * @param errors   for storing errors
 * @return      the generated output
 */
@Override
protected Object doProcess(Object input, MessageCollection errors) {
    Object result;
    File inputFile;
    File tmpFile;
    JpegImageMetadata meta;
    TiffImageMetadata exif;
    TiffOutputSet outputSet;
    TiffOutputDirectory exifDir;
    FileOutputStream fos;
    BufferedOutputStream bos;

    result = null;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();
    tmpFile = TempUtils.createTempFile(getClass().getSimpleName().toLowerCase() + "-", ".jpg");

    fos = null;
    bos = null;
    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                outputSet = exif.getOutputSet();
                if (outputSet != null) {
                    exifDir = outputSet.getOrCreateExifDirectory();
                    if (exifDir != null) {
                        exifDir.removeField(m_Tag.getTagInfo());
                        fos = new FileOutputStream(tmpFile);
                        bos = new BufferedOutputStream(fos);
                        new ExifRewriter().updateExifMetadataLossless(inputFile, bos, outputSet);
                        if (!FileUtils.copy(tmpFile, inputFile))
                            errors.add("Failed to replace " + inputFile + " with updated EXIF from " + tmpFile);
                        if (!FileUtils.delete(tmpFile))
                            errors.add("Failed to delete tmp file: " + tmpFile);
                    } else {
                        errors.add("Failed to obtain EXIF directory: " + input);
                    }
                } else {
                    errors.add("Failed to obtain output set: " + input);
                }
            } else {
                errors.add("No EXIF meta-data available: " + input);
            }
        } else {
            errors.add("No meta-data available: " + input);
        }
    } catch (Exception e) {
        errors.add("Failed to read EXIF tag " + m_Tag + " from: " + input, e);
    } finally {
        FileUtils.closeQuietly(bos);
        FileUtils.closeQuietly(fos);
    }

    if (errors.isEmpty())
        result = input;

    return result;
}