001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.layer.geoimage; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Dimension; 007import java.awt.Graphics2D; 008import java.awt.geom.AffineTransform; 009import java.awt.image.BufferedImage; 010import java.io.IOException; 011import java.io.InputStream; 012import java.io.UncheckedIOException; 013import java.net.URI; 014import java.time.Instant; 015import java.util.Locale; 016import java.util.Map; 017import java.util.function.Consumer; 018import java.util.stream.Stream; 019 020import javax.imageio.ImageReadParam; 021import javax.imageio.ImageReader; 022 023import com.drew.imaging.jpeg.JpegMetadataReader; 024import com.drew.imaging.jpeg.JpegProcessingException; 025import com.drew.imaging.png.PngMetadataReader; 026import com.drew.imaging.png.PngProcessingException; 027import com.drew.imaging.tiff.TiffMetadataReader; 028import com.drew.imaging.tiff.TiffProcessingException; 029import com.drew.metadata.Directory; 030import com.drew.metadata.Metadata; 031import com.drew.metadata.MetadataException; 032import com.drew.metadata.exif.ExifIFD0Directory; 033import com.drew.metadata.exif.GpsDirectory; 034import com.drew.metadata.iptc.IptcDirectory; 035import com.drew.metadata.jpeg.JpegDirectory; 036import com.drew.metadata.xmp.XmpDirectory; 037import org.openstreetmap.josm.data.imagery.street_level.Projections; 038import org.openstreetmap.josm.tools.ExifReader; 039import org.openstreetmap.josm.tools.JosmRuntimeException; 040import org.openstreetmap.josm.tools.Logging; 041 042/** 043 * Image utilities 044 * @since 18592 045 */ 046public final class ImageUtils { 047 private ImageUtils() { 048 // Hide constructor 049 } 050 051 /** 052 * Rotate an image, if needed 053 * @param img The image to rotate 054 * @param exifOrientation The exif orientation 055 * @return The rotated image or the original 056 */ 057 public static BufferedImage applyExifRotation(BufferedImage img, Integer exifOrientation) { 058 if (exifOrientation == null || !ExifReader.orientationNeedsCorrection(exifOrientation)) { 059 return img; 060 } 061 boolean switchesDimensions = ExifReader.orientationSwitchesDimensions(exifOrientation); 062 int width = switchesDimensions ? img.getHeight() : img.getWidth(); 063 int height = switchesDimensions ? img.getWidth() : img.getHeight(); 064 BufferedImage rotated = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 065 AffineTransform transform = ExifReader.getRestoreOrientationTransform(exifOrientation, img.getWidth(), img.getHeight()); 066 Graphics2D g = rotated.createGraphics(); 067 g.drawImage(img, transform, null); 068 g.dispose(); 069 return rotated; 070 } 071 072 /** 073 * Common subsampling method 074 * @param reader The image reader 075 * @param target The target area 076 * @return The sampling parameters 077 */ 078 public static ImageReadParam withSubsampling(ImageReader reader, Dimension target) { 079 try { 080 ImageReadParam param = reader.getDefaultReadParam(); 081 Dimension source = new Dimension(reader.getWidth(0), reader.getHeight(0)); 082 if (source.getWidth() > target.getWidth() || source.getHeight() > target.getHeight()) { 083 int subsampling = (int) Math.floor(Math.max( 084 source.getWidth() / target.getWidth(), 085 source.getHeight() / target.getHeight())); 086 param.setSourceSubsampling(subsampling, subsampling, 0, 0); 087 } 088 return param; 089 } catch (IOException e) { 090 throw new UncheckedIOException(e); 091 } 092 } 093 094 /** 095 * Apply exif information from an {@link InputStream} 096 * @param image The image to apply information to 097 * @param inputStream The input stream to read 098 */ 099 public static void applyExif(ImageMetadata image, InputStream inputStream) { 100 Metadata metadata; 101 102 if (image == null || inputStream == null) { 103 return; 104 } 105 106 metadata = getMetadata(image.getImageURI(), inputStream); 107 if (metadata == null) { 108 image.setExifTime(image.getLastModified()); 109 image.setExifCoor(null); 110 image.setPos(null); 111 return; 112 } 113 final String fn = image.getImageURI().toString(); 114 115 IptcDirectory dirIptc = metadata.getFirstDirectoryOfType(IptcDirectory.class); 116 if (dirIptc != null) { 117 ifNotNull(ExifReader.readCaption(dirIptc), image::setIptcCaption); 118 ifNotNull(ExifReader.readHeadline(dirIptc), image::setIptcHeadline); 119 ifNotNull(ExifReader.readKeywords(dirIptc), image::setIptcKeywords); 120 ifNotNull(ExifReader.readObjectName(dirIptc), image::setIptcObjectName); 121 } 122 123 for (XmpDirectory xmpDirectory : metadata.getDirectoriesOfType(XmpDirectory.class)) { 124 Map<String, String> properties = xmpDirectory.getXmpProperties(); 125 final String projectionType = "GPano:ProjectionType"; 126 if (properties.containsKey(projectionType)) { 127 Stream.of(Projections.values()).filter(p -> p.name().equalsIgnoreCase(properties.get(projectionType))) 128 .findFirst().ifPresent(image::setProjectionType); 129 break; 130 } 131 } 132 133 // Changed to silently cope with no time info in exif. One case 134 // of person having time that couldn't be parsed, but valid GPS info 135 Instant time = null; 136 try { 137 time = ExifReader.readInstant(metadata); 138 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException ex) { 139 Logging.warn(ex); 140 } 141 142 if (time == null) { 143 Logging.info(tr("No EXIF time in file \"{0}\". Using last modified date as timestamp.", fn)); 144 time = image.getLastModified(); //use lastModified time if no EXIF time present 145 } 146 image.setExifTime(time); 147 148 final Directory dir = metadata.getFirstDirectoryOfType(JpegDirectory.class); 149 final Directory dirExif = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class); 150 final GpsDirectory dirGps = metadata.getFirstDirectoryOfType(GpsDirectory.class); 151 152 try { 153 if (dirExif != null && dirExif.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) { 154 image.setExifOrientation(dirExif.getInt(ExifIFD0Directory.TAG_ORIENTATION)); 155 } 156 } catch (MetadataException ex) { 157 Logging.debug(ex); 158 } 159 160 try { 161 if (dir != null && dir.containsTag(JpegDirectory.TAG_IMAGE_WIDTH) && dir.containsTag(JpegDirectory.TAG_IMAGE_HEIGHT)) { 162 // there are cases where these do not match width and height stored in dirExif 163 image.setWidth(dir.getInt(JpegDirectory.TAG_IMAGE_WIDTH)); 164 image.setHeight(dir.getInt(JpegDirectory.TAG_IMAGE_HEIGHT)); 165 } 166 } catch (MetadataException ex) { 167 Logging.debug(ex); 168 } 169 170 if (dirGps == null || dirGps.getTagCount() <= 1) { 171 image.setExifCoor(null); 172 image.setPos(null); 173 return; 174 } 175 176 ifNotNull(ExifReader.readSpeed(dirGps), image::setSpeed); 177 ifNotNull(ExifReader.readElevation(dirGps), image::setElevation); 178 179 try { 180 image.setExifCoor(ExifReader.readLatLon(dirGps)); 181 image.setPos(image.getExifCoor()); 182 } catch (MetadataException | IndexOutOfBoundsException ex) { // (other exceptions, e.g. #5271) 183 Logging.error("Error reading EXIF from file: " + ex); 184 image.setExifCoor(null); 185 image.setPos(null); 186 } 187 188 try { 189 ifNotNull(ExifReader.readDirection(dirGps), image::setExifImgDir); 190 } catch (IndexOutOfBoundsException ex) { // (other exceptions, e.g. #5271) 191 Logging.debug(ex); 192 } 193 194 try { 195 ifNotNull(ExifReader.readGpsTrackDirection(dirGps), image::setExifGpsTrack); 196 } catch (IndexOutOfBoundsException ex) { 197 Logging.debug(ex); 198 } 199 200 try { 201 ifNotNull(ExifReader.readHpositioningError(dirGps), image::setExifHPosErr); 202 } catch (IndexOutOfBoundsException ex) { 203 Logging.debug(ex); 204 } 205 206 try { 207 ifNotNull(ExifReader.readGpsDiffMode(dirGps), image::setGpsDiffMode); 208 } catch (IndexOutOfBoundsException ex) { 209 Logging.debug(ex); 210 } 211 212 try { 213 ifNotNull(ExifReader.readGpsMeasureMode(dirGps), image::setGps2d3dMode); 214 } catch (IndexOutOfBoundsException ex) { 215 Logging.debug(ex); 216 } 217 218 try { 219 ifNotNull(ExifReader.readGpsDop(dirGps), image::setExifGpsDop); 220 } catch (IndexOutOfBoundsException ex) { 221 Logging.debug(ex); 222 } 223 224 try { 225 ifNotNull(ExifReader.readGpsDatum(dirGps), image::setExifGpsDatum); 226 } catch (IndexOutOfBoundsException ex) { 227 Logging.debug(ex); 228 } 229 230 try { 231 ifNotNull(ExifReader.readGpsProcessingMethod(dirGps), image::setExifGpsProcMethod); 232 } catch (IndexOutOfBoundsException ex) { 233 Logging.debug(ex); 234 } 235 236 ifNotNull(dirGps.getGpsDate(), d -> image.setExifGpsTime(d.toInstant())); 237 } 238 239 private static Metadata getMetadata(URI uri, InputStream inputStream) { 240 inputStream.mark(32); 241 final Exception topException; 242 final String fn = uri.toString(); 243 try { 244 // try to parse metadata according to extension 245 String ext = fn.substring(fn.lastIndexOf('.') + 1).toLowerCase(Locale.US); 246 switch (ext) { 247 case "jpg": 248 case "jpeg": 249 return JpegMetadataReader.readMetadata(inputStream); 250 case "tif": 251 case "tiff": 252 return TiffMetadataReader.readMetadata(inputStream); 253 case "png": 254 return PngMetadataReader.readMetadata(inputStream); 255 default: 256 throw new NoMetadataReaderWarning(ext); 257 } 258 } catch (JpegProcessingException | TiffProcessingException | PngProcessingException | IOException 259 | NoMetadataReaderWarning exception) { 260 //try other formats (e.g. JPEG file with .png extension) 261 topException = exception; 262 } 263 try { 264 return JpegMetadataReader.readMetadata(inputStream); 265 } catch (JpegProcessingException | IOException ex1) { 266 Logging.trace(ex1); 267 } 268 try { 269 return TiffMetadataReader.readMetadata(inputStream); 270 } catch (TiffProcessingException | IOException ex2) { 271 Logging.trace(ex2); 272 } 273 274 try { 275 return PngMetadataReader.readMetadata(inputStream); 276 } catch (PngProcessingException | IOException ex3) { 277 Logging.trace(ex3); 278 } 279 Logging.warn(topException); 280 Logging.info(tr("Can''t parse metadata for file \"{0}\". Using last modified date as timestamp.", fn)); 281 return null; 282 } 283 284 private static class NoMetadataReaderWarning extends Exception { 285 NoMetadataReaderWarning(String ext) { 286 super("No metadata reader for format *." + ext); 287 } 288 } 289 290 private static <T> void ifNotNull(T value, Consumer<T> setter) { 291 if (value != null) { 292 setter.accept(value); 293 } 294 } 295}