使用java gwt生成内联图像

时间:2011-06-20 10:00:44

标签: java gwt base64 google-contacts inline-images

我正在尝试使用Java GWT编写内联映像。但是图像不显示:

<img src="data:unknown;base64,Pz9QAQSkZJRgABAQAAAQABAA9Q9AAUDBAcJCggFBQkGCAYGBggFBQUFCAgGBQYGBwUHBwUGBgUHChALBwgaCQUFDBUMDhERHxMfBxciGBYSGBAeEx4BBQUFCAcIDwgJCBIIDA4SEhISEhISEh4SEhIeEhIeHhISEh4eEhIeHh4SHh4eEhISEhISHh4eEhIeEh4eEhISHfz9ABEIAGAAYAMBIgACEQEDEQD9QAcAAACAQUBAAAAAAAAAAAAAAAAAQcCAwQGCAT9QAvEAACAQIEBAMHBQAAAAAAAAAAAQIDEQQFEiEGBzFBE1FyIjJhYnD9RRSPz9P0AGwEBAAIDAQEAAAAAAAAAAAAAAAECBAUHBgL9QAgEQEAAgEFAAMBAAAAAAAAAAAAAQIDBAUREiETMmExP0ADAMBAAIRAxEAPw9M0zKv1jbfz9bP0SUlJdkZtD0RV4JeRluEP0jP0tP0URVGNiorZSf9R9MP0dT0aVH9RznWgcfz9M379RET9Pz9GXo/EzNuW1FYUv9SXN1Wfz9Dj8/UpcHP05RjsQVM2S9XPz9Rf9Vb9Pz9SxxVL9JpDcWoNRzxuXYQXAYmFwAZV79WNiOfz9JX4vZEY8XoyPz9EnR6Lvz9X8PPz9My9vVv9P00c0lyRl8dOz9Ogr9P1GP0RBcG4YS79P07MF9dv09P1fRxwWk6R0hpLPz9XP1/Ux80cv1bf0CPz9OxH9UFwAP1qR3H9TP0CJg/Ffz9Pz9TlYVSkpxS39WL9S0T9a04cm8cZX4NSU39P0XEv0+1r9TPz9Pz9P1TTw9aEpWTv06Nfz9VP07NFn9cM3fF1eP1GAzRzP0hL0wSX9X04Jg5aZSL9P1rWr9Yv1fEi5ZOv1zMf0ND2UjJfz9Pz9HnZ9VoqFPymIPz9af1yD2QOIWJGP1ZQf1NXdmQBxXP0SUfz9P11aP0tMjv9SUpP1/Rf1BP1NTD9Yz9Pz9TT9X9HvX9XSwiT1sQT9NTT9W0zbv0mXv06P0ZP1RSfz9Rb9f0ADExgVQYAABcBDQ9cTH9Fgb9Sy79YzsPS0l8GE8gQAEAYCAYAAAAAAAAAPz9">

它告诉我,其原因是,我用base64编写错误的方法,或者字符集错误。

当返回我在网上找到的以下照片代码时,一切正常(所以不是,我的浏览器无法显示内嵌图像):

<img src="data:unknown;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==">

以下是我生成图片代码的方法。我打开一个网址并尝试对结果进行base64编码:

try {
    IoProvider.get().makeRequestAsText(url,
        new ResponseReceivedHandler<String>() {
          public void onResponseReceived(ResponseReceivedEvent<String> event) {
            final Response<String> response = event.getResponse();
            if (response.getStatusCode() == HTTP_OK){
            callback.onSuccess("data:unknown;base64,"
                + Base64.encode(response.getText()));
            }
          }
        }, options);
} catch ...

这就是我使用的base64编码器:http://snipt.net/tweakt/gwt-base64/

任何想法,为什么生成的图像无效?

编辑:

根据你的答案,我重新编写了我的代码。现在看来是这样的:

IoProvider.get().makeRequest(url,
  new ResponseReceivedHandler<Object>() {
    public void onResponseReceived(ResponseReceivedEvent<Object> event) {
      final Response<Object> response = event.getResponse();
        if (response.getStatusCode() == HTTP_OK) {

          // not working
          callback.onSuccess("data:image/jpeg;base64,"
              + Base64Utils.toBase64(response.getText().getBytes()));

          // working image
          // callback.onSuccess("data:unknown;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==");
        }
      }
}, options);

编辑后的代码生成以下代码:

<img src="data:image/jpeg;base64,77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve+/vQDvv70ABQMEBwkKCAUFCQYIBgYGCAUFBQUICAYFBgYHBQcHBQYGBQcKEAsHCBoJBQUMFQwOEREfEx8HFyIYFhIYEB4THgEFBQUIBwgPCAkIEggMDhISEhISEhISHhISEh4SEh4eEhISHh4SEh4eHhIeHh4SEhISEhIeHh4SEh4SHh4SEhIe77+977+9ABEIAGAAYAMBIgACEQEDEQHvv73vv70AHAAAAgEFAQAAAAAAAAAAAAAAAAEHAgMEBggF77+977+9AC8QAAIBAgQEAwcFAAAAAAAAAAABAgMRBAUSIQYHMUETUXIiMmFice+/ve+/vRRS77+977+977+977+977+9ABsBAQACAwEBAAAAAAAAAAAAAAABAgQFBwYD77+977+9ACARAQACAQUAAwEAAAAAAAAAAAABAgMEBRESIRMyYTHvv73vv70ADAMBAAIRAxEAPwDvv70w77+9Myvvv71jbu+/ve+/vcWt77+9Eu+/vUlJdkZtDO+/vRHvv71eyIl5GW4R77+9I++/ve+/vS3vv73vv70U77+9FUY2KitlKO+/ve+/vRDvv70x77+9HUzvv70a77+9Uu+/vUTvv73Hp++/vWgc4a+m77+977+9M3/vv71ERe+/ve+/ve+/ve+/vRl6PxMzbu+/vW1FYUzvv71Jc3Va77+977+9Dj8/77+9Slwd77+9OUY7EO+/vVM277+9L1fvv73vv73vv73vv70Y77+977+9V++/ve+/ve+/ve+/ve+/vSxx77+9U++/ve+/vdKaQ3FqDUc8bu+/vXYQXAYmFwAZ77+9X++/ve+/vWNiOu+/ve+/vSV+L2RGPO+/vXoy77+977+977+9EnR6L++/ve+/ve+/vX8P77+977+977+9My9v77+9XO+/ve+/ve+/vTRzSXJGXx0477+977+9Ogvvv73vv73vv71GP0RB1bBuGO+/vS/vv73vv73vv707MFDvv71377+9Pe+/ve+/vV/vv70ccO+/vWnnrLpHSGkt77+977+9Xe+/vX9THzRz77+9W86y77+9Au+/ve+/ve+/vTsS77+977+9QXAB77+9akdy77+9Te+/vQLvv73GmD8W77+977+977+977+977+9TlYVSkpx77+9Lu+/ve+/vWPvv71LRe+/vWjvv704cm8cZX4NSU7vv73vv73vv70XE++/vT7Oq1vvv71N77+977+977+977+977+977+977+9U++/vTw9aEpWT++/vTo277+977+9Ve+/vTs0Wu+/vXHPjtufFO+/vV7vv73vv71GAzRz77+977+9ISzvv70w77+9Ju+/vVzvv704Jg5aZSPvv73vv73vv71ry6Fr77+9Y++/vV8SLlk777+9czLvv70ND2UjJu+/ve+/ve+/ve+/ve+/vR52fe+/vVoqFe+/vcKmIe+/ve+/vWrvv71yD2QOIWJG77+977+9WULvv71N77+9d2ZAHFfvv73vv70SUu+/ve+/ve+/ve+/vXVp77+9LTI877+977+9JSnvv73vv71/Ru+/vUHvv73vv71N77+9Me+/vWDvv73vv73vv73vv73vv73vv70177+977+9cO+/vR/Dtu+/vV0sIu+/vT1s77+9Be+/vTU177+9WO+/vTNv77+9Jl/vv70677+977+9Ge+/ve+/vVFK77+977+977+9F++/vXzvv70ADExgVQYAABcBDQDvv71xMu+/vRYH77+9Sy/vv71jOw9LSXwYTyBAAQBgIBgAAAAAAAAB77+977+9">

