001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.servlet.taglib.ui;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.image.ImageBag;
019    import com.liferay.portal.kernel.image.ImageToolUtil;
020    import com.liferay.portal.kernel.json.JSONFactoryUtil;
021    import com.liferay.portal.kernel.json.JSONObject;
022    
023    import java.awt.image.RenderedImage;
024    
025    import java.io.IOException;
026    
027    /**
028     * @author Roberto D??az
029     */
030    public class ImageSelectorProcessor {
031    
032            public ImageSelectorProcessor(byte[] bytes) {
033                    _bytes = bytes;
034            }
035    
036            public byte[] cropImage(String cropRegion)
037                    throws IOException, PortalException {
038    
039                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject(cropRegion);
040    
041                    int height = jsonObject.getInt("height");
042                    int width = jsonObject.getInt("width");
043                    int x = jsonObject.getInt("x");
044                    int y = jsonObject.getInt("y");
045    
046                    if ((x > 0) || (y > 0) || (width > 0) || (height > 0)) {
047                            ImageBag imageBag = ImageToolUtil.read(_bytes);
048    
049                            RenderedImage renderedImage = imageBag.getRenderedImage();
050    
051                            renderedImage = ImageToolUtil.crop(
052                                    renderedImage, height, width, x, y);
053    
054                            return ImageToolUtil.getBytes(renderedImage, imageBag.getType());
055                    }
056    
057                    return _bytes;
058            }
059    
060            public byte[] scaleImage(int width) throws IOException {
061                    ImageBag imageBag = ImageToolUtil.read(_bytes);
062    
063                    RenderedImage renderedImage = imageBag.getRenderedImage();
064    
065                    renderedImage = ImageToolUtil.scale(renderedImage, width);
066    
067                    return ImageToolUtil.getBytes(renderedImage, imageBag.getType());
068            }
069    
070            private final byte[] _bytes;
071    
072    }