无法在GWT中转换Base64 jpg

时间:2013-06-09 23:13:23

标签: jquery ajax image google-app-engine gwt

我无法以jpg格式转换URI编码图像(png工作正常)。我的客户端是一个简单的jquery ajax帖子。在服务器上,我只是尝试解码图像,调整大小,并将其添加到blobstore。我正在学习JQuery,所以如果问题是在客户端,请为我愚​​蠢。谢谢。

客户:

function send(target){

                var sendInfo = { 
                            team: localStorage.getItem("teamName"),
                            name: target,
                            imagedata: image
                        };


                $.mobile.loading( 'show', {
                    textVisible: false,
                    theme: 'z',
                    html: ""
                });

                $.ajax({
                    type: "POST",
                    url: "/UploadImage",
                    data: sendInfo
                    }).done(function(data) {
                        $.mobile.loading('hide');
                    })
                    .fail(function(data) {
                        $.mobile.loading('hide');
                });

服务器:

public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        try {

        String team = req.getParameter("team");
        String name = req.getParameter("name");
        String imageData = req.getParameter("imagedata").replaceAll("data:image/[a-z]*;base64,", "");
        System.err.print("ImageData: " + imageData);

        Image image = ImagesServiceFactory.makeImage(Base64Utils.fromBase64(imageData));
        System.out.println(image.getHeight() + " : " + image.getWidth());

        } catch (Exception e) {
            e.printStackTrace();
        }
}

测试案例:

ImageData(JPEG): data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAA...
RETURNS: java.lang.IllegalArgumentException: imageData must be a valid image
ImageData(PNG): data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQCAIAAABAH0oBAAAAA3NCS...
RETURNS: 720 : 1280 (i.e. it's working)

2 个答案:

答案 0 :(得分:0)

work around适用于开发,但不适用于生产。 sun.misc.BASE64Decoder()受限制。

String base64encJPG = (String)req.getParameter("imagedata").replaceAll("data:image/[a-z]*;base64,", "");  
        byte decoded[] = new sun.misc.BASE64Decoder().decodeBuffer(base64encJPG);  
        InputStream in = new ByteArrayInputStream(decoded);  
        BufferedImage bufferedImage = ImageIO.read(in);  
        System.out.println(bufferedImage.getHeight() + " : " + bufferedImage.getWidth());

答案 1 :(得分:0)

如果你正在使用appengine,你可以使用apache commons library

public byte[] decode(final byte[] bytes) {
    return org.apache.commons.codec.binary.Base64.decodeBase64(bytes);
}