org.zodiac.netty.marshallers.ImageStreamInterpreter Maven / Gradle / Ivy
package org.zodiac.netty.marshallers;
import org.zodiac.sdk.toolkit.marshallers.Marshaller;
import org.zodiac.sdk.mime.MimeType;
import org.zodiac.sdk.toolkit.util.image.ImageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import java.awt.image.RenderedImage;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
final class ImageStreamInterpreter implements Marshaller {
public ImageStreamInterpreter() {
super();
}
@Override
public RenderedImage read(ByteBuf data, Object[] hints) throws Exception {
try (final ByteBufInputStream in = new ByteBufInputStream(data)) {
return ImageUtil.readImage(in);
}
}
@Override
public void write(RenderedImage obj, ByteBuf into, Object[] hints) throws Exception {
String format = NettyContentMarshallers.findHint(String.class, hints, null);
if (format == null) {
MimeType mimeType = NettyContentMarshallers.findHint(MimeType.class, hints, null);
if (mimeType != null && mimeType.toString().startsWith("image") && mimeType.secondaryType().isPresent()) {
format = mimeType.secondaryType().map(CharSequence::toString)
/*won't happen*/
.orElseThrow(Error::new);
List formats = Arrays.asList(ImageIO.getWriterFormatNames());
if ("jpeg".equals(format) || !formats.contains(format)) {
format = "jpg";
}
}
if (format == null) {
format = "jpg";
}
}
try (final ByteBufOutputStream out = new ByteBufOutputStream(into)) {
ImageUtil.writeImage((RenderedImage) obj, format, out);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy