Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.
SOLVED

Asset Management

Avatar

Level 2

How to crop image programmatically using ImageHelper.getCropRect()? Can anyone provide me documentation or sample code for reference?

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Neha_Jadhav ,

You can try to use  ImageHelper.createLayer(dataResource) for layer creation:

Sample code you can check below:

private void cropCad(final Asset asset, final ResourceResolver resolver, final long cropValue)
            throws WorkflowException {

        if (asset == null) {
            LOG.debug("Cad asset is null");
            return;
        }

        final Resource dataResource = asset.getOriginal().getChild(JcrConstants.JCR_CONTENT);
        final Layer layer = ImageHelper.createLayer(dataResource);

        String cropRatios = StringUtils.EMPTY;

        if (asset.getMetadata() != null) {
            long heightinDec = 0L;
            long widthinDec = 0L;
            if (asset.getMetadata(DamConstants.TIFF_IMAGELENGTH) != null) {
                heightinDec = (long) asset.getMetadata(DamConstants.TIFF_IMAGELENGTH);
            }
            if (asset.getMetadata(DamConstants.TIFF_IMAGEWIDTH) != null) {
                widthinDec = (long) asset.getMetadata(DamConstants.TIFF_IMAGEWIDTH);
            }

            cropRatios = new StringBuilder(Long.toString(0L)).append(",").append(Long.toString(0L))
                    .append(",").append(Long.toString(widthinDec)).append(",")
                    .append(Long.toString(heightinDec - cropValue)).toString();
        }

        final Rectangle rect = ImageHelper.getCropRect(cropRatios, asset.getPath());
        layer.crop(rect);

        OutputStream out = null;
        InputStream in = null;
        final String mimeType = StandardImageHandler.PNG1_MIMETYPE;
        File file = null;

        try {
            final String tempFilePrefix = "cropped-" + asset.getName();

            file = File.createTempFile(tempFilePrefix, ".tmp");
            out = FileUtils.openOutputStream(file);

            layer.write(mimeType, 1.0, out);

            in = FileUtils.openInputStream(file);

            final Map<String, Object> map = new HashMap<>();
            map.put(RenditionHandler.PROPERTY_RENDITION_MIME_TYPE, mimeType);

            try {

                final Revision stateId = asset.createRevision(
                        asset.getName() + Calendar.getInstance().getTimeInMillis(), "Asset backup revision");
                asset.removeRendition("original");

                if (asset.getOriginal() != null) {
                    LOG.info("Original Not Removed2!!!");
                } else {
                    LOG.info("Original is Removed2!!!");
                }

                asset.addRendition("original", in, map);

                final Rendition croppedOriginal = asset.getOriginal();

                if (croppedOriginal != null) {

                    LOG.debug("Original Exists!!! {}", croppedOriginal.getPath());

                } else {
                    LOG.info("Cropped original unavailable. Trying to restore to the previous original. {}",
                            asset.getPath());
                    asset.restore(stateId.getId());
                    throw new WorkflowException("Error 1 occurred while cropping and setting the rendition");
                }

            } catch (final Exception e) {
                LOG.error("Error in Adding Original", e);
                throw new WorkflowException("Error 2 occurred while cropping and setting the rendition");
            }

           

        } catch (final IOException e) {

            LOG.error("Error while cropping an outfit image", e);
            throw new WorkflowException("Error 3 occurred while cropping and setting the rendition");

        } finally {

            if (null != file && !file.delete()) {
                LOG.warn("Temporary file cannot be deleted or it's null");
            }

            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

 

 

Thanks
Tarun

 

View solution in original post

3 Replies

Avatar

Community Advisor

public Layer cropImage(Asset asset, Session session, int x, int y, int width, int height) {
Rendition original = asset.getOriginal();
Layer layer = null;

if (original != null) {
try {
layer = new Layer(original.getStream());
Rectangle rect = new Rectangle(x, y, width, height);
layer.crop(rect);
} catch (Exception e) {
// handle exception
}
}

return layer;
}

 

Please replace the x, y, width, and height parameters with the actual values for your crop area.

Avatar

Correct answer by
Community Advisor

Hi @Neha_Jadhav ,

You can try to use  ImageHelper.createLayer(dataResource) for layer creation:

Sample code you can check below:

private void cropCad(final Asset asset, final ResourceResolver resolver, final long cropValue)
            throws WorkflowException {

        if (asset == null) {
            LOG.debug("Cad asset is null");
            return;
        }

        final Resource dataResource = asset.getOriginal().getChild(JcrConstants.JCR_CONTENT);
        final Layer layer = ImageHelper.createLayer(dataResource);

        String cropRatios = StringUtils.EMPTY;

        if (asset.getMetadata() != null) {
            long heightinDec = 0L;
            long widthinDec = 0L;
            if (asset.getMetadata(DamConstants.TIFF_IMAGELENGTH) != null) {
                heightinDec = (long) asset.getMetadata(DamConstants.TIFF_IMAGELENGTH);
            }
            if (asset.getMetadata(DamConstants.TIFF_IMAGEWIDTH) != null) {
                widthinDec = (long) asset.getMetadata(DamConstants.TIFF_IMAGEWIDTH);
            }

            cropRatios = new StringBuilder(Long.toString(0L)).append(",").append(Long.toString(0L))
                    .append(",").append(Long.toString(widthinDec)).append(",")
                    .append(Long.toString(heightinDec - cropValue)).toString();
        }

        final Rectangle rect = ImageHelper.getCropRect(cropRatios, asset.getPath());
        layer.crop(rect);

        OutputStream out = null;
        InputStream in = null;
        final String mimeType = StandardImageHandler.PNG1_MIMETYPE;
        File file = null;

        try {
            final String tempFilePrefix = "cropped-" + asset.getName();

            file = File.createTempFile(tempFilePrefix, ".tmp");
            out = FileUtils.openOutputStream(file);

            layer.write(mimeType, 1.0, out);

            in = FileUtils.openInputStream(file);

            final Map<String, Object> map = new HashMap<>();
            map.put(RenditionHandler.PROPERTY_RENDITION_MIME_TYPE, mimeType);

            try {

                final Revision stateId = asset.createRevision(
                        asset.getName() + Calendar.getInstance().getTimeInMillis(), "Asset backup revision");
                asset.removeRendition("original");

                if (asset.getOriginal() != null) {
                    LOG.info("Original Not Removed2!!!");
                } else {
                    LOG.info("Original is Removed2!!!");
                }

                asset.addRendition("original", in, map);

                final Rendition croppedOriginal = asset.getOriginal();

                if (croppedOriginal != null) {

                    LOG.debug("Original Exists!!! {}", croppedOriginal.getPath());

                } else {
                    LOG.info("Cropped original unavailable. Trying to restore to the previous original. {}",
                            asset.getPath());
                    asset.restore(stateId.getId());
                    throw new WorkflowException("Error 1 occurred while cropping and setting the rendition");
                }

            } catch (final Exception e) {
                LOG.error("Error in Adding Original", e);
                throw new WorkflowException("Error 2 occurred while cropping and setting the rendition");
            }

           

        } catch (final IOException e) {

            LOG.error("Error while cropping an outfit image", e);
            throw new WorkflowException("Error 3 occurred while cropping and setting the rendition");

        } finally {

            if (null != file && !file.delete()) {
                LOG.warn("Temporary file cannot be deleted or it's null");
            }

            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

 

 

Thanks
Tarun