星期六, 三月 13, 2004

Html Inline Image 工具(一):把Gif87a 图片转换为Ascii表示

当前网站:http://sunose.blogspot.com
目的:打开一个gif图片把16进制数字转换为ASCII表示或转为Bas64表示.为Inline Image准备数据.
------------------------------------------------------------------------
import sun.misc.*;
import java.io.*;
import java.lang.Integer;

public class InLineImageTool {
private static BASE64Encoder encoder = new BASE64Encoder();
private static BASE64Decoder decoder = new BASE64Decoder();

public InLineImageTool() {
}

public static String bytesToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
buf.append(byteToHex(data[i]).toUpperCase());
}
return (buf.toString());
}


/**
* method to convert a byte to a hex string.
*
* @param data the byte to convert
* @return String the converted byte
*/
public static String byteToHex(byte data) {
StringBuffer buf = new StringBuffer();
buf.append(toHexChar((data >>> 4) & 0x0F));//高字节充0,把高移到低字节保存
buf.append(toHexChar(data & 0x0F));//低字节转成字符
return buf.toString();
}


/**
* Convenience method to convert an int to a hex char.
*
* @param i the int to convert
* @return char the converted char
*/
public static char toHexChar(int i) {
if ((0 <= i) && (i <= 9)) {
return (char) ('0' + i);//把0-9字节转成ASCII
} else {
return (char) ('a' + (i - 10));//把a-f转成ASCII
}
}



public static void main (String[] args) throws Exception
{
if(args.length<2){System.out.println("Syntax:java InLineImageTool gifFile format(base64 or gif)");System.exit(0);}

File giffile=null;
giffile=new File(args[0]);
FileInputStream insrc=new FileInputStream(giffile);
byte[] inbyte=new byte[1];
if(args[1].equals("gif"))
{
String temp="";

for(int i=0;i<giffile.length();i++)
{
if(insrc.read(inbyte)==-1)break;
System.out.print("\\x"+byteToHex(inbyte[0]));
}
}else if(args[1].equals("base64"))//Base64 is Latin ascii string
{
byte[] fielbyte=new byte[(int)giffile.length()];//多大的文件?:)
insrc.read(fielbyte);
System.out.print(encoder.encode(fielbyte));
}else
{
System.out.println("Invalid format String:"+args[0]+" Valid is base64 or gif");
}
}
}

//另外还有一种把gif转为base64的简便方法:打开发送邮件软件:outlookexpress或Mozilla Thunderbird 新建邮件,然后保存为草稿(drafts)然后看邮件源代码:
Content-Type: image/gif;
name="1.gif"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="1.gif"
下面所附加的就是Base64编码了.