Search in sources :

Example 21 with Image

use of org.structr.web.entity.Image in project structr by structr.

the class ImageHelper method createThumbnail.

public static Thumbnail createThumbnail(final Image originalImage, final int maxWidth, final int maxHeight, final String formatString, final boolean crop, final Integer reqOffsetX, final Integer reqOffsetY) {
    Thumbnail.Format format = Thumbnail.defaultFormat;
    try {
        final String imageFormatString = getImageFormatString(originalImage);
        format = formatString != null ? Thumbnail.Format.valueOf(formatString) : (imageFormatString != null ? Thumbnail.Format.valueOf(imageFormatString) : Thumbnail.defaultFormat);
    } catch (IllegalArgumentException iae) {
        logger.debug("Unsupported thumbnail format - using default");
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Thumbnail tn = new Thumbnail();
    try {
        final long start = System.nanoTime();
        BufferedImage source = getRotatedImage(originalImage);
        if (source != null) {
            final int sourceWidth = source.getWidth();
            final int sourceHeight = source.getHeight();
            // Update image dimensions
            final PropertyMap properties = new PropertyMap();
            properties.put(StructrApp.key(Image.class, "width"), sourceWidth);
            properties.put(StructrApp.key(Image.class, "height"), sourceHeight);
            originalImage.setProperties(originalImage.getSecurityContext(), properties);
            // float aspectRatio = sourceWidth/sourceHeight;
            final float scale = getScaleRatio(sourceWidth, sourceHeight, maxWidth, maxHeight, crop);
            // Don't scale up
            if (scale > 1.0) {
                final int destWidth = getThumbnailWidth(sourceWidth, scale);
                final int destHeight = getThumbnailHeight(sourceHeight, scale);
                if (crop) {
                    final int offsetX = reqOffsetX != null ? reqOffsetX : Math.abs(maxWidth - destWidth) / 2;
                    final int offsetY = reqOffsetY != null ? reqOffsetY : Math.abs(maxHeight - destHeight) / 2;
                    final Integer[] dims = finalImageDimensions(offsetX, offsetY, maxWidth, maxHeight, sourceWidth, sourceHeight);
                    logger.debug("Offset and Size (x,y,w,h): {},{},{},{}", new Object[] { dims[0], dims[1], dims[2], dims[3] });
                    Thumbnails.of(source).scale(1.0f / scale).sourceRegion((int) (dims[0] * scale), (int) (dims[1] * scale), (int) (dims[2] * scale), (int) (dims[3] * scale)).outputFormat(format.name()).toOutputStream(baos);
                    tn.setWidth(dims[2]);
                    tn.setHeight(dims[3]);
                } else {
                    Thumbnails.of(source).scale(1.0f / scale).outputFormat(format.name()).toOutputStream(baos);
                    tn.setWidth(destWidth);
                    tn.setHeight(destHeight);
                }
            } else {
                // Thumbnail is source image
                ImageIO.write(source, format.name(), baos);
                tn.setWidth(sourceWidth);
                tn.setHeight(sourceHeight);
            }
        } else {
            logger.debug("Thumbnail could not be created");
            return null;
        }
        final long end = System.nanoTime();
        final long time = (end - start) / 1000000;
        logger.debug("Thumbnail created. Reading, scaling and writing took {} ms", time);
        tn.setBytes(baos.toByteArray());
        return tn;
    } catch (Throwable t) {
        logger.warn("Unable to create thumbnail for image with ID {}.", originalImage.getUuid(), t);
    }
    return null;
}
Also used : ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) BufferedImage(java.awt.image.BufferedImage) Image(org.structr.web.entity.Image) BufferedImage(java.awt.image.BufferedImage) PropertyMap(org.structr.core.property.PropertyMap)

Example 22 with Image

use of org.structr.web.entity.Image in project structr by structr.

the class ImageHelper method findAndReconnectThumbnails.