我也试过转换字符集:

try {
  callback.onSuccess("data:image/jpeg;base64,"
    + Base64Utils.toBase64(response.getText().getBytes("ISO-8859-1")));
} catch (UnsupportedEncodingException e) { }

产生该代码:

<img src="data:image/jpeg;base64,/f39/QAQSkZJRgABAQAAAQABAAD9/QD9AAUDBAcJCggFBQkGCAYGBggFBQUFCAgGBQYGBwUHBwUGBgUHChALBwgaCQUFDBUMDhERHxMfBxciGBYSGBAeEx4BBQUFCAcIDwgJCBIIDA4SEhISEhISEh4SEhIeEhIeHhISEh4eEhIeHh4SHh4eEhISEhISHh4eEhIeEh4eEhISHv39ABEIAGAAYAMBIgACEQEDEQH9/QAcAAACAQUBAAAAAAAAAAAAAAAAAQcCAwQGCAX9/QAvEAACAQIEBAMHBQAAAAAAAAAAAQIDEQQFEiEGBzFBE1FyIjJhYnH9/RRS/f39/f0AGwEBAAIDAQEAAAAAAAAAAAAAAAECBAUHBgP9/QAgEQEAAgEFAAMBAAAAAAAAAAAAAQIDBAUREiETMmEx/f0ADAMBAAIRAxEAPwD9MP0zK/1jbv39bf0S/UlJdkZtDP0R/V4JeRluEf0j/f0t/f0U/RVGNiorZSj9/RD9Mf0dTP0a/VL9RP3n/Wgc5v39M3/9REX9/f39GXo/EzNu/W1FYUz9SXN1Wv39Dj8//UpcHf05RjsQ/VM2/S9X/f39/Rj9/Vf9/f39/Sxx/VP9/ZpDcWoNRzxu/XYQXAYmFwAZ/V/9/WNiOv39JX4vZEY8/Xoy/f39EnR6L/39/X8P/f39My9v/Vz9/f00c0lyRl8dOP39Ogv9/f1GP0RBcG4Y/S/9/f07MFD9d/09/f1f/Rxw/Wk6R0hpLf39Xf1/Ux80c/1bsv0C/f39OxL9/UFwAf1qR3L9Tf0C/Zg/Fv39/f39TlYVSkpx/S79/WP9S0X9aP04cm8cZX4NSU79/f0XE/0+q1v9Tf39/f39/f1T/Tw9aEpWT/06Nv39Vf07NFr9cc7fFP1e/f1GAzRz/f0hLP0w/Sb9XP04Jg5aZSP9/f1r4Wv9Y/1fEi5ZO/1zMv0ND2UjJv39/f39HnZ9/VoqFf2mIf39av1yD2QOIWJG/f1ZQv1N/XdmQBxX/f0SUv39/f11af0tMjz9/SUp/f1/Rv1B/f1N/TH9YP39/f39/TX9/XD9H/b9XSwi/T1s/QX9NTX9WP0zb/0mX/06/f0Z/f1RSv39/Rf9fP0ADExgVQYAABcBDQD9cTL9Fgf9Sy/9YzsPS0l8GE8gQAEAYCAYAAAAAAAAAf39">

如何将响应传递给Base64编码器,而不将其转换为String?

response.getData()是一个对象,我喜欢把它作为byte []。

7 个答案:

答案 0 :(得分:6)

约亨,

我使用不同的Base64编码库进行了大量测试:

测试代码:

