use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.
the class MetadatenImagesHelper method scaleFile.
/**
* scale given image file to png using internal embedded content server
*
* @throws ImageManagerException
* @throws IOException
* @throws ImageManipulatorException
*/
public void scaleFile(String inFileName, String outFileName, int inSize, int intRotation) throws ContentLibException, IOException, ImageManipulatorException {
ConfigurationHelper conf = ConfigurationHelper.getInstance();
Path inPath = Paths.get(inFileName);
URI s3URI = null;
try {
s3URI = new URI("s3://" + conf.getS3Bucket() + "/" + S3FileUtils.path2Key(inPath));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
log.error(e);
}
log.trace("start scaleFile");
int tmpSize = inSize;
if (tmpSize < 1) {
tmpSize = 1;
}
log.trace("Scale to " + tmpSize + "%");
if (ConfigurationHelper.getInstance().getContentServerUrl() == null) {
log.trace("api");
ImageManager im = null;
JpegInterpreter pi = null;
try {
im = conf.useS3() ? new ImageManager(s3URI) : new ImageManager(inPath.toUri());
// im = new ImageManager(Paths.get(inFileName).toUri());
log.trace("im");
ImageInterpreter ii = im.getMyInterpreter();
Dimension inputResolution = new Dimension((int) ii.getXResolution(), (int) ii.getYResolution());
log.trace("input resolution: " + inputResolution.width + "x" + inputResolution.height + "dpi");
Dimension outputResolution = new Dimension(144, 144);
log.trace("output resolution: " + outputResolution.width + "x" + outputResolution.height + "dpi");
Dimension dim = new Dimension(tmpSize * outputResolution.width / inputResolution.width, tmpSize * outputResolution.height / inputResolution.height);
log.trace("Absolute scale: " + dim.width + "x" + dim.height + "%");
RenderedImage ri = im.scaleImageByPixel(dim, ImageManager.SCALE_BY_PERCENT, intRotation);
log.trace("ri");
pi = new JpegInterpreter(ri);
log.trace("pi");
pi.setXResolution(outputResolution.width);
log.trace("xres = " + pi.getXResolution());
pi.setYResolution(outputResolution.height);
log.trace("yres = " + pi.getYResolution());
FileOutputStream outputFileStream = new FileOutputStream(outFileName);
log.trace("output");
pi.writeToStream(null, outputFileStream);
log.trace("write stream");
outputFileStream.close();
log.trace("close stream");
} finally {
if (im != null) {
im.close();
}
if (pi != null) {
pi.close();
}
}
} else {
String imageURIString = conf.useS3() ? s3URI.toString() : inFileName;
String cs = conf.getContentServerUrl() + imageURIString + "&scale=" + tmpSize + "&rotate=" + intRotation + "&format=jpg";
cs = cs.replace("\\", "/");
log.trace("url: " + cs);
URL csUrl = new URL(cs);
CloseableHttpClient httpclient = null;
HttpGet method = null;
InputStream istr = null;
OutputStream fos = null;
try {
httpclient = HttpClientBuilder.create().build();
method = new HttpGet(csUrl.toString());
log.trace("get");
Integer contentServerTimeOut = ConfigurationHelper.getInstance().getGoobiContentServerTimeOut();
Builder builder = RequestConfig.custom();
builder.setSocketTimeout(contentServerTimeOut);
RequestConfig rc = builder.build();
method.setConfig(rc);
byte[] response = httpclient.execute(method, HttpClientHelper.byteArrayResponseHandler);
if (response == null) {
log.error("Response stream is null");
return;
}
istr = new ByteArrayInputStream(response);
fos = new FileOutputStream(outFileName);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = istr.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
log.error("Unable to connect to url " + cs, e);
return;
} finally {
method.releaseConnection();
if (httpclient != null) {
httpclient.close();
}
if (istr != null) {
try {
istr.close();
} catch (IOException e) {
log.error(e);
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
}
use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.
the class GoobiImageResource method getImageSize.
private Dimension getImageSize(String uri) {
Dimension size = IMAGE_SIZES.get(uri);
if (size == null) {
try (ImageManager manager = new ImageManager(URI.create(uri))) {
size = new Dimension(manager.getMyInterpreter().getOriginalImageWidth(), manager.getMyInterpreter().getOriginalImageHeight());
setImageSize(uri, size);
} catch (ContentLibException e) {
log.error("Error retrieving image size of " + uri);
} catch (FileNotFoundException e1) {
log.error("Error retrieving image size of " + uri + ". Reason: url could not be resolved");
}
}
return size;
}
use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.
the class GoobiImageResource method createGoobiImageURI.
private URI createGoobiImageURI(HttpServletRequest request, Path processFolder, String folder, String filename) throws ContentLibException {
try {
this.imageFolder = getImagesFolder(processFolder, folder);
Path imagePath = imageFolder.resolve(filename);
this.thumbnailFolder = processFolder.resolve("thumbs");
// replace image Path with thumbnail path if image file does not exist
if (!Files.exists(imagePath) && hasThumbnailDirectories(imageFolder, thumbnailFolder)) {
imagePath = getThumbnailPath(imagePath, thumbnailFolder, Optional.empty(), true).orElse(imagePath);
}
URI originalImageURI = Image.toURI(imagePath);
Optional<Dimension> requestedImageSize = getRequestedImageSize(request);
if (requestedImageSize.isPresent()) {
// actual image request, no info.json
boolean imageTooLarge = isFileTooLarge(imagePath);
Dimension imageSize = getImageSize(originalImageURI.toString());
if (!imageTooLarge) {
int maxImageSize = ConfigurationHelper.getInstance().getMaximalImageSize();
imageTooLarge = maxImageSize > 0 && Math.max(imageSize.getWidth(), imageSize.getHeight()) > maxImageSize;
}
Optional<Dimension> requestedRegionSize = getRequestedRegionSize(request);
requestedImageSize = completeRequestedSize(requestedImageSize, requestedRegionSize, imageSize);
if (hasThumbnailDirectories(imageFolder, thumbnailFolder)) {
// requested image if the entire image were requested
if (requestedImageSize.isPresent() && requestedRegionSize.isPresent()) {
double regionScaleW = requestedImageSize.get().getWidth() / requestedRegionSize.get().getWidth();
double regionScaleH = requestedImageSize.get().getHeight() / requestedRegionSize.get().getHeight();
requestedImageSize = Optional.of(new Dimension((int) Math.round(regionScaleW * imageSize.getWidth()), (int) Math.round(regionScaleH * imageSize.getHeight())));
}
// set the path of the thumbnail/image to use
imagePath = getThumbnailPath(imagePath, thumbnailFolder, requestedImageSize, imageTooLarge).orElse(imagePath);
// add an attribute to the request on how to scale the requested region to its
// size on the original image
Dimension size = requestedImageSize.orElse(null);
getThumbnailSize(imagePath.getParent().getFileName().toString()).map(sizeString -> calcThumbnailScale(imageSize, sizeString, size, requestedRegionSize.isPresent())).ifPresent(scale -> setThumbnailScale(scale, request));
log.debug("Using thumbnail {} for image width {} and region width {}", imagePath, requestedImageSize.map(Object::toString).orElse("max"), requestedRegionSize.map(Dimension::getWidth).map(Object::toString).orElse("full"));
} else if (imageTooLarge) {
// image too large for display and no thumbnails available
throw new ContentLibException("Image size is larger than the allowed maximal size. Please consider using a compressed derivate or generating thumbnails for these images.");
} else {
// ignore thumbnail folder for this request
this.thumbnailFolder = null;
}
} else {
// info request
}
return Image.toURI(imagePath);
} catch (NumberFormatException | NullPointerException e) {
throw new ContentNotFoundException("No process found with id " + processFolder.getFileName().toString(), e);
} catch (IOException | InterruptedException | SwapException | DAOException | ContentLibException e) {
throw new ContentNotFoundException("Error initializing image resource for " + processFolder.getFileName().toString() + ". Reason: " + e.getMessage(), e);
}
}
use of de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException in project goobi-workflow by intranda.
the class AutomaticThumbnailHandler method generateThumbnailsFromDirectory.
private void generateThumbnailsFromDirectory(Process process, String imageDirectory, int[] sizes, String command) throws SwapException, DAOException, ContentLibException {
try {
File[] fileList = new File(imageDirectory).listFiles();
for (int size : sizes) {
String thumbnailDirectory = process.getThumbsDirectory() + Paths.get(imageDirectory).getFileName().toString() + "_" + String.valueOf(size);
File outputDirectory = new File(thumbnailDirectory);
if (outputDirectory.exists()) {
if (!checkIfChanged(outputDirectory, fileList)) {
return;
}
} else {
outputDirectory.mkdirs();
}
Scale scale = new Scale.ScaleToBox(new Dimension(size, size));
for (File img : fileList) {
if (img.isDirectory()) {
continue;
}
String basename = FilenameUtils.getBaseName(img.toString());
OutputStream out = new FileOutputStream(thumbnailDirectory + FileSystems.getDefault().getSeparator() + basename + "_" + size + ".jpg");
// remove spaces from url
ImageRequest request = new ImageRequest(new URI(img.getAbsolutePath().replace(" ", "%20")), RegionRequest.FULL, scale, Rotation.NONE, Colortype.DEFAULT, ImageFileFormat.JPG, Map.of("ignoreWatermark", "true"));
new GetImageAction().writeImage(request, out);
}
}
} catch (Exception e) {
log.error(e);
}
}
Aggregations