public static void findAndReconnectThumbnails(final Image originalImage) {
    final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
    final PropertyKey<Image> tnSmallKey = StructrApp.key(Image.class, "tnSmall");
    final PropertyKey<Image> tnMidKey = StructrApp.key(Image.class, "tnMid");
    final PropertyKey<String> pathKey = StructrApp.key(Image.class, "path");
    final App app = StructrApp.getInstance();
    final Integer origWidth = originalImage.getWidth();
    final Integer origHeight = originalImage.getHeight();
    if (origWidth == null || origHeight == null) {
        if (!Arrays.asList("image/svg+xml", "image/x-icon", "image/x-photoshop").contains(originalImage.getContentType())) {
            logger.info("Could not determine width and heigth for {}", originalImage.getName());
        }
        return;
    }
    for (ThumbnailProperty tnProp : new ThumbnailProperty[] { (ThumbnailProperty) tnSmallKey, (ThumbnailProperty) tnMidKey }) {
        int maxWidth = tnProp.getWidth();
        int maxHeight = tnProp.getHeight();
        boolean crop = tnProp.getCrop();
        final float scale = getScaleRatio(origWidth, origHeight, maxWidth, maxHeight, crop);
        final String tnName = ImageHelper.getThumbnailName(originalImage.getName(), getThumbnailWidth(origWidth, scale), getThumbnailHeight(origHeight, scale));
        try {
            final Image thumbnail = (Image) app.nodeQuery(Image.class).and(pathKey, PathHelper.getFolderPath(originalImage.getProperty(pathKey)) + PathHelper.PATH_SEP + tnName).getFirst();
            if (thumbnail != null) {
                app.create(originalImage, thumbnail, thumbnailRel);
            }
        } catch (FrameworkException ex) {
            logger.debug("Error reconnecting thumbnail " + tnName + " to original image " + originalImage.getName(), ex);
        }
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) ThumbnailProperty(org.structr.web.property.ThumbnailProperty) FrameworkException(org.structr.common.error.FrameworkException) BufferedImage(java.awt.image.BufferedImage) Image(org.structr.web.entity.Image) Relation(org.structr.core.entity.Relation)

Example 23 with Image

use of org.structr.web.entity.Image in project structr by structr.

the class DeployCommand method exportFileConfiguration.

private void exportFileConfiguration(final AbstractFile abstractFile, final Map<String, Object> config) {
    if (abstractFile.isVisibleToPublicUsers()) {
        putIf(config, "visibleToPublicUsers", true);
    }
    if (abstractFile.isVisibleToAuthenticatedUsers()) {
        putIf(config, "visibleToAuthenticatedUsers", true);
    }
    if (abstractFile instanceof File) {
        final File file = (File) abstractFile;
        if (file.isTemplate()) {
            putIf(config, "isTemplate", true);
        }
    }
    putIf(config, "type", abstractFile.getProperty(File.type));
    putIf(config, "contentType", abstractFile.getProperty(StructrApp.key(File.class, "contentType")));
    putIf(config, "cacheForSeconds", abstractFile.getProperty(StructrApp.key(File.class, "cacheForSeconds")));
    putIf(config, "useAsJavascriptLibrary", abstractFile.getProperty(StructrApp.key(File.class, "useAsJavascriptLibrary")));
    putIf(config, "includeInFrontendExport", abstractFile.getProperty(StructrApp.key(File.class, "includeInFrontendExport")));
    putIf(config, "basicAuthRealm", abstractFile.getProperty(StructrApp.key(File.class, "basicAuthRealm")));
    putIf(config, "enableBasicAuth", abstractFile.getProperty(StructrApp.key(File.class, "enableBasicAuth")));
    if (abstractFile instanceof Image) {
        final Image image = (Image) abstractFile;
        putIf(config, "isThumbnail", image.isThumbnail());
        putIf(config, "isImage", image.isImage());
        putIf(config, "width", image.getWidth());
        putIf(config, "height", image.getHeight());
    }
    if (abstractFile instanceof AbstractMinifiedFile) {
        if (abstractFile instanceof MinifiedCssFile) {
            final MinifiedCssFile mcf = (MinifiedCssFile) abstractFile;
            putIf(config, "lineBreak", mcf.getLineBreak());
        }
        if (abstractFile instanceof MinifiedJavaScriptFile) {
            final MinifiedJavaScriptFile mjf = (MinifiedJavaScriptFile) abstractFile;
            putIf(config, "optimizationLevel", mjf.getOptimizationLevel());
        }
        final Class<Relation> relType = StructrApp.getConfiguration().getRelationshipEntityClass("AbstractMinifiedFileMINIFICATIONFile");
        final PropertyKey<Integer> positionKey = StructrApp.key(relType, "position");
        final Map<Integer, String> minifcationSources = new TreeMap<>();
        for (Relation minificationSourceRel : AbstractMinifiedFile.getSortedRelationships((AbstractMinifiedFile) abstractFile)) {
            final File file = (File) minificationSourceRel.getTargetNode();
            minifcationSources.put(minificationSourceRel.getProperty(positionKey), file.getPath());
        }
        putIf(config, "minificationSources", minifcationSources);
    }
    // export all dynamic properties
    for (final PropertyKey key : StructrApp.getConfiguration().getPropertySet(abstractFile.getClass(), PropertyView.All)) {
        // only export dynamic (=> additional) keys
        if (!key.isPartOfBuiltInSchema()) {
            putIf(config, key.jsonName(), abstractFile.getProperty(key));
        }
    }
    exportOwnershipAndSecurity(abstractFile, config);
}
Also used : Image(org.structr.web.entity.Image) TreeMap(java.util.TreeMap) MinifiedCssFile(org.structr.web.entity.MinifiedCssFile) Relation(org.structr.core.entity.Relation) AbstractMinifiedFile(org.structr.web.entity.AbstractMinifiedFile) MinifiedJavaScriptFile(org.structr.web.entity.MinifiedJavaScriptFile) AbstractFile(org.structr.web.entity.AbstractFile) AbstractMinifiedFile(org.structr.web.entity.AbstractMinifiedFile) MinifiedCssFile(org.structr.web.entity.MinifiedCssFile) File(org.structr.web.entity.File) MinifiedJavaScriptFile(org.structr.web.entity.MinifiedJavaScriptFile) PropertyKey(org.structr.core.property.PropertyKey)

Example 24 with Image

use of org.structr.web.entity.Image in project structr by structr.

the class FileImportVisitor method createFile.

private void createFile(final Path path, final String fileName) throws IOException {
    String newFileUuid = null;
    try (final Tx tx = app.tx(true, false, false)) {
        final String fullPath = "/" + basePath.relativize(path).toString();
        final PropertyMap fileProperties = getPropertiesForFileOrFolder(fullPath);
        if (fileProperties == null) {
            if (!fileName.startsWith(".")) {
                logger.info("Ignoring {} (not in files.json)", fullPath);
            }
        } else {
            Folder parent = null;
            if (!basePath.equals(path.getParent())) {
                final String parentPath = "/" + basePath.relativize(path.getParent()).toString();
                parent = getExistingFolder(parentPath);
            }
            boolean skipFile = false;
            File file = app.nodeQuery(File.class).and(StructrApp.key(File.class, "parent"), parent).and(File.name, fileName).getFirst();
            if (file != null) {
                final Long checksumOfExistingFile = file.getChecksum();
                final Long checksumOfNewFile = FileHelper.getChecksum(path.toFile());
                if (checksumOfExistingFile != null && checksumOfNewFile != null && checksumOfExistingFile.equals(checksumOfNewFile)) {
                    skipFile = true;
                } else {
                    // remove existing file first!
                    app.delete(file);
                }
            }
            if (!skipFile) {
                logger.info("Importing {}...", fullPath);
                try (final FileInputStream fis = new FileInputStream(path.toFile())) {
                    // create file in folder structure
                    file = FileHelper.createFile(securityContext, fis, null, File.class, fileName, parent);
                    final String contentType = file.getContentType();
                    // modify file type according to content
                    if (StringUtils.startsWith(contentType, "image") || ImageHelper.isImageType(file.getProperty(name))) {
                        file.unlockSystemPropertiesOnce();
                        file.setProperties(securityContext, new PropertyMap(NodeInterface.type, Image.class.getSimpleName()));
                    }
                    newFileUuid = file.getUuid();
                }
            }
            if (file != null) {
                if (fileProperties.containsKey(StructrApp.key(AbstractMinifiedFile.class, "minificationSources"))) {
                    deferredFiles.add(file);
                } else {
                    file.unlockSystemPropertiesOnce();
                    file.setProperties(securityContext, fileProperties);
                }
            }
            if (newFileUuid != null) {
                final File createdFile = app.get(File.class, newFileUuid);
                String type = createdFile.getType();
                boolean isImage = createdFile instanceof Image;
                logger.debug("File {}: {}, isImage? {}", new Object[] { createdFile.getName(), type, isImage });
                if (isImage) {
                    try {
                        ImageHelper.updateMetadata(createdFile);
                        handleThumbnails((Image) createdFile);
                    } catch (Throwable t) {
                        logger.warn("Unable to update metadata: {}", t.getMessage());
                    }
                }
            }
        }
        tx.success();
    } catch (FrameworkException ex) {
        logger.error("Error occured while reading file properties " + fileName, ex);
    }
}
Also used : PropertyMap(org.structr.core.property.PropertyMap) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) AbstractMinifiedFile(org.structr.web.entity.AbstractMinifiedFile) Folder(org.structr.web.entity.Folder) Image(org.structr.web.entity.Image) AbstractFile(org.structr.web.entity.AbstractFile) AbstractMinifiedFile(org.structr.web.entity.AbstractMinifiedFile) File(org.structr.web.entity.File) FileInputStream(java.io.FileInputStream)

