/*
 * $Id: Encoder.java,v 1.2 2006/07/17 20:22:40 larry Exp $ 
 */
package com.representqueens.spark;

/*
 * 
 * Copyright 2006 Larry Ogrodnek
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.imageio.ImageIO;

/**
 * Encodes Image data as Strings, using code from David Flanagan's
 * website (http://www.davidflanagan.com/).
 * 
 * @author David Flanagan
 * @author Larry Ogrodnek <larry@cheesesteak.net>
 * @version $Revision: 1.2 $ $Date: 2006/07/17 20:22:40 $
 */
public class Encoder
{
  public enum Format
  {
    DATA,
    JAVASCRIPT
  };


  public static String encode(final BufferedImage bi,
                              final Format format) throws IOException
  {
    try
    {
      final ByteArrayOutputStream os = new ByteArrayOutputStream();

      ImageIO.write(bi, "png", os);

      final byte[] data = os.toByteArray();

      final String rawString = new String(data, "iso8859-1");

      String encoded = URLEncoder.encode(rawString, "iso8859-1");
      encoded = encoded.replaceAll("\\+", "%20");

      if (Format.JAVASCRIPT.equals(format))
      {
        return "javascript:'" + encoded.replaceAll("%", "\\\\x") + "'";
      }

      return "data:image/png," + encoded;
    }
    catch (final UnsupportedEncodingException uee)
    {
      throw new RuntimeException(uee);
    }
  }
}