public static void main(String [] args) throws IOException {
    File file = new File("./resources/so.png");
    BufferedInputStream bufRead =  new BufferedInputStream(new FileInputStream(file));
    ByteBuffer buffer = ByteBuffer.allocate(30*1024) ; // x kb
    byte[] c = new byte[1];     
    while ((bufRead.read(c))>0) { //1 byte/time to avoid buffer arithmetics 
        buffer.put(c);
    }
    byte[] data = new byte[buffer.position()];
    buffer.flip();
    buffer.get(data);
    String dataAsSt = new String(data); // transform the data to a string -- encoding error-prone
    //gwt-base64
    //String gwtBase64 = GwtBase64.encode(dataAsSt);  //doesn't work

    //google base64 impl
    String googleBase64 = Base64Utils.toBase64(data);

    //apache base64 codec
    Base64 base64codec = new Base64(-1);
    String apacheBase64 = base64codec.encodeToString(data);

    System.out.println("Google:"+googleBase64);
    System.out.println("Apache:"+apacheBase64);
    //System.out.println("GWTb64:"+gwtBase64);
}

<强>结论:

  • (gwt-base64)根本没用。它在我尝试过的每张图片上都失败了java.lang.StringIndexOutOfBoundsException: String index out of range。请注意,我注释掉了代码。

  • (google)浏览器无法理解它产生的Base64编码。

  • (apache)使用此构造函数:new Base64(-1)=没有分隔线,没有url-safe。

信用点:如果修改字符映射的最后2个字符,则可以使google实现正常工作:'$','_'变为'+','/'。

我的主要结论是您当前使用的Base64库是错误的。 我建议当你寻找替代实现时,尝试以二进制格式(byte [])保留图像和base64编码器之间的字节流。如果使用相同的编码/解码,字符串可能会起作用,但如果编码和解码在两个不同的地方(如客户端/服务器)完成,则会有风险。

祝你好运!

PS:试试这个: - )

<img src="data:unknown;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBhQRERQSDxQVFRUWGR4YGRgYFhgdFxUcHxgYGR4fIBsYGysfICEvGhgZHy8sIyswLCwsISIxNTIrNSYsLC0BCQoKDgwOGQ8NGjUjHiQ1KikzMTEwMDUvKTU1NTArNTU1NSkxNDUwKjA1MSo1LCo1NTUsMDU0LDYvKTYpNjUpLP/AABEIAEMA8AMBIgACEQEDEQH/xAAbAAEAAwEBAQEAAAAAAAAAAAAABAUGBwMIAv/EAEMQAAEDAgQDBAUICAUFAAAAAAEAAgMEEQUGEiEHEzFBUWFxFCIygZEIFiNCcqGx0TRUkpOjssHwUlOCs+EVJjNiov/EABoBAQACAwEAAAAAAAAAAAA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fep3FDhqMXjjLJBFNETpcQS0h1rg236gEH80GX+Ui53olKB7POdfz0G34uVrm+kiGV7BrdDaaFzOlg76MgjxuT8SpEXDOapwx9Fi1SZpeZrjmBc4xWaA327E/WuO4rHjgdiT2NpZsQb6I03DdUhA8oyLX99kFVTYIanKRfa7qed8rfs6tLvucT7lX0ta7HZMJw67g2CItlPda9z+7YweZK79heUoKehFBGDyuW6M36u1AhxPiSSVjeFnCV+FTzT1EkcjnMDI9Gr1Rqu4nUOps3p4oOPVmZJIcLmweS/MZV9LfVGrU3960H3r6SyVgfoVBTU9rFkY1fbPrO/+iVh8b4NGfGW14fGIDIyR8Z1ay5tr22tYlo+JXU0BERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREH/2Q=="/>

编辑:进一步研究

我花了更多时间而不是合理地寻找解决方案。 GWT包装器不允许您获取原始数据,但您可以使用JSNI强制浏览器获取二进制数据:

native String getBinaryResource(String url) /*-{
    // ...implemented with JavaScript                 
    var req = new XMLHttpRequest();
    req.open("GET", url, false);  // The last parameter determines whether the request is asynchronous -> this case is sync.
    req.overrideMimeType('text/plain; charset=x-user-defined');
    req.send(null);
    if (req.status == 200) {                    
        return req.responseText;
    } else return null
}-*/;

