util.StreamBlobUtil.java Source code

Java tutorial

Introduction

Here is the source code for util.StreamBlobUtil.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package util;

import util.WebUtil;
import util.GlobalConst;
import util.ExpiringObjectPool;
import model.Photo;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.awt.Dimension;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * image magic includes
 */
import magick.ImageInfo;
import magick.MagickImage;
import magick.MagickException;

/**
 *
 * @author Smitha Gudur (smitha@redbasinnetworks.com)
 * @version $Revision: 1.1 $
 */
public class StreamBlobUtil {

    /** Logger for this class and subclasses */
    protected static final Log logger = LogFactory.getLog("util.StreamBlobUtil");
    protected ExpiringObjectPool eop;
    private volatile ImageInfo info = null;
    private volatile MagickImage image = null;
    protected ImgUtil imageHelper = new ImgJaiTool();

    static {
        System.setProperty("com.sun.media.jai.disableMediaLib", "true");
    }

    /**
    * Returns scaled blob
    * @param b byte stream
    * @return scaled byte stream
    */
    /*
       public synchronized byte[] streamBlob(byte[] b) throws BasicObjException {
       if (b == null) {
          return null;
       }
    try {
           System.setProperty("jmagick.systemclassloader", "no");
        ImageInfo info = new ImageInfo();
           if (info != null) {
           MagickImage image = new MagickImage(info, b);
      if (image != null) { 
              Dimension d = image.getDimension();
              d = WebUtil.getDimension(d, GlobalConst.pWidth, GlobalConst.pHeight);
         if (d != null) {
                 MagickImage scaled = image.scaleImg((int)d.getWidth(), (int)d.getHeight());
            if (scaled != null) {
                    return (scaled.imageToBlob(info));
       }
         }
      }
           }
           } catch (Exception e) {
      throw new BasicObjException("Error writing image stream ", e);
           }
           return null;
       } 
    */

    /**
    * Returns scaled blob
    * @param b byte stream
    * @param width width of the image
    * @param height height of the image
    * @param scale boolean yes or no
    * @return scaled byte stream
    */
    public synchronized byte[] newStreamBlob(byte[] b, int width, int height, boolean doIScale)
            throws BasicObjException {

        logger.info("entered 1 streamBlob");
        if (b == null) {
            return null;
        }
        logger.info("entered 2 streamBlob");
        try {
            initializeImageInfo();
            logger.info("completed new ImageInfo()");
            if (info != null) {
                logger.info("info != null");
                //MagickImage image = new MagickImage(info, b);
                logger.info("completed new MagickImage() in streamBlob");
                if (image != null) {
                    image.blobToImage(info, b);
                    MagickImage scaled = null;
                    if (doIScale) {
                        // scale the image
                        Dimension d = image.getDimension();
                        logger.info("completed new getDimension() in streamBlob");
                        d = WebUtil.getDimension(d, width, height);
                        logger.info("completed getDimension() in streamBlob");
                        if (d != null) {
                            scaled = image.scaleImage((int) d.getWidth(), (int) d.getHeight());
                        }
                    } else {
                        // don't scale the image
                        scaled = image.scaleImage(width, height);
                    }
                    if (scaled != null) {
                        logger.info("completing 4 streamBlob");
                        return (scaled.imageToBlob(info));
                    }
                }
            }
        } catch (Exception e) {
            throw new BasicObjException("Error writing image stream ", e);
        }
        logger.info("returning null in streamBlob");
        return null;
    }

    public synchronized byte[] streamBlob(byte[] img, int scaledWidth, int scaledHeight, boolean doIScale)
            throws BasicObjException {
        //some parameters
        String type = "jpeg";
        int quality = 90;
        //jai operations
        ImgMetadata data = null;
        ImgMetadata scaled = null;
        try {
            if (img == null) {
                throw new BasicObjException("Byte array img[] passed to streamBlob is null");
            }
            data = imageHelper.makeImg(img);
            scaled = imageHelper.scaleImg(data, scaledWidth, scaledHeight);
        } catch (Exception e) {
            throw new BasicObjException("Some JAI scaling error occurred.", e);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        scaled.writeTo(os, type, quality); //calls JAI.create("encode", result, fos, type, null);
        return os.toByteArray();
    }

    public HttpServletResponse setHeader(HttpServletResponse response, Photo photo, String btitle) {

        if (photo == null || response == null) {
            return response;
        }

        int maxAge = 2592000;
        response.setContentType(photo.getValue(DbConstants.MIMETYPE));
        response.setHeader("Content-Disposition", "attachment; filename=" + btitle);
        response.setHeader("Cache-Control", "max-age=" + maxAge);
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Connection", "Keep-Alive");
        response.setHeader("Keep-Alive", "timeout=15, max=100");
        return response;
    }

    public Photo setPhoto(Photo photo, byte[] blob) {
        if (photo == null || blob == null) {
            return null;
        }
        Photo sPhoto = (Photo) eop.newObject(DbConstants.PHOTO);
        sPhoto.setValue(DbConstants.MIMETYPE, photo.getValue(DbConstants.MIMETYPE));
        sPhoto.setValue(DbConstants.BTITLE, photo.getValue(DbConstants.BTITLE));
        sPhoto.setBlob(blob);
        return sPhoto;
    }

    public synchronized void initializeImageInfo() throws BasicObjException {
        logger.info("entered initializeImageInfo");
        System.setProperty("jmagick.systemclassloader", "no");
        try {
            if (info == null) {
                logger.info("allocate new ImageInfo()");
                info = new ImageInfo();
                logger.info("completed allocating new ImageInfo()");
            }
            if (image == null) {
                logger.info("allocating new MagickImage()");
                image = new MagickImage();
                logger.info("completed allocating new MagickImage()");
            }
        } catch (Exception e) {
            throw new BasicObjException("Error creating new ImageInfo()", e);
        }
        logger.info("completed initializeImageInfo");
    }

    /**
     *  This method is called by spring.
     * @param eop
     */
    public void setEop(ExpiringObjectPool eop) {
        this.eop = eop;
    }

}