imageencode.ImageEncode.java Source code

Java tutorial

Introduction

Here is the source code for imageencode.ImageEncode.java

Source

package imageencode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Element;

public class ImageEncode {

    // private static final String BASE_64_FILE_SUFFIX = ".64";
    // private static final int BLOCK_SIZE = 128;

    /**
     * A utility class to convert to and from base 64 encoding.
     * 
     * @author <a href="mailto:russgold@httpunit.org">Russell Gold</a>
     **/
    public static class Base64_ {

        final static String encodingChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        private void convert3To4(final char[] source, final int sourceIndex, final char[] target) {
            target[0] = (char) (source[sourceIndex] >>> 2);
            target[1] = (char) ((source[sourceIndex] & 0x03) << 4 | source[sourceIndex + 1] >>> 4);
            target[2] = (char) ((source[sourceIndex + 1] & 0x0f) << 2 | source[sourceIndex + 2] >>> 6);
            target[3] = (char) (source[sourceIndex + 2] & 0x3f);
        }

        private void convert4To3(final byte[] source, final byte[] target, final int targetIndex) {
            target[targetIndex] = (byte) (source[0] << 2 | source[1] >>> 4);
            target[targetIndex + 1] = (byte) ((source[1] & 0x0f) << 4 | source[2] >>> 2);
            target[targetIndex + 2] = (byte) ((source[2] & 0x03) << 6 | source[3]);
        }

        /**
         * Returns the plaintext equivalent of a base 64-encoded string.
         * 
         * @param source
         *            a base 64 string (which must have a multiple of 4
         *            characters)
         */
        public String decode(final String source) {
            if (source.length() % 4 != 0) {
                throw new RuntimeException("valid Base64 codes have a multiple of 4 characters");
            }
            final int numGroups = source.length() / 4;
            final int numExtraBytes = source.endsWith("==") ? 2 : source.endsWith("=") ? 1 : 0;
            final byte[] targetBytes = new byte[3 * numGroups];
            final byte[] sourceBytes = new byte[4];
            for (int group = 0; group < numGroups; group++) {
                for (int i = 0; i < sourceBytes.length; i++) {
                    sourceBytes[i] = (byte) Math.max(0, encodingChar.indexOf(source.charAt(4 * group + i)));
                }
                convert4To3(sourceBytes, targetBytes, group * 3);
            }
            return new String(targetBytes, 0, targetBytes.length - numExtraBytes);
        }

        /**
         * Returns the base 64 encoded equivalent of a supplied string.
         * 
         * @param source
         *            the string to encode
         */
        public String encode(final String source) {
            final char[] sourceBytes = getPaddedBytes(source);
            final int numGroups = (sourceBytes.length + 2) / 3;
            final char[] targetBytes = new char[4];
            final char[] target = new char[4 * numGroups];

            for (int group = 0; group < numGroups; group++) {
                convert3To4(sourceBytes, group * 3, targetBytes);
                for (int i = 0; i < targetBytes.length; i++) {
                    target[i + 4 * group] = encodingChar.charAt(targetBytes[i]);
                }
            }

            final int numPadBytes = sourceBytes.length - source.length();

            for (int i = target.length - numPadBytes; i < target.length; i++) {
                target[i] = '=';
            }
            return new String(target);
        }

        private char[] getPaddedBytes(final String source) {
            final char[] converted = source.toCharArray();
            final int requiredLength = 3 * ((converted.length + 2) / 3);
            final char[] result = new char[requiredLength];
            System.arraycopy(converted, 0, result, 0, converted.length);
            return result;
        }

    }

    public static byte[] getBytesFromFile(final File file) throws IOException {
        final InputStream is = new FileInputStream(file);
        // Get the size of the file
        final long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
            is.close();
            throw new IOException("File exceeds max value: " + Integer.MAX_VALUE);
        }

        // Create the byte array to hold the data
        final byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            is.close();
            throw new IOException("Could not completely read file" + file.getName());

        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

    public void decode(final String filePath, final Element node) throws IOException {
        final File imageFile = new File(filePath);
        final OutputStream os = new FileOutputStream(imageFile);
        String encodedImage = node.getTextContent();
        // String decoded = decode(encodedImage);
        // os.write(decoded);
        final Runtime runtime = Runtime.getRuntime();
        System.out.println("Free memory : " + runtime.freeMemory());
        String[] sei = encodedImage.split("\r\n");
        // System.out.println(encodedImage);
        System.out.println("Free memory : " + runtime.freeMemory());
        for (final String element : sei) {
            final byte[] byteImage = Base64.decodeBase64(element);
            try {
                os.write(byteImage);
            } catch (final FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        os.close();
        System.out.println("Free memory : " + runtime.freeMemory());
        encodedImage = null;
        sei = null;
        System.gc();
        System.out.println("Free memory : " + runtime.freeMemory());
    }

    /********************************************************************************************************************
     * $Id: Base64.java,v 1.4 2002/12/24 15:17:17 russgold Exp $
     * 
     * Copyright (c) 2000-2002 by Russell Gold
     * 
     * Permission is hereby granted, free of charge, to any person obtaining a
     * copy of this software and associated documentation files (the
     * "Software"), to deal in the Software without restriction, including
     * without limitation the rights to use, copy, modify, merge, publish,
     * distribute, sublicense, and/or sell copies of the Software, and to permit
     * persons to whom the Software is furnished to do so, subject to the
     * following conditions:
     * 
     * The above copyright notice and this permission notice shall be included
     * in all copies or substantial portions of the Software.
     * 
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
     * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
     * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
     * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
     * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
     * USE OR OTHER DEALINGS IN THE SOFTWARE.
     * 
     *******************************************************************************************************************/

    public void encode(final String filePath, final Element node) throws IOException {
        // ByteArrayOutputStream baos = null;
        try {
            final File imageFile = new File(filePath);
            final byte[] array = getBytesFromFile(imageFile);
            final String encodedImage = Base64.encodeBase64String(array);
            node.setTextContent(encodedImage); // store it inside node
        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}