0

我无法将 URI 编码的图像转换为 jpg 格式(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)
4

2 回答 2

0

如果您使用的是 appengine,您可以使用 apache commons library

public byte[] decode(final byte[] bytes) {
    return org.apache.commons.codec.binary.Base64.decodeBase64(bytes);
}
于 2013-06-10T03:50:54.930 回答
0

这项工作在开发中有效,但在生产中无效。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());
于 2013-06-10T01:07:19.290 回答