Search in sources :

Example 6 with Metadata

use of com.drew.metadata.Metadata in project ArachneCentralAPI by OHDSI.

the class BaseUserServiceImpl method saveAvatar.

@Override
public void saveAvatar(U user, MultipartFile file) throws IOException, WrongFileFormatException, ImageProcessingException, MetadataException, IllegalAccessException, SolrServerException, NoSuchFieldException {
    String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
    BufferedImage img = ImageIO.read(file.getInputStream());
    if (img == null) {
        throw new WrongFileFormatException("file", "File format is not supported");
    }
    final File avatar = getUserAvatarFile(user);
    Metadata metadata = ImageMetadataReader.readMetadata(file.getInputStream());
    ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
    int orientation = 1;
    try {
        orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
    } catch (Exception ignore) {
        LOGGER.debug(ignore.getMessage(), ignore);
    }
    List<Scalr.Rotation> rotations = new LinkedList<>();
    switch(orientation) {
        case 1:
            break;
        case // Flip X
        2:
            rotations.add(Scalr.Rotation.FLIP_HORZ);
            break;
        case // PI rotation
        3:
            rotations.add(Scalr.Rotation.CW_180);
            break;
        case // Flip Y
        4:
            rotations.add(Scalr.Rotation.FLIP_VERT);
            break;
        case // - PI/2 and Flip X
        5:
            rotations.add(Scalr.Rotation.CW_90);
            rotations.add(Scalr.Rotation.FLIP_HORZ);
            break;
        case // -PI/2 and -width
        6:
            rotations.add(Scalr.Rotation.CW_90);
            break;
        case // PI/2 and Flip
        7:
            rotations.add(Scalr.Rotation.CW_90);
            rotations.add(Scalr.Rotation.FLIP_VERT);
            break;
        case // PI / 2
        8:
            rotations.add(Scalr.Rotation.CW_270);
            break;
        default:
            break;
    }
    for (Scalr.Rotation rotation : rotations) {
        img = Scalr.rotate(img, rotation);
    }
    BufferedImage thumbnail = Scalr.resize(img, Math.min(Math.max(img.getHeight(), img.getWidth()), 640), Scalr.OP_ANTIALIAS);
    ImageIO.write(thumbnail, fileExt, avatar);
    user.setUpdated(new Date());
    U savedUser = userRepository.save(user);
    indexBySolr(savedUser);
}
Also used : WrongFileFormatException(com.odysseusinc.arachne.portal.exception.WrongFileFormatException) Metadata(com.drew.metadata.Metadata) BufferedImage(java.awt.image.BufferedImage) SolrServerException(org.apache.solr.client.solrj.SolrServerException) UserNotFoundException(com.odysseusinc.arachne.portal.exception.UserNotFoundException) MetadataException(com.drew.metadata.MetadataException) WrongFileFormatException(com.odysseusinc.arachne.portal.exception.WrongFileFormatException) IOException(java.io.IOException) PasswordValidationException(com.odysseusinc.arachne.portal.exception.PasswordValidationException) ImageProcessingException(com.drew.imaging.ImageProcessingException) NotUniqueException(com.odysseusinc.arachne.portal.exception.NotUniqueException) ValidationException(com.odysseusinc.arachne.portal.exception.ValidationException) ArachneSystemRuntimeException(com.odysseusinc.arachne.portal.exception.ArachneSystemRuntimeException) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) LinkedList(java.util.LinkedList) Date(java.util.Date) Scalr(org.imgscalr.Scalr) ExifIFD0Directory(com.drew.metadata.exif.ExifIFD0Directory) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile)

Example 7 with Metadata

use of com.drew.metadata.Metadata in project UniversalMediaServer by UniversalMediaServer.

the class ImagesUtil method parseImage.

