Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow custom mime type determination #154

Merged
merged 2 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
}

group 'com.docutools'
version = '1.5.12'
version = '1.6.0-alpha.1'

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package com.docutools.jocument.image;

import com.docutools.jocument.impl.word.WordImageUtils;
import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import javax.imageio.ImageIO;
Expand All @@ -15,22 +15,22 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public final class DefaultImageStrategy implements ImageStrategy {
public class DefaultImageStrategy implements ImageStrategy {

private static final Logger log = LogManager.getLogger(DefaultImageStrategy.class);

private static final Object MUTEX = new Object();

//https://stackoverflow.com/a/7855774/4786733
private static volatile ImageStrategy INSTANCE;
private static volatile DefaultImageStrategy INSTANCE;

/**
* Gets the singleton instance of the defualt {@link ImageStrategy} prefered by jocument.
*
* @return the default {@link ImageStrategy}
*/
public static ImageStrategy instance() {
ImageStrategy localRef = INSTANCE;
public static DefaultImageStrategy instance() {
DefaultImageStrategy localRef = INSTANCE;
if (localRef == null) {
synchronized (MUTEX) {
localRef = INSTANCE;
Expand Down Expand Up @@ -73,7 +73,7 @@ public ImageReference scale(ImageReference original, double scaleBy) {
// https://stackoverflow.com/a/12164026/4786733
public Dimension getDimensions(Path path) throws IOException {
log.trace("Getting image dimensions of '{}'", path);
var mimeType = WordImageUtils.probeContentTypeSafely(path).orElseThrow(() -> new IOException("Could not determine File Type"));
var mimeType = getMimeType(path);
Iterator<ImageReader> iter = ImageIO.getImageReadersByMIMEType(mimeType);
while (iter.hasNext()) {
ImageReader reader = iter.next();
Expand All @@ -90,4 +90,9 @@ public Dimension getDimensions(Path path) throws IOException {
}
throw new IOException("Not a known image file: " + path.toAbsolutePath());
}

@Override
public String getMimeType(Path path) throws IOException {
return Files.probeContentType(path);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,5 @@ public interface ImageStrategy {
*/
Dimension getDimensions(Path path) throws IOException;

String getMimeType(Path path) throws IOException;
}
37 changes: 12 additions & 25 deletions src/main/java/com/docutools/jocument/impl/word/WordImageUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static XWPFPicture insertImage(XWPFParagraph paragraph, Path path, ImageS
.map(pictureDimensions -> scaleToTargetDimensions(pictureDimensions, targetDimensions))
.map(WordImageUtils::toEmu)
.orElse(DEFAULT_DIM);
var contentType = probeImageType(path);
var contentType = probeImageType(path, imageStrategy);

try (var in = Files.newInputStream(path, StandardOpenOption.READ)) {
logger.debug("Adding picture from path {} with content type {} and dimensions {} {}", path, contentType, dim.width, dim.height);
Expand Down Expand Up @@ -110,16 +110,20 @@ private static Dimension scale(Dimension dim, int maxHeight, int maxWidth) {
}

/**
* Get the XWPF integer representing the image type of the file at the provided {@link Path},
* returning `DEFAULT_XWPF_CONTENT_TYPE` if it can not be determined.
* Get the XWPF integer representing the image type of the file at the provided {@link Path}, returning `DEFAULT_XWPF_CONTENT_TYPE` if it can not be
* determined.
*
* @param path the path to the image file
* @param path the path to the image file
* @param imageStrategy the image strategy containing a file type resolving function
* @return the {@link int} representing the image type in the xwpf system.
*/
public static int probeImageType(Path path) {
return probeContentTypeSafely(path)
.map(WordImageUtils::toPoiType)
.orElse(DEFAULT_XWPF_CONTENT_TYPE);
public static int probeImageType(Path path, ImageStrategy imageStrategy) {
try {
String mimeType = imageStrategy.getMimeType(path);
return WordImageUtils.toPoiType(mimeType);
} catch (IOException e) {
return DEFAULT_XWPF_CONTENT_TYPE;
}
}

private static int toPoiType(String mimeType) {
Expand All @@ -138,21 +142,4 @@ private static int toPoiType(String mimeType) {
default -> Document.PICTURE_TYPE_JPEG;
};
}

/**
* Get the mime type of the file at the provided {@link Path}.
*
* @param path the path to the file to examine
* @return an optional containing the mime type of the file if it can be determined, or {@link Optional#empty()} if not
*/
public static Optional<String> probeContentTypeSafely(Path path) {
try {
return Optional.ofNullable(Files.probeContentType(path))
.filter(contentType -> !contentType.isBlank());
} catch (Exception e) {
logger.warn("Failed to probe content type of path %s".formatted(path), e);
return Optional.empty();
}
}

}