Simplify ImageData.resizeImage (FINERACT-1201)

This commit is contained in:
Michael Vorburger
2020-11-06 05:27:17 +02:00
committed by Petri Tuomola
parent 0af9aa3d0c
commit 716ba79671
5 changed files with 65 additions and 74 deletions
@@ -227,7 +227,7 @@ public class DocumentManagementApiResource {
this.context.authenticatedUser().validateHasReadPermission(this.systemEntityType); this.context.authenticatedUser().validateHasReadPermission(this.systemEntityType);
final FileData fileData = this.documentReadPlatformService.retrieveFileData(entityType, entityId, documentId); final FileData fileData = this.documentReadPlatformService.retrieveFileData(entityType, entityId, documentId);
final ResponseBuilder response = Response.ok(fileData.file()); final ResponseBuilder response = Response.ok(fileData.inputStream());
response.header("Content-Disposition", "attachment; filename=\"" + fileData.name() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + fileData.name() + "\"");
response.header("Content-Type", fileData.contentType()); response.header("Content-Type", fileData.contentType());
@@ -21,6 +21,7 @@ package org.apache.fineract.infrastructure.documentmanagement.api;
import com.sun.jersey.core.header.FormDataContentDisposition; import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataBodyPart; import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataParam; import com.sun.jersey.multipart.FormDataParam;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Base64; import java.util.Base64;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@@ -43,6 +44,7 @@ import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSer
import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils; import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils;
import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils.ImageFileExtension; import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils.ImageFileExtension;
import org.apache.fineract.infrastructure.documentmanagement.data.ImageData; import org.apache.fineract.infrastructure.documentmanagement.data.ImageData;
import org.apache.fineract.infrastructure.documentmanagement.exception.ContentManagementException;
import org.apache.fineract.infrastructure.documentmanagement.exception.InvalidEntityTypeForImageManagementException; import org.apache.fineract.infrastructure.documentmanagement.exception.InvalidEntityTypeForImageManagementException;
import org.apache.fineract.infrastructure.documentmanagement.service.ImageReadPlatformService; import org.apache.fineract.infrastructure.documentmanagement.service.ImageReadPlatformService;
import org.apache.fineract.infrastructure.documentmanagement.service.ImageWritePlatformService; import org.apache.fineract.infrastructure.documentmanagement.service.ImageWritePlatformService;
@@ -144,9 +146,14 @@ public class ImagesApiResource {
imageDataURISuffix = ContentRepositoryUtils.ImageDataURIsuffix.PNG.getValue(); imageDataURISuffix = ContentRepositoryUtils.ImageDataURIsuffix.PNG.getValue();
} }
final byte[] resizedImage = imageData.getContentOfSize(maxWidth, maxHeight); ImageData resizedImage = imageData.resize(imageData, maxWidth, maxHeight);
final String clientImageAsBase64Text = imageDataURISuffix + Base64.getMimeEncoder().encodeToString(resizedImage); try {
return Response.ok(clientImageAsBase64Text).build(); byte[] resizedImageBytes = resizedImage.getInputStream().readAllBytes();
final String clientImageAsBase64Text = imageDataURISuffix + Base64.getMimeEncoder().encodeToString(resizedImageBytes);
return Response.ok(clientImageAsBase64Text).build();
} catch (IOException e) {
throw new ContentManagementException(imageData.getEntityDisplayName(), e.getMessage(), e);
}
} }
@GET @GET
@@ -163,8 +170,8 @@ public class ImagesApiResource {
} }
final ImageData imageData = this.imageReadPlatformService.retrieveImage(entityName, entityId); final ImageData imageData = this.imageReadPlatformService.retrieveImage(entityName, entityId);
final ImageData resizedImage = imageData.resize(imageData, maxWidth, maxHeight);
final ResponseBuilder response = Response.ok(imageData.getContentOfSize(maxWidth, maxHeight)); final ResponseBuilder response = Response.ok(resizedImage.getInputStream());
final String dispositionType = "inline_octet".equals(output) ? "inline" : "attachment"; final String dispositionType = "inline_octet".equals(output) ? "inline" : "attachment";
response.header("Content-Disposition", response.header("Content-Disposition",
dispositionType + "; filename=\"" + imageData.getEntityDisplayName() + ImageFileExtension.JPEG + "\""); dispositionType + "; filename=\"" + imageData.getEntityDisplayName() + ImageFileExtension.JPEG + "\"");
@@ -56,7 +56,7 @@ public class FileData {
return this.fileName; return this.fileName;
} }
public InputStream file() { public InputStream inputStream() {
try { try {
if (this.inputStream == null) { if (this.inputStream == null) {
return new FileInputStream(this.file); return new FileInputStream(this.file);
@@ -22,17 +22,17 @@ import java.awt.Color;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.RenderingHints; import java.awt.RenderingHints;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils; import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils;
import org.apache.fineract.infrastructure.documentmanagement.contentrepository.ContentRepositoryUtils.ImageFileExtension;
import org.apache.fineract.infrastructure.documentmanagement.domain.StorageType; import org.apache.fineract.infrastructure.documentmanagement.domain.StorageType;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -54,38 +54,36 @@ public class ImageData {
this.entityDisplayName = entityDisplayName; this.entityDisplayName = entityDisplayName;
} }
private byte[] getContent() { public ImageData resize(ImageData image, Integer maxWidth, Integer maxHeight) {
try { if (maxWidth == null && maxHeight != null) {
if (this.storageType.equals(StorageType.S3) && this.inputStream != null) { return image;
return IOUtils.toByteArray(this.inputStream); }
} else if (this.storageType.equals(StorageType.FILE_SYSTEM) && this.file != null) { try (InputStream is = image.getInputStream()) {
final FileInputStream fileInputStream = new FileInputStream(this.file); InputStream resizedIS = resizeImage(image.getFileExtension(), is, maxWidth != null ? maxWidth : Integer.MAX_VALUE,
return IOUtils.toByteArray(fileInputStream); maxHeight != null ? maxHeight : Integer.MAX_VALUE);
}
ImageData resizedImage = new ImageData(image.location(), image.storageType(), image.getEntityDisplayName());
resizedImage.updateContent(resizedIS);
return resizedImage;
} catch (IOException e) { } catch (IOException e) {
LOG.error("Error occured.", e); LOG.warn("resize() failed, returning original image: {}", e.getMessage(), e);
return image;
} }
return null;
} }
private byte[] resizeImage(InputStream in, int maxWidth, int maxHeight) throws IOException { private InputStream resizeImage(ImageFileExtension fileExtension, InputStream in, int maxWidth, int maxHeight) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
resizeImage(in, out, maxWidth, maxHeight);
return out.toByteArray();
}
private void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException {
BufferedImage src = ImageIO.read(in); BufferedImage src = ImageIO.read(in);
if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) { if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) {
out.write(getContent()); in.reset();
return; return in;
} }
float widthRatio = (float) src.getWidth() / maxWidth; float widthRatio = (float) src.getWidth() / maxWidth;
float heightRatio = (float) src.getHeight() / maxHeight; float heightRatio = (float) src.getHeight() / maxHeight;
float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio; float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio;
// TODO(lindahl): Improve compressed image quality (perhaps quality // TODO(lindahl): Improve compressed image quality (perhaps quality ratio)
// ratio)
int newWidth = (int) (src.getWidth() / scaleRatio); int newWidth = (int) (src.getWidth() / scaleRatio);
int newHeight = (int) (src.getHeight() / scaleRatio); int newHeight = (int) (src.getHeight() / scaleRatio);
@@ -96,42 +94,12 @@ public class ImageData {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null); g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null);
g.dispose(); g.dispose();
ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out); ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", os);
return new ByteArrayInputStream(os.toByteArray());
} }
public byte[] getContentOfSize(Integer maxWidth, Integer maxHeight) { private void setImageFileExtension(String filename) {
if (maxWidth == null && maxHeight != null) {
return getContent();
}
byte[] out = null;
if (this.storageType.equals(StorageType.S3) && this.inputStream != null) {
try {
out = resizeImage(this.inputStream, maxWidth != null ? maxWidth : Integer.MAX_VALUE,
maxHeight != null ? maxHeight : Integer.MAX_VALUE);
} catch (IOException e) {
LOG.error("Error occured.", e);
}
} else if (this.storageType.equals(StorageType.FILE_SYSTEM) && this.file != null) {
FileInputStream fis = null;
try {
fis = new FileInputStream(this.file);
out = resizeImage(fis, maxWidth != null ? maxWidth : Integer.MAX_VALUE, maxHeight != null ? maxHeight : Integer.MAX_VALUE);
} catch (IOException ex) {
LOG.error("Error occured.", ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
LOG.error("Error occured.", ex);
}
}
}
}
return out;
}
private void setImageContentType(String filename) {
fileExtension = ContentRepositoryUtils.ImageFileExtension.JPEG; fileExtension = ContentRepositoryUtils.ImageFileExtension.JPEG;
if (StringUtils.endsWith(filename.toLowerCase(), ContentRepositoryUtils.ImageFileExtension.GIF.getValue())) { if (StringUtils.endsWith(filename.toLowerCase(), ContentRepositoryUtils.ImageFileExtension.GIF.getValue())) {
@@ -144,14 +112,33 @@ public class ImageData {
public void updateContent(final File file) { public void updateContent(final File file) {
this.file = file; this.file = file;
if (this.file != null) { if (this.file != null) {
setImageContentType(this.file.getName()); setImageFileExtension(this.file.getName());
} }
} }
public void updateContent(final InputStream objectContent) {
this.inputStream = objectContent;
}
public InputStream getInputStream() {
if (this.file != null) {
try {
return new FileInputStream(this.file);
} catch (FileNotFoundException e) {
throw new IllegalStateException("FileNotFoundException: " + file, e);
}
}
return this.inputStream;
}
public String contentType() { public String contentType() {
return ContentRepositoryUtils.ImageMIMEtype.fromFileExtension(this.fileExtension).getValue(); return ContentRepositoryUtils.ImageMIMEtype.fromFileExtension(this.fileExtension).getValue();
} }
public ContentRepositoryUtils.ImageFileExtension getFileExtension() {
return this.fileExtension;
}
public StorageType storageType() { public StorageType storageType() {
return this.storageType; return this.storageType;
} }
@@ -164,10 +151,6 @@ public class ImageData {
return this.location; return this.location;
} }
public void updateContent(final InputStream objectContent) {
this.inputStream = objectContent;
}
public String getEntityDisplayName() { public String getEntityDisplayName() {
return this.entityDisplayName; return this.entityDisplayName;
} }
@@ -86,14 +86,15 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService {
@Override @Override
public ImageData retrieveImage(String entityType, final Long entityId) { public ImageData retrieveImage(String entityType, final Long entityId) {
try { try {
Object owner; String displayName;
String displayName = null;
if (EntityTypeForImages.CLIENTS.toString().equalsIgnoreCase(entityType)) { if (EntityTypeForImages.CLIENTS.toString().equalsIgnoreCase(entityType)) {
owner = this.clientRepositoryWrapper.findOneWithNotFoundDetection(entityId); Client owner = this.clientRepositoryWrapper.findOneWithNotFoundDetection(entityId);
displayName = ((Client) owner).getDisplayName(); displayName = owner.getDisplayName();
} else if (EntityTypeForImages.STAFF.toString().equalsIgnoreCase(entityType)) { } else if (EntityTypeForImages.STAFF.toString().equalsIgnoreCase(entityType)) {
owner = this.staffRepositoryWrapper.findOneWithNotFoundDetection(entityId); Staff owner = this.staffRepositoryWrapper.findOneWithNotFoundDetection(entityId);
displayName = ((Staff) owner).displayName(); displayName = owner.displayName();
} else {
displayName = "UnknownEntityType:" + entityType;
} }
final ImageMapper imageMapper = new ImageMapper(displayName); final ImageMapper imageMapper = new ImageMapper(displayName);