/**
 * Parses an image file and stores the results in the given
 * {@link DLNAMediaInfo}. Parsing is performed using both
 * <a href=https://github.com/drewnoakes/metadata-extractor>Metadata Extractor</a>
 * and {@link ImageIO}. While Metadata Extractor offers more detailed
 * information, {@link ImageIO} offers information that is convenient for
 * image transformation with {@link ImageIO}. Parsing will be performed if
 * just one of the two methods produces results, but some details will be
 * missing if either one failed.
 * <p><b>
 * This method consumes and closes {@code inputStream}.
 * </b>
 * @param file the {@link File} to parse.
 * @param media the {@link DLNAMediaInfo} instance to store the parsing
 *              results to.
 * @throws IOException if an IO error occurs or no information can be parsed.
 */
public static void parseImage(File file, DLNAMediaInfo media) throws IOException {
    // 1 MB
    final int MAX_BUFFER = 1048576;
    if (file == null) {
        throw new IllegalArgumentException("parseImage: file cannot be null");
    }
    if (media == null) {
        throw new IllegalArgumentException("parseImage: media cannot be null");
    }
    boolean trace = LOGGER.isTraceEnabled();
    if (trace) {
        LOGGER.trace("Parsing image file \"{}\"", file.getAbsolutePath());
    }
    long size = file.length();
    ResettableInputStream inputStream = new ResettableInputStream(Files.newInputStream(file.toPath()), MAX_BUFFER);
    try {
        Metadata metadata = null;
        FileType fileType = null;
        try {
            fileType = FileTypeDetector.detectFileType(inputStream);
            metadata = getMetadata(inputStream, fileType);
        } catch (IOException e) {
            metadata = new Metadata();
            LOGGER.debug("Error reading \"{}\": {}", file.getAbsolutePath(), e.getMessage());
            LOGGER.trace("", e);
        } catch (ImageProcessingException e) {
            metadata = new Metadata();
            LOGGER.debug("Error parsing {} metadata for \"{}\": {}", fileType.toString().toUpperCase(Locale.ROOT), file.getAbsolutePath(), e.getMessage());
            LOGGER.trace("", e);
        }
        ImageFormat format = ImageFormat.toImageFormat(fileType);
        if (format == null || format == ImageFormat.TIFF) {
            ImageFormat tmpformat = ImageFormat.toImageFormat(metadata);
            if (tmpformat != null) {
                format = tmpformat;
            }
        }
        if (inputStream.isFullResetAvailable()) {
            inputStream.fullReset();
        } else {
            // If we can't reset it, close it and create a new
            inputStream.close();
            inputStream = new ResettableInputStream(Files.newInputStream(file.toPath()), MAX_BUFFER);
        }
        ImageInfo imageInfo = null;
        try {
            imageInfo = ImageIOTools.readImageInfo(inputStream, size, metadata, false);
        } catch (UnknownFormatException | IIOException | ParseException e) {
            if (format == null) {
                throw new UnknownFormatException("Unable to recognize image format for \"" + file.getAbsolutePath() + "\" - parsing failed", e);
            }
            LOGGER.debug("Unable to parse \"{}\" with ImageIO because the format is unsupported, image information will be limited", file.getAbsolutePath());
            LOGGER.trace("ImageIO parse failure reason: {}", e.getMessage());
            // Gather basic information from the data we have
            if (metadata != null) {
                try {
                    imageInfo = ImageInfo.create(metadata, format, size, true, true);
                } catch (ParseException pe) {
                    LOGGER.debug("Unable to parse metadata for \"{}\": {}", file.getAbsolutePath(), pe.getMessage());
                    LOGGER.trace("", pe);
                }
            }
        }
        if (imageInfo == null && format == null) {
            throw new ParseException("Parsing of \"" + file.getAbsolutePath() + "\" failed");
        }
        if (format == null) {
            format = imageInfo.getFormat();
        } else if (imageInfo != null && imageInfo.getFormat() != null && format != imageInfo.getFormat()) {
            if (imageInfo.getFormat() == ImageFormat.TIFF && format.isRaw()) {
                if (format == ImageFormat.ARW && !isARW(metadata)) {
                    // XXX Remove this if https://github.com/drewnoakes/metadata-extractor/issues/217 is fixed
                    // Metadata extractor misidentifies some Photoshop created TIFFs for ARW, correct it
                    format = ImageFormat.toImageFormat(metadata);
                    if (format == null) {
                        format = ImageFormat.TIFF;
                    }
                    LOGGER.trace("Correcting misidentified image format ARW to {} for \"{}\"", format, file.getAbsolutePath());
                } else {
                    /*
						 * ImageIO recognizes many RAW formats as TIFF because
						 * of their close relationship let's treat them as what
						 * they really are.
						 */
                    imageInfo = ImageInfo.create(imageInfo.getWidth(), imageInfo.getHeight(), format, size, imageInfo.getBitDepth(), imageInfo.getNumComponents(), imageInfo.getColorSpace(), imageInfo.getColorSpaceType(), metadata, false, imageInfo.isImageIOSupported());
                    LOGGER.trace("Correcting misidentified image format TIFF to {} for \"{}\"", format.toString(), file.getAbsolutePath());
                }
            } else {
                LOGGER.debug("Image parsing for \"{}\" was inconclusive, metadata parsing " + "detected {} format while ImageIO detected {}. Choosing {}.", file.getAbsolutePath(), format, imageInfo.getFormat(), imageInfo.getFormat());
                format = imageInfo.getFormat();
            }
        }
        media.setImageInfo(imageInfo);
        if (format != null) {
            media.setCodecV(format.toFormatConfiguration());
            media.setContainer(format.toFormatConfiguration());
        }
        if (trace) {
            LOGGER.trace("Parsing of image \"{}\" completed", file.getName());
        }
    } finally {
        inputStream.close();
    }
}
Also used : ImageProcessingException(com.drew.imaging.ImageProcessingException) Metadata(com.drew.metadata.Metadata) IIOException(javax.imageio.IIOException) IIOException(javax.imageio.IIOException) FileType(com.drew.imaging.FileType) UnknownFormatException(net.pms.util.UnknownFormatException) ParseException(net.pms.util.ParseException) ResettableInputStream(net.pms.util.ResettableInputStream)

