001 /*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005
006 package com.kitfox.svg.xml;
007
008 import java.io.FilterOutputStream;
009 import java.io.IOException;
010 import java.io.OutputStream;
011
012 /**
013 *
014 * @author kitfox
015 */
016 public class Base64OutputStream extends FilterOutputStream
017 {
018 int buf;
019 int numBytes;
020 int numChunks;
021
022 public Base64OutputStream(OutputStream out)
023 {
024 super(out);
025 }
026
027 public void flush() throws IOException
028 {
029 out.flush();
030 }
031
032 public void close() throws IOException
033 {
034 switch (numBytes)
035 {
036 case 1:
037 buf <<= 4;
038 out.write(getBase64Byte(1));
039 out.write(getBase64Byte(0));
040 out.write('=');
041 out.write('=');
042 break;
043 case 2:
044 buf <<= 2;
045 out.write(getBase64Byte(2));
046 out.write(getBase64Byte(1));
047 out.write(getBase64Byte(0));
048 out.write('=');
049 break;
050 case 3:
051 out.write(getBase64Byte(3));
052 out.write(getBase64Byte(2));
053 out.write(getBase64Byte(1));
054 out.write(getBase64Byte(0));
055 break;
056 default:
057 assert false;
058 }
059
060 out.close();
061 }
062
063 public void write(int b) throws IOException
064 {
065 buf = (buf << 8) | (0xff & b);
066 numBytes++;
067
068 if (numBytes == 3)
069 {
070 out.write(getBase64Byte(3));
071 out.write(getBase64Byte(2));
072 out.write(getBase64Byte(1));
073 out.write(getBase64Byte(0));
074
075 numBytes = 0;
076 numChunks++;
077 if (numChunks == 16)
078 {
079 // out.write('\r');
080 // out.write('\n');
081 numChunks = 0;
082 }
083 }
084 }
085
086 public byte getBase64Byte(int index)
087 {
088 return Base64Util.encodeByte((buf >> (index * 6)) & 0x3f);
089 }
090 }