Package net.helipilot50.stocktrade.gxt.framework.client

Source Code of net.helipilot50.stocktrade.gxt.framework.client.ImageData

/*
Copyright (c) 2003-2009 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package net.helipilot50.stocktrade.gxt.framework.client;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.log4j.Logger;

/**
* The ImageData class represents non-nullable images as portable objects. An ImageData object can represent either a monochrome or color image.
*/
public class ImageData extends DataValue
{
  private static final BufferedImage emptyImage = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);

  public enum qq_Resolver {cVALUE};

  // TF:26/03/2009:Changed this class to use ImageIcon as the underlying data representation as these images are serializable
  private ImageIcon imageIcon = new ImageIcon();
    private static final TextData textValue = new TextData("ImageData"); //$NON-NLS-1$

    public ImageData() {
    }

    public ImageData(TextData value, qq_Resolver pResolver) {
      if (pResolver == qq_Resolver.cVALUE) {
        setValue(value);
      }
    }

    /**
     * Constructor to set the Image value.  CraigM:26/09/2008.
     *
     * @param value
     * @param pResolver
     */
    public ImageData(Image value, qq_Resolver pResolver) {
      if (pResolver == qq_Resolver.cVALUE) {
        setValue(value);
      }
    }
   
    /**
     * Create a new ImageData from an ImageIcon
     * @param icon
     */
    public ImageData(ImageIcon icon){
        this();
        this.setValue(icon);
    }

    /**
     * Construct an ImageData from the information contained in the passed byte vector. The object can either be
     * a serialised ImageIcon, a serialised ImageData or a sequence of bytes that can be converted to an image
     * using the ImageIO routines.
     * @param byteImage
     */
    public ImageData(ByteVector byteImage){
        this();
        this.setValue(byteImage);
    }
   
    /**
     * Construct an ImageData from the information contained in the passed byte array. The object can either be
     * a serialised ImageIcon, a serialised ImageData or a sequence of bytes that can be converted to an image
     * using the ImageIO routines.
     * @param byteImage
     */
    public ImageData(byte[] byteImage){
        this();
        this.setValue(byteImage);
    }
   
    /**
     * Construct an ImageData that contains the value of the passed image
     * @param value
     */
    public ImageData(Image value) {
        this();
        setValue(value);
    }
   
    /**
     * Construct an ImageData that contains the value of the passed imageData
     * @param value
     */
    public ImageData(ImageData value) {
        this();
        setValue(value);
    }
   
    public ImageData(URL resource){
      this();
        if (resource != null) {
            try {
                BufferedImage image = ImageIO.read(resource);
                if (image != null) {
                    setValue(image);
                } else {
                  UsageException ue = new UsageException("unreadable image from URL " + resource);
                  ErrorMgr.addError(ue);
                  throw ue;
                }
            } catch (IOException e) {
                Logger.getLogger("task.part.logmgr").debug("IOException loading URL: " + resource);
            }
        }
        else {
            Logger.getLogger("task.part.logmgr").debug("Cannot load a null URL");
        }
    }

    /**
     * Removes the image associated with this ImageData and leaves it in a default state,
     * as if it had just been new'd
     */
    public void clear() {
      this.imageIcon = new ImageIcon();
    }
   
    /**
     * @return Returns the textValue.
     */
    public TextData getTextValue() {
        return textValue;
    }

    /**
     * @return Returns the value. This method is guaranteed to never return null
     */
    public Image getValue() {
      if (imageIcon == null || imageIcon.getImage() == null) {
        return emptyImage;
      }
        return imageIcon.getImage();
    }

    public void setValue(ImageIcon value) {
        if(value != null){
            this.hasNullValue = false;
            imageIcon = new ImageIcon(value.getImage());
        }
        else {
            this.hasNullValue = true;
            imageIcon = null;
        }
        super.reportChange();
    }
   
    /**
     * @param value The value to set.
     */
    public void setValue(Image value) {
        if(value != null){
            this.hasNullValue = false;
            imageIcon = new ImageIcon(value);
        }
        else {
            this.hasNullValue = true;
            imageIcon = null;
        }
        super.reportChange();
    }
   
    /**
     * Set the value of this image to be the same as the image passed in. Note that at the
     * moment the image is a reference to the original image -- changes to the original image
     * (but not the original image data) will be reflected in this image
     * @param value
     */
    public void setValue(ImageData value) {
      // TF:10/03/2009:Check to see if we're setting this to ourself, and bail if we are
      if (value == this) {
        return;
      }
        if (value != null) {
          if (value.isNull()) {
            if (this.isNullable()) {
              this.setIsNull(true);
            }
            else {
              data_RaiseNullAssignExcpt();
            }
          }
          else {
                if(value != null){
                    this.hasNullValue = false;
                    // TF:12/05/2010:Checked to see if there's a valid image
                    if (value.imageIcon.getImage() != null) {
                      this.imageIcon = new ImageIcon(value.imageIcon.getImage());
                    }
                    else {
                      this.imageIcon = new ImageIcon();
                    }
                }
                else{
                  this.imageIcon = null;
                    this.hasNullValue = true;
                }
                super.reportChange();

            }
        }
        else {
          data_RaiseInvalidMethodExcpt();
        }
    }
   
    /**
     * Set the value of this image to be the image represented in the passed DataValue. This is
     * overridden from the superclass to ensure correct runtime behaviour when called as:
     * <code> setValue((DataValue)myArg)</code>
     * and myArg really is an ImageData
     * @param value
     */
    @Override
    public void setValue(DataValue source) {
      if (source instanceof ImageData) {
        this.setValue((ImageData)source);
      }
      else {
        super.setValue(source);
      }
    }
   
    /**
     * Set the value of this image to be the image represented in the passed BinaryData
     * @param value
     */
    public void setValue(BinaryData value) {
        if (value != null) {
            this.setValue(value.getValue());
        }
        else {
          data_RaiseNilOperandExcpt();
        }
    }

    public void setValue(byte[] value) {
      // TF:10/03/2009:Changed this to re-use existing byte value as this will never be null now
        if(value != null){
          this.imageIcon = readFromByteArray(value, value.length);
          this.hasNullValue = (imageIcon == null);
        }
        else {
          this.imageIcon = null;
            this.hasNullValue = true;
        }
        super.reportChange();
    }

    public void setValue(ByteVector value) {
        if(value != null){
            this.imageIcon = readFromByteArray(value.getByteArray(), value.length());
          this.hasNullValue = (imageIcon == null);
        }
        else{
            this.hasNullValue = true;
            this.imageIcon = null;
        }
        super.reportChange();
    }
   
    protected static String guessImageFormat(byte[] image){
        String tempFormat = ""; //$NON-NLS-1$
        String image_format="";   //$NON-NLS-1$
        if (image.length >= 4) {
            try{
                tempFormat=tempFormat.concat(""+(char)image[0] + (char)image[1] + (char)image[2] + (char)image[3]); //$NON-NLS-1$
                if(tempFormat.substring(0,2).equalsIgnoreCase("BM"))
                  image_format ="BM"; //$NON-NLS-1$ //$NON-NLS-2$
                // CraigM: 19/07/2007 - Added PNG check
                else if (tempFormat.substring(0,3).equalsIgnoreCase("PNG"))
                  image_format ="PNG"; //$NON-NLS-1$ //$NON-NLS-2$
                else if (tempFormat.substring(0,3).equalsIgnoreCase("GIF"))
                  image_format ="GIF"; //$NON-NLS-1$ //$NON-NLS-2$
                else if (tempFormat.substring(0,3).equalsIgnoreCase("qq"))
                  image_format ="qq"; //$NON-NLS-1$ //$NON-NLS-2$
                else   image_format ="JPEG"; //$NON-NLS-1$
                Logger.getLogger("task.part.logmgr").debug(Messages.getString("ImageData.15")+image_format ); //$NON-NLS-1$ //$NON-NLS-2$
                //else  throw new UsageException("Invalid Image format");
            }catch (ArrayIndexOutOfBoundsException e) {
                throw new UsageException(Messages.getString("ImageData.16"),e); //$NON-NLS-1$
            }
        }
        return image_format;
    }

    public  void readFromFile(TextData file) {
        readFromFile(file.asString());
    }

    public  void readFromFile(String file) {
        readFromFile(new java.io.File(file));
    }

    public void readFromFile(String file, int pFormat) {
        // Note that in Java we don't need to use the file format, the ImageIO APIs will work it out for us
      java.io.File f = new java.io.File(file);
      readFromFile(f);
    }

    public void readFromFile(TextData file, int pFormat) {
        this.readFromFile(file.toString(), pFormat);
    }

    /**
     * Read the contents of the specified file into this ImageData
     * @param file
     */
    public void readFromFile(java.io.File file) {
        try {
            BufferedImage bi = ImageIO.read(file);
            this.setValue(bi);
        } catch (IOException e) {
            FileResourceException errorVar = new FileResourceException(e);
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
    }
   
    public void readFromFile(File file) {
        readFromFile(file.getNativeFile());
    }

    public void readFromFile(File file, int pFormat) {
      readFromFile(file.getNativeFile());
    }
   
    /**
     * Read the value of the memory stream as an ImageData. Note that this reads the whole memory stream, not from the current offset.
     * @param stream
     */
    public void readFromFile(MemoryStream stream) {
      // TF:10/03/2009:Changed this to re-use existing byte value as this will never be null now
      byte[] bytes = stream.toByteArray();
      this.imageIcon = readFromByteArray(bytes, bytes.length);
      this.hasNullValue = (imageIcon == null);
        super.reportChange();
    }
   
    /**
     * Read an image from the passed array of bytes, allowing to read up to length bytes. This method will be able to extract the
     * following sort of images from a byte array:
     * <ul>
     *   <li>A serialized ImageData</li>
     *   <li>A serialised ImageIcon</li>
     *   <li>An image that can be converted from bytes into an image using the ImageIO.read() library</li>
     * </ul>
     * @param bytes
     * @param length
     * @return
     */
    private static ImageIcon readFromByteArray(byte[] bytes, int length) {
      ByteArrayInputStream bis = new ByteArrayInputStream(bytes, 0, length);
      try {
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object o = ois.readObject();
        if (o instanceof ImageData) {
          return ((ImageData)o).imageIcon;
        }
        else if (o instanceof ImageIcon) {
          return (ImageIcon)o;
        }
      }
      catch (IOException ioe) {
        // This was probably an invalid object stream, possibly because we're reading from a file.
        // Just fall through and try to do it as a file
      }
      catch (ClassNotFoundException cnfe) {
        // This was probably an invalid object stream, possibly because we're reading from a file.
        // Just fall through and try to do it as a file
      }
      try {
          ImageIcon result = new ImageIcon(bytes);
          if (result != null && result.getImage() != null && result.getIconHeight() > 0 && result.getIconWidth() > 0){
            return result;
          }
        bis.reset();
      Image i = ImageIO.read(bis);
      if (i != null) {
        return new ImageIcon(i);
      }
    } catch (IOException e) {
      // Fall through to the exception thrower
    }
    finally {
      try {
        bis.close();
      }
      catch (IOException e) {}
    }
    UsageException ue = new UsageException("Invalid attempt to convert a byte array to an image.");
    ErrorMgr.addError(ue);
    throw ue;
    }

    //TF:Mar 19, 2010: use CloneHelper instead

//    public Object clone() {
//        ImageData result = new ImageData();
//        this.duplicateIntoTarget(result, false);
//        return result;
//    }
//
//    public Object clone(boolean pDeep) {
//        ImageData result = new ImageData();
//        this.duplicateIntoTarget(result, pDeep);
//        return result;
//    }

    public void duplicateIntoTarget(ImageData pData, boolean pDeep) {
        super.duplicateIntoTarget(pData, pDeep);
        // TF:12/05/2010:Corrected this method
        if (this.imageIcon.getImage() == null) {
          pData.imageIcon = new ImageIcon();
        }
        else {
          pData.imageIcon = new ImageIcon(this.imageIcon.getImage());
        }
        pData.hasNullValue = this.hasNullValue;
    }
   
    public ImageIcon asIconImage(){
        ImageIcon ii = new ImageIcon(getValue());
        return ii;
    }

    public ImageIcon asScaledIconImage(int width, int height){
        ImageIcon ii = new ImageIcon(getValue().getScaledInstance(width, height, Image.SCALE_SMOOTH));
        return ii;
    }

    public static byte[] imageToByteArray(Image image, String formatName) {
        if (image instanceof RenderedImage == false)
            image = getBufferedImage(image, Transparency.OPAQUE);

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        try {
          ImageIO.write((RenderedImage) image, formatName, byteOS);
        } catch (IOException e) {
          return null;
        }

        return byteOS.toByteArray();
    }

    public BufferedImage getBufferedImage(int transparency) {
        return getBufferedImage(this.getValue(), transparency);
    }

    public BufferedImage getBufferedImage() {
        return getBufferedImage(this.getValue(), Transparency.OPAQUE);
    }

    public static BufferedImage getBufferedImage(Image image, int transparency)
    {
        if (image instanceof BufferedImage)
        return (BufferedImage) image;

        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
        // BufferedImage bufferedImage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        BufferedImage bufferedImage = gc.createCompatibleImage(100, 80, transparency);


        Graphics g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bufferedImage;
    }
   
    public void propertyChange(PropertyChangeEvent arg0) {
      // -----------------------------------------------------------------------
      // TF:29/01/2010:JCT-640:Changed this to invoke a method on the superclass
      // -----------------------------------------------------------------------
        this.firePropertyChange("VALUE", null, this.getValue()); //$NON-NLS-1$
    }

    /**
     * Compares the value attribute of the object specified in the source parameter with the value
     * of this object and returns an integer indicating their relative magnitude
     * (equals, less than, and so on). If the convert parameter is TRUE, the method
     * converts source to a DataValue object if necessary and then does the comparison.
     */
    public int compareValue(DataValue source, boolean convert, boolean ignoreCase) {
        if (source == null) {
            return Constants.DV_CMP_NIL;
        }
        else if (this.isNull() || source.isNull()) {
            return Constants.DV_CMP_NULL;
        }
        else if (source instanceof ImageData) {
            Image thisValue = this.getValue();
            Image otherValue = ((ImageData)source).getValue();
            if (thisValue.equals(otherValue))
                return Constants.DV_CMP_EQ;
            else
                return Constants.DV_CMP_NE;
        }
        else
            return Constants.DV_CMP_UNCONVERTIBLE;
    }

    public int dataType() {
        return Constants.DV_DT_IMAGE;
    }

    public void decodeValue(TextData text, DataFormat format) {
    }

  /**
   * Set the of the image data from the passed string. This method will always throw a UsageException, as this is an unsupported operation
   */
  @Override
  public void setValue(TextData source) {
    UsageException err = new UsageException("Attempt to use method that is invalid for ImageData object.");
    err.setReasonCode(Constants.SP_ER_INVALIDSTATE);
    ErrorMgr.addError(err);
    throw err;
  }

  /**
   * Set the of the image data from the passed string. This method will always throw a UsageException, as this is an unsupported operation
   */
  @Override
  public void setValue(String source) {
    UsageException err = new UsageException("Attempt to use method that is invalid for ImageData object.");
    err.setReasonCode(Constants.SP_ER_INVALIDSTATE);
    ErrorMgr.addError(err);
    throw err;
  }
 
  @Override
  public boolean equals(Object obj) {
    // TF:24/02/2009:Added type test for safety
    if (obj instanceof ImageData) {
      // AD:12/6/2008 Changed image icon compare where instances where compared in the past.
      ImageData newImage = (ImageData)obj;
      return (this.compareValue(newImage) == Constants.DV_CMP_EQ);
    }
    return false;
  }
 
  @Override
  public int hashCode() {
    // TF:24/02/2009:Override the hashCode functionality since we override the equals functionality
    // NB: this.getValue() cannot return null
    return this.getValue().hashCode();
  }

  @Override
    public boolean isNullable() {
        return false;
    }
}
TOP

Related Classes of net.helipilot50.stocktrade.gxt.framework.client.ImageData

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.