Example 8 with Metadata

use of com.drew.metadata.Metadata in project react-native-camera by react-native-community.

the class MutableImage method fixOrientation.

public void fixOrientation() throws ImageMutationFailedException {
    try {
        Metadata metadata = originalImageMetaData();
        ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
        if (exifIFD0Directory == null) {
            return;
        } else if (exifIFD0Directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) {
            int exifOrientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
            if (exifOrientation != 1) {
                rotate(exifOrientation);
                exifIFD0Directory.setInt(ExifIFD0Directory.TAG_ORIENTATION, 1);
            }
        }
    } catch (ImageProcessingException | IOException | MetadataException e) {
        throw new ImageMutationFailedException("failed to fix orientation", e);
    }
}
Also used : ImageProcessingException(com.drew.imaging.ImageProcessingException) Metadata(com.drew.metadata.Metadata) ExifIFD0Directory(com.drew.metadata.exif.ExifIFD0Directory) IOException(java.io.IOException) MetadataException(com.drew.metadata.MetadataException)

Example 9 with Metadata

use of com.drew.metadata.Metadata in project bioformats by openmicroscopy.

the class EXIFServiceImpl method initialize.

// -- EXIFService API methods --
@Override
public void initialize(String file) throws ServiceException, IOException {
    try {
        File jpegFile = new File(file);
        Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
        directory = metadata.getDirectory(ExifSubIFDDirectory.class);
    } catch (Throwable e) {
        throw new ServiceException("Could not read EXIF data", e);
    }
}
Also used : ExifSubIFDDirectory(com.drew.metadata.exif.ExifSubIFDDirectory) ServiceException(loci.common.services.ServiceException) Metadata(com.drew.metadata.Metadata) File(java.io.File)

Example 10 with Metadata

use of com.drew.metadata.Metadata in project structr by structr.

the class ImageHelper method getExifData.