喜欢破解一个难题,但我已经应用了所有这些,但是,base64编码无效。 JS和Java包装器之间仍然存在编码问题,我无法将String解码回正确的byte []。尝试了所有可能的编码组合。一种可能的方法是使用本机javascript库base64 req.responseText并将String返回给java对应文件。

到目前为止您的原始问题。

现在,查看一些替代想法和问题背后的要求:在我的研究中,我已经看到Base64经常用于内联图像在服务器端以避免额外的HTTP在客户端获取图像的开销。它似乎也是CSS内联的流行替代品。

在此问题的上下文中,代码正在客户端(浏览器)上工作,并且这些原因不适用。使用基础XMLHTTPRequest获取图像二进制文件是从浏览器向服务器创建其他HTTP请求。鉴于在客户端上下文中,您显然拥有图像的URL(传递给IoProvider.get().makeRequest(*url*,...),因为如果图像对象,我们无法通过简单的动态更新让浏览器完成工作:

(这可能不是最好的代码示例,但它会为您提供图片(对不起双关语;-))

void setImage(String url) {
    final HTML imageHolder = new HTML();
    String imgTag = "<IMG src='"+url+"' />'";
    imageHolder.setHTML(imgTag);
    RootPanel.get("imageContainer").add(imageHolder); // imageContainer is a div
}

编辑:坚果破裂

最后找到了最后一个难题:如何正确解码JavaScript字符串中的二进制数据。请注意一些警告:由于它们不支持原生XMLHTTPRequest上的overrideMimeType方法,因此无法在IE上工作。

native String getBinaryResource(String url) /*-{
    var req = new XMLHttpRequest();
    req.open("GET", url, false);  // The last parameter determines whether the request is asynchronous.
    req.overrideMimeType('text/plain; charset=x-user-defined');

    req.send(null);
    if (req.status == 200) {
        return req.responseText;
    } else return null
}-*/;

private void sendRequestBinary() {
    String url = URL.encode("/Computer_File_030.gif");
    String data = getBinaryResource(url);
    if (data != null) {
        // The secret sauce: Method to decode the binary data in the response string
        byte[] binData = new byte[data.length()];
        for (int i=0;i<data.length();i++) {
            binData[i] = (byte)(data.charAt(i) & 0xff);
        }
        final HTML imageHolder = new HTML();
        String base64=Base64Utils.toBase64(binData);

        String imgTag = "<IMG src='data:image/gif;base64,"+base64+"' />'";
        imageHolder.setHTML(imgTag);
            RootPanel.get("imageContainer").add(imageHolder);
            errorLabel.setText("Base64:");
    } else {
        errorLabel.setText("Another error :-(");
    }
}

答案 1 :(得分:0)

您的图片编码字符串似乎错了,您错过了包含图片内容类型。

http://en.wikipedia.org/wiki/Data_URI_scheme

数据:[] [;字符集=] [; BASE64]

答案 2 :(得分:0)

您确定收到的图像数据是否正确?由于您要求将图像作为文本请求,因此GWT可能会在调用您的回调之前处理二进制数据(例如,转义不可打印的字符)。

答案 3 :(得分:0)

unknown不是有效的MIME类型。您的数据URI应以data:image/png或适合要显示的图像的任何内容开头。尽管MIME类型不正确,但file实用程序无法识别您发布的第一个URL中的已解码数据。它应该是什么样的文件?

答案 4 :(得分:0)

这里有一些示例代码,从我需要生成一个Captcha服务器端作为bot威慑。你似乎知道你在做什么,为了简明起见我要省略servlet设置。

无论如何,有2个地方我看错了。

1)您的response.getText()不是正确的图像编码。如果您从数据库加载或使用生成图像的工具作为Java Image类的实例,则只会出现问题。

