Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,10 @@
public class MediaConfiguration implements Config {
private final List<MediaFormat> formats;

/**
* Image processor to use. Possible values: libvips, imagemagick, imageio.
*/
private String processor = "imageio";

private String binPath;
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,17 @@ public void initConfiguration (Configuration configuration) {
.get()).getTaxonomies()
)
);
configuration.add(
com.condation.cms.api.configuration.configs.MediaConfiguration.class,
new com.condation.cms.api.configuration.configs.MediaConfiguration(
var mediaConfig = new com.condation.cms.api.configuration.configs.MediaConfiguration(
((com.condation.cms.core.configuration.configs.MediaConfiguration) get("media")
.get()).getMediaFormats()
)
);
mediaConfig.setProcessor(((com.condation.cms.core.configuration.configs.MediaConfiguration) get("media")
.get()).getProcessor());
mediaConfig.setBinPath(((com.condation.cms.core.configuration.configs.MediaConfiguration) get("media")
.get()).getValueOrDefault("bin_path", ""));
configuration.add(
com.condation.cms.api.configuration.configs.MediaConfiguration.class,
mediaConfig
);

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,9 @@
import com.condation.cms.api.eventbus.events.ConfigurationReloadEvent;
import com.condation.cms.api.media.MediaFormat;
import com.condation.cms.api.media.MediaUtils;
import com.google.common.hash.HashCode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import lombok.Data;
Expand Down Expand Up @@ -82,6 +78,24 @@ public void reload() {
});
}

public String getProcessor() {
var processor = getSources().stream()
.filter(ConfigSource::exists)
.map(config -> config.getString("processor"))
.filter(Objects::nonNull)
.findFirst();
return processor.orElse("imageio");
}

public String getValueOrDefault(String name, String defaultValue) {
var valueGetter = getSources().stream()
.filter(ConfigSource::exists)
.map(config -> config.getString(name))
.filter(Objects::nonNull)
.findFirst();
return valueGetter.orElse(defaultValue);
}