public static JSONObject getExifData(final File originalImage) {
    final JSONObject exifDataJson = new JSONObject();
    try {
        final Metadata metadata = getMetadata(originalImage);
        final ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
        final ExifSubIFDDirectory exifSubIFDDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
        final GpsDirectory gpsDirectory = metadata.getFirstDirectoryOfType(GpsDirectory.class);
        if (exifIFD0Directory != null) {
            final JSONObject exifIFD0DataJson = new JSONObject();
            exifIFD0Directory.getTags().forEach((tag) -> {
                exifIFD0DataJson.put(tag.getTagName(), exifIFD0Directory.getDescription(tag.getTagType()));
            });
            originalImage.setProperty(StructrApp.key(Image.class, "exifIFD0Data"), exifIFD0DataJson.toString());
            exifDataJson.putOnce("exifIFD0Data", exifIFD0DataJson);
        }
        if (exifSubIFDDirectory != null) {
            final JSONObject exifSubIFDDataJson = new JSONObject();
            exifSubIFDDirectory.getTags().forEach((tag) -> {
                exifSubIFDDataJson.put(tag.getTagName(), exifSubIFDDirectory.getDescription(tag.getTagType()));
            });
            originalImage.setProperty(StructrApp.key(Image.class, "exifSubIFDData"), exifSubIFDDataJson.toString());
            exifDataJson.putOnce("exifSubIFDData", exifSubIFDDataJson);
        }
        if (gpsDirectory != null) {
            final JSONObject exifGpsDataJson = new JSONObject();
            gpsDirectory.getTags().forEach((tag) -> {
                exifGpsDataJson.put(tag.getTagName(), gpsDirectory.getDescription(tag.getTagType()));
            });
            originalImage.setProperty(StructrApp.key(Image.class, "gpsData"), exifGpsDataJson.toString());
            exifDataJson.putOnce("gpsData", exifGpsDataJson);
        }
        return exifDataJson;
    } catch (Exception ex) {
        logger.warn("Unable to extract EXIF metadata.", ex);
    }
    return null;
}
Also used : GpsDirectory(com.drew.metadata.exif.GpsDirectory) ExifSubIFDDirectory(com.drew.metadata.exif.ExifSubIFDDirectory) JSONObject(org.json.JSONObject) Metadata(com.drew.metadata.Metadata) ExifIFD0Directory(com.drew.metadata.exif.ExifIFD0Directory) BufferedImage(java.awt.image.BufferedImage) Image(org.structr.web.entity.Image) JSONException(org.json.JSONException) FrameworkException(org.structr.common.error.FrameworkException) ImageProcessingException(com.drew.imaging.ImageProcessingException) MetadataException(com.drew.metadata.MetadataException) IOException(java.io.IOException)

Aggregations

Metadata (com.drew.metadata.Metadata)10 ImageProcessingException (com.drew.imaging.ImageProcessingException)9 IOException (java.io.IOException)6 MetadataException (com.drew.metadata.MetadataException)5 ExifIFD0Directory (com.drew.metadata.exif.ExifIFD0Directory)5 BufferedImage (java.awt.image.BufferedImage)3 FileType (com.drew.imaging.FileType)2 ExifSubIFDDirectory (com.drew.metadata.exif.ExifSubIFDDirectory)2 File (java.io.File)2 IIOException (javax.imageio.IIOException)2 ParseException (net.pms.util.ParseException)2 UnknownFormatException (net.pms.util.UnknownFormatException)2 GpsDirectory (com.drew.metadata.exif.GpsDirectory)1 ArachneSystemRuntimeException (com.odysseusinc.arachne.portal.exception.ArachneSystemRuntimeException)1 NotExistException (com.odysseusinc.arachne.portal.exception.NotExistException)1 NotUniqueException (com.odysseusinc.arachne.portal.exception.NotUniqueException)1 PasswordValidationException (com.odysseusinc.arachne.portal.exception.PasswordValidationException)1 PermissionDeniedException (com.odysseusinc.arachne.portal.exception.PermissionDeniedException)1 UserNotFoundException (com.odysseusinc.arachne.portal.exception.UserNotFoundException)1 ValidationException (com.odysseusinc.arachne.portal.exception.ValidationException)1