Skip to content

Commit

Permalink
Use new image save workflow for ImagePlaceholderData
Browse files Browse the repository at this point in the history
* use `try-with` for opening images
* try to save as jpg, if that fails try to save as png
* only catch `IO-` & `NoWriterFoundException`
  in `CustomWordPlaceholderData#transform`
  • Loading branch information
AntonOellerer committed Nov 12, 2024
1 parent 7d8c75e commit 81b42e9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
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 = '5.0.0'
version = '6.0.0'

java {
toolchain {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.docutools.jocument.impl.word.placeholders;

import com.docutools.jocument.GenerationOptions;
import com.docutools.jocument.image.ImageReference;
import com.docutools.jocument.image.NoWriterFoundException;
import com.docutools.jocument.impl.word.CustomWordPlaceholderData;
import com.docutools.jocument.impl.word.ElementRemovalException;
import com.docutools.jocument.impl.word.WordImageUtils;
Expand Down Expand Up @@ -93,20 +95,29 @@ protected void transform(IBodyElement placeholder, IBody part, Locale locale, Ge
}

private Path applyOptions(GenerationOptions options) {
try {
var image = options.imageStrategy().load(imagePath);
try (var image = options.imageStrategy().load(imagePath)) {
double scale = Math.max(image.getWidth() / (double) maxWidth, image.getHeight() / (double) maxHeight);
if (scale > 1.0) {
var resized = options.imageStrategy().scale(image, 1 / scale);
image.close();
image = resized;
try (var resized = options.imageStrategy().scale(image, 1 / scale)) {
return saveImage(resized);
}
}
Path path = image.saveAsJpeg();
image.close();
return path;
} catch (Exception e) {
return saveImage(image);
} catch (IOException | NoWriterFoundException e) {
logger.error(e);
return imagePath;
}
}

private Path saveImage(ImageReference imageReference) throws IOException, NoWriterFoundException {
try {
return imageReference.saveAsJpeg();
} catch (NoWriterFoundException e) {
try {
return imageReference.saveAsPng();
} catch (NoWriterFoundException ex) {
throw new NoWriterFoundException("JPG,PNG");
}
}
}
}

0 comments on commit 81b42e9

Please sign in to comment.