public List<Format> getFormats() {
var sorted = new TreeSet<Format>((o1, o2) -> o1.name.compareTo(o2.name));
sorted.addAll(getList("formats", Format.class));
Expand Down
53 changes: 26 additions & 27 deletions cms-media/src/main/java/com/condation/cms/media/MediaManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import com.condation.cms.api.theme.Theme;
import com.condation.cms.api.utils.FileUtils;
import com.condation.cms.api.utils.PathUtil;
import java.io.File;
import com.condation.cms.media.processor.ImageProcessorFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
Expand All @@ -41,7 +41,6 @@
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.yaml.snakeyaml.Yaml;

/**
Expand All @@ -59,6 +58,8 @@ public abstract class MediaManager implements EventListener<ConfigurationReloadE
protected Map<String, MediaFormat> mediaFormats;
protected Path tempDirectory;

private ImageProcessorFactory processorFactory;

protected MediaManager(List<Path> assetPath, Path tempFolder, Theme theme, Configuration configuration) {
this.assetBase = assetPath;
this.tempFolder = tempFolder;
Expand Down Expand Up @@ -134,43 +135,41 @@ public Optional<byte[]> getScaledContent(final String mediaPath, final MediaForm
return tempContent;
}

Thumbnails.Builder<File> scaleBuilder = Thumbnails
.of(resolve.get().toFile())
.size(mediaFormat.width(), mediaFormat.height());

if (mediaFormat.cropped()) {
setupImageBuilder(scaleBuilder, resolve.get(), mediaFormat);
}

byte[] data = Scale.toFormat(scaleBuilder.asBufferedImage(), mediaFormat);
CropCalculator.CropArea crop = mediaFormat.cropped()
? resolveCrop(resolve.get(), mediaFormat)
: null;

writeTempContent(mediaPath, mediaFormat, data);
Path tempFile = writeTempPlaceholder(mediaPath, mediaFormat);
getProcessorFactory().get().process(resolve.get(), tempFile, mediaFormat, crop);

return Optional.of(data);
return Optional.of(Files.readAllBytes(tempFile));
}
return Optional.empty();
}

private void setupImageBuilder(Thumbnails.Builder<File> builder, Path media, MediaFormat format) {
private CropCalculator.CropArea resolveCrop(Path media, MediaFormat format) {
var metaFileName = media.getFileName().toString() + ".meta.yaml";
var metaFile = media.getParent().resolve(metaFileName);
var size = ImageSize.getSize(media);
double focal_x = 0.5;
double focal_y = 0.5;
double focalX = 0.5;
double focalY = 0.5;
if (Files.exists(metaFile)) {
try {
final Meta meta = new Yaml().loadAs(Files.readString(metaFile, StandardCharsets.UTF_8), Meta.class);
focal_x = meta.getFocalPoint_x();
focal_y = meta.getFocalPoint_y();
focalX = meta.getFocalPoint_x();
focalY = meta.getFocalPoint_y();
} catch (IOException ex) {
log.warn("Could not read meta file: {}", metaFile, ex);
}
}
CropCalculator.CropArea crop = CropCalculator.calculateCrop(
size.width(), size.height(),
focal_x, focal_y,
format.width(), format.height());
builder.sourceRegion(crop.toRectangle());
return CropCalculator.calculateCrop(size.width(), size.height(), focalX, focalY, format.width(), format.height());
}

private ImageProcessorFactory getProcessorFactory() {
if (processorFactory == null) {
processorFactory = new ImageProcessorFactory(configuration.get(MediaConfiguration.class));
}
return processorFactory;
}

public String getTempFilename(final String mediaPath, final MediaFormat mediaFormat) {
Expand All @@ -180,13 +179,10 @@ public String getTempFilename(final String mediaPath, final MediaFormat mediaFor
return tempFilename;
}

private Path writeTempContent(final String mediaPath, final MediaFormat mediaFormat, byte[] content) throws IOException {
private Path writeTempPlaceholder(final String mediaPath, final MediaFormat mediaFormat) throws IOException {
var tempFilename = getTempFilename(mediaPath, mediaFormat);

var tempFile = getTempDirectory().resolve(tempFilename);
Files.deleteIfExists(tempFile);
Files.write(tempFile, content);

return tempFile;
}

Expand Down Expand Up @@ -221,6 +217,9 @@ public void consum(ConfigurationReloadEvent event) {
return;
}
this.mediaFormats = null;
if (processorFactory != null) {
processorFactory.reset();
}
getMediaFormats();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package com.condation.cms.media.processor;

/*-
* #%L
* CMS Media
* %%
* Copyright (C) 2023 - 2026 CondationCMS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/

import com.condation.cms.api.media.MediaFormat;
import com.condation.cms.api.media.MediaUtils;
import com.condation.cms.media.CropCalculator.CropArea;
import com.luciad.imageio.webp.WebPWriteParam;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

/**
* Fallback processor using Thumbnailator + Java ImageIO.
* Always available — no external tools required.
*/
@Slf4j
public class ImageIOProcessor implements ImageProcessor {

@Override
public String name() {
return "imageio";
}

@Override
public boolean isAvailable() {
return true;
}

@Override
public void process(Path source, Path target, MediaFormat format, CropArea crop) throws IOException {
Thumbnails.Builder<File> builder = Thumbnails
.of(source.toFile())
.size(format.width(), format.height());

if (crop != null) {
builder.sourceRegion(crop.toRectangle());
}

byte[] data = toFormat(builder.asBufferedImage(), format);
Files.write(target, data);
}

private static byte[] toFormat(BufferedImage imageBuff, MediaFormat mediaFormat) throws IOException {
if (mediaFormat.format() == null) {
throw new IllegalArgumentException("unknown media format");
}
return switch (mediaFormat.format()) {
case JPEG -> toJPG(imageBuff, !mediaFormat.compression());
case WEBP -> toWEBP(imageBuff, !mediaFormat.compression());
case PNG -> toPNG(imageBuff, !mediaFormat.compression());
};
}

private static byte[] toPNG(BufferedImage imageBuff, boolean uncompressed) throws IOException {
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
if (uncompressed) {
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
try {
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if (writeParam.canWriteCompressed()) {
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(1f);
}
try (MemoryCacheImageOutputStream out = new MemoryCacheImageOutputStream(buffer)) {
writer.setOutput(out);
writer.write(null, new IIOImage(imageBuff, null, null), writeParam);
}
return buffer.toByteArray();
} finally {
writer.dispose();
}
} else {
ImageIO.write(imageBuff, "png", buffer);
return buffer.toByteArray();
}
}
}

private static byte[] toJPG(BufferedImage imageBuff, boolean uncompressed) throws IOException {
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
if (uncompressed) {
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
try (MemoryCacheImageOutputStream out = new MemoryCacheImageOutputStream(buffer)) {
writer.setOutput(out);
writer.write(null, new IIOImage(imageBuff, null, null), jpegParams);
return buffer.toByteArray();
} finally {
writer.dispose();
}
} else {
ImageIO.write(imageBuff, "jpg", buffer);
return buffer.toByteArray();
}
}
}

private static byte[] toWEBP(BufferedImage imageBuff, boolean uncompressed) throws IOException {
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
if (uncompressed) {
WebPWriteParam writeParam = new WebPWriteParam(Locale.getDefault());
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSLESS_COMPRESSION]);
ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
try (MemoryCacheImageOutputStream out = new MemoryCacheImageOutputStream(buffer)) {
writer.setOutput(out);
writer.write(null, new IIOImage(imageBuff, null, null), writeParam);
return buffer.toByteArray();
} finally {
writer.dispose();
}
} else {
ImageIO.write(imageBuff, "webp", buffer);
return buffer.toByteArray();
}
}
}
}
Loading