将画布图像从Java Servlet保存到png图像文件中 [英] Save canvas image into png image file from Java Servlet

查看:105
本文介绍了将画布图像从Java Servlet保存到png图像文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将画布图像从HTML页面保存到Java Servlet中的图像文件。我需要通过Ajax请求将图像从HTML发送到Java Servlet。有人可以帮帮我吗?我已经尝试了以下选项

I have been trying to save a canvas image from my HTML page to an image file in Java Servlet. I need to send the image from HTML to Java Servlet through an Ajax request. Can someone please help me out? I have already tried out the following option

Stack Overflow Question 1

这里, request.getPart(myImg)返回null,因此无效。请帮帮我。

Here, request.getPart("myImg") is returning null, hence this is not working. Please help me out.

我也试过以下解决方案
将画布内容发送到java

I have also tried the following solution Sending content of canvas to java

这里的问题是它给了我一个例外无效的文字/长度设置在下一行

The problem here is that it is giving me an exception of invalid literal/lengths set at the following line

BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes)); 

请帮助!!

更新:

这是我的Ajax代码:

Here is my Ajax Code:

function uploadImage() {
    var canvasServer = document.getElementById("canvasThumbResult");
    var context = canvasServer.getContext("2d");                    
    var imageDataURL = canvasServer.toDataURL('image/png');

    var xhr = new XMLHttpRequest();
    xhr.open("POST", trinityCvaServicesUrl+"common/uploadImage", true);
    var boundary = Math.random().toString().substr(2);
    xhr.setRequestHeader("content-type", 
        "multipart/form-data; charset=utf-8; boundary=" + boundary);
    var multipart = "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=myImg\r\n" +
        "Content-type: image/png\r\n\r\n" +
        imageDataURL + "\r\n" +
        "--" + boundary + "--\r\n";
    xhr.send(multipart);    
    /*xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("imgData="+imageDataURL);*/
}

这是我的Java代码:

And here is my Java Code:

FileOutputStream fos = null;
        try {
            Part part = req.getPart("myImg");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    part.getInputStream(), Charset.forName("utf-8")));

            /*String imgData = request.getParameter("imgData");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(
                            imgData.getBytes(StandardCharsets.UTF_8)),
                    Charset.forName("utf-8")));*/

            String sImg = br.readLine();
            sImg = sImg.substring("data:image/png;base64,".length());
            byte[] bImg64 = sImg.getBytes();
            byte[] bImg = Base64.decodeBase64(bImg64); 
            fos = new FileOutputStream(ReloadableProps.getProperty("local.image.save.path")+"img.png");
            fos.write(bImg);

            /*String imgData = req.getParameter("imgData");
            String img64 = imgData.replaceAll("data:image/png;base64,", "");
            byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64 );
            BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));    
            File outputfile = new File(ReloadableProps.getProperty("local.image.save.path")+"img.png");
            ImageIO.write(bfi , "png", outputfile);
            bfi.flush();*/
        } catch (Exception e) {
            e.printStackTrace();
            String loggerMessage = "Upload image failed : ";
            CVAException.printException(loggerMessage + e.getMessage());
        } finally {
            if(fos != null) {
                fos.close();
            }
        }


推荐答案

我设法以某种方式保存图像。不确定这是否是一种有效的方法。如果您认为这可能不是一种有效的方法,请发表评论。感谢您的反馈。

I have managed to save the image somehow. Not sure if that is an efficient way of doing this. Please comment if you feel this might not be an efficient way of doing this. Appreciate your feedback.

我的JavaScript代码:

My JavaScript code:

    var canvasServer = document.getElementById("canvasThumbResult");
    var context = canvasServer.getContext("2d");                    
    var imageDataURL = canvasServer.toDataURL('image/png');
    var ajax = new XMLHttpRequest();
    ajax.open("POST",trinityCvaServicesUrl+"common/uploadImage",false);
    ajax.setRequestHeader("Content-Type", "application/upload");
    ajax.send(imageDataURL);

我的Java代码:

        InputStream in = null;
        FileOutputStream fos = null;
        try {
            HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(req);
            InputStream is = wrappedRequest.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            String imageString = writer.toString();
            imageString = imageString.substring("data:image/png;base64,"
                    .length());
            byte[] contentData = imageString.getBytes();
            byte[] decodedData = Base64.decodeBase64(contentData);
            String imgName = ReloadableProps
                    .getProperty("local.image.save.path")
                    + String.valueOf(System.currentTimeMillis()) + ".png";
            fos = new FileOutputStream(imgName);
            fos.write(decodedData);
        } catch (Exception e) {
            e.printStackTrace();
            String loggerMessage = "Upload image failed : ";
            CVAException.printException(loggerMessage + e.getMessage());
        } finally {
            if (in != null) {
                in.close();
            }
            if (fos != null) {
                fos.close();
            }
        }

这篇关于将画布图像从Java Servlet保存到png图像文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