Example 25 with Image

use of org.structr.web.entity.Image in project structr by structr.

the class ListFilesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final String rawType = (String) webSocketData.getNodeData().get("type");
    final Class type = SchemaHelper.getEntityClassForRawType(rawType);
    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    final PropertyKey sortProperty = StructrApp.key(type, sortKey);
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(type).includeDeletedAndHidden().sort(sortProperty).order("desc".equals(sortOrder));
    // for image lists, suppress thumbnails
    if (type.equals(Image.class)) {
        query.and(StructrApp.key(Image.class, "isThumbnail"), false);
    }
    try {
        // do search
        List<NodeInterface> filteredResults = new LinkedList();
        List<? extends GraphObject> resultList = query.getAsList();
        // add only root folders to the list
        for (GraphObject obj : resultList) {
            if (obj instanceof AbstractFile) {
                AbstractFile node = (AbstractFile) obj;
                if (node.getParent() == null) {
                    filteredResults.add(node);
                }
            }
        }
        // save raw result count
        int resultCountBeforePaging = filteredResults.size();
        // set full result list
        webSocketData.setResult(PagingHelper.subList(filteredResults, pageSize, page));
        webSocketData.setRawResultCount(resultCountBeforePaging);
        // send only over local connection
        getWebSocket().send(webSocketData, true);
    } catch (FrameworkException fex) {
        logger.warn("", fex);
    }
}
Also used : AbstractFile(org.structr.web.entity.AbstractFile) Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) Image(org.structr.web.entity.Image) GraphObject(org.structr.core.GraphObject) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey) NodeInterface(org.structr.core.graph.NodeInterface)

Aggregations

Image (org.structr.web.entity.Image)26 FrameworkException (org.structr.common.error.FrameworkException)18 Tx (org.structr.core.graph.Tx)12 PropertyMap (org.structr.core.property.PropertyMap)12 Test (org.junit.Test)9 StructrUiTest (org.structr.web.StructrUiTest)9 BufferedImage (java.awt.image.BufferedImage)8 IOException (java.io.IOException)7 File (org.structr.web.entity.File)6 AbstractFile (org.structr.web.entity.AbstractFile)5 App (org.structr.core.app.App)4 StructrApp (org.structr.core.app.StructrApp)4 SecurityContext (org.structr.common.SecurityContext)3 Relation (org.structr.core.entity.Relation)3 PropertyKey (org.structr.core.property.PropertyKey)3 Folder (org.structr.web.entity.Folder)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 ByteArrayOutputStream (org.apache.commons.io.output.ByteArrayOutputStream)2