Input : String imgName (Image name)
Output : Image Object

This Procedure can do two things :

  1. Creating Image object from image file on file system
  2. Creating Image object from image file on http server

public static Image getImageLocation(String imgName)
{
    Image retImage = null;

    try
    {
        /*
        Assume IMAGE_DIRECTORY_URI -> image location constant on file system
        */
        String imgUri = IMAGE_DIRECTORY_URI + imgName;
        FileConnection fc =
              (FileConnection) Connector.open(imgUri, Connector.READ_WRITE);

        /* Can't find, get it from http server */
        if (!fc.exists())
        {
            System.out.println("[getImageLocation] : File not exist!");
            /*
            IMAGE_DIRECTORY_URL -> image location constant on http server
            */
            String imgUrl = IMAGE_DIRECTORY_URL + imgName;

            /*
            ConnectionUtil -> class used to handle http connection
            */
            ConnectionUtil conn = new ConnectionUtil();
            String imgResponse = conn.connect(Utilities.encodeURL(imgUrl));

            /*
            Response not OK, then return null
            */
            if (imgResponse.trim().startsWith(ConnectionUtil.ERROR_HEADER))
            {
                System.out.println("[getImageLocation] : Response not OK!");
                return retImage;
            }
            /* OK, means ready to write into file */
            /* Create file, sebagai output stream */
            fc.create();
            OutputStream outstream = fc.openOutputStream();
            /* write imgResponse.getBytes() with type byte[] to output stream */
            outstream.write(imgResponse.getBytes());
            /* create object Image from output stream */
            retImage =
                Image.createImage(
                    imgResponse.getBytes(), 0, imgResponse.getBytes().length);

            imgResponse = null;
            outstream.flush();
            outstream.close();
        }
        /* Means file exist on file system */
        else
        {
            System.out.println("[getImageLocation] : File exist!");
            /* Set file as input stream */
            DataInputStream dIStrm = fc.openDataInputStream();
            /* Create array of byte in the amount of size of file */
            byte [] imgData = new byte[(int)fc.fileSize()];
            /* Read from input stream then write into array of byte */
            dIStrm.readFully(imgData);
            /* Create object Image from array of byte */
            retImage = Image.createImage(imgData, 0, imgData.length); 

            imgData = null;
            dIStrm.close();
        }

        fc.close();
        System.gc();

    } catch (ArrayIndexOutOfBoundsException ax) {
        ax.printStackTrace();
        retImage = null;
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
        retImage = null;
    }
    return retImage;
}
Advertisements