2)你必须设置一个mime类型。数据:未知必须是有效的mimetype,例如data:image / jpeg(参考http://www.w3schools.com/media/media_mimeref.asp)如果你没有设置mimetype,浏览器必须猜测,如果猜错了,你的图像就不会显示。< / p>

我建议使用一个匹配的mime类型(jpeg,gif,png)的已建立的编解码器,假设你从一个byte []而不是一个文件加载,我还建议使用sun.misc.BASE64Encoder()。encode(byte) [])因为你可以确定它按预期工作。

客户端

ThecoderslibraryGWT.loginService.capImage( 
        new AsyncCallback<String>() {

    @Override
    public void onFailure(Throwable caught) {
        error.setHTML(caught.getMessage());
    }

    @Override
    public void onSuccess(String result) {
        String base64EncodedImage = result;             
        img.setUrl("data:image/jpg;base64," + base64EncodedImage);
        vp.setVisible(true);
    }
});

<小时/> 服务器端

/**
 * 64 Bit encoded captcha image
 */
public String capImage() {

    byte[] data = null;

    // the output stream to render the captcha image as jpeg 
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {                       
        // get the session id that will identify the generated captcha. 
        //the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = this.getThreadLocalRequest().getSession().getId();

        BufferedImage challenge = CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId, this.getThreadLocalRequest().getLocale());

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);

        jpegEncoder.encode(challenge);


        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(challenge, "jpg", os);
        data= os.toByteArray();         

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Unable to create validation image.");
    } catch (CaptchaServiceException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Unable to create validation image.");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Unable to create validation image.");
    }

    return new sun.misc.BASE64Encoder().encode(data);
}

答案 5 :(得分:0)

2个可能的原因:

1)在进入Base64.encode(response.getText())之前,读取图像并通过HTTP发送的服务器端代码正在弄乱图像的二进制格式的编码。如果你可以访问服务器端,Base64。在服务器上对你的图像进行编码,然后通过它:

callback.onSuccess("data:unknown;base64,"+ response.getText()); // response already in Base64

2)如果您无权访问服务器端,请尝试避免response.getText()调用的字符串转换。

new ResponseReceivedHandler<byte[]>() {
    public void onResponseReceived(ResponseReceivedEvent<byte[]> event) {
        final Response<byte[]> response = event.getResponse();
            if (response.getStatusCode() == HTTP_OK){
                callback.onSuccess("data:unknown;base64," + Base64.encode(**response.getData()**));
            }
        }
     }, options);
} catch ...

答案 6 :(得分:0)

为什么它值得我发布我的解决方案发送图像到服务器。它使用了我读过你无法使用的RPC调用,但也许它有帮助。

//客户端

public void onModuleLoad() {
    HTML html = new HTML(
            "<img src=\"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 vr4MkhoXe0rZigAAAABJRU5ErkJggg==\" alt=\"Red dot\">");

    RootPanel.get().add(html);

    greetingService.greetServer("", new AsyncCallback<String>() {

        @Override
        public void onSuccess(String result) {
            HTML html = new HTML(
                    "<img src=\"data:image/png;base64, "+ result + "\" alt=\"Window Logo\">");

            RootPanel.get().add(html);
            RootPanel.get().add(new Label(result));

        }

        @Override
        public void onFailure(Throwable caught) {
            // TODO Auto-generated method stub

        }
    });
}

//服务器

public String greetServer(String input)抛出IllegalArgumentException {

    // BASE64Encoder

    try{FileInputStream img = new FileInputStream(
            "C:\\icon_a.png");
    ByteArrayBuffer bab = new ByteArrayBuffer(0);
    int eof = 0;
    while (eof != -1) {
        eof = img.read();
        bab.append(eof);
    }

     String rets = new BASE64Encoder().encode(bab.toByteArray());
        return rets;

    }catch (Exception e) {
        // TODO: handle exception
    }

    return null;
}

PS:图片为http://www.drweb.de/icons/twitter/pd_twitter_iconset/pd_twitter_iconset/PNG/256/icon_a.png