Canvas輸出圖片並保存到本地

之前做手寫識別的比賽,對於畫板canvas寫出的數字,要生成圖片保存到本地,然後調用python進行識別。對圖片保存經歷了三個版本變更。


一、直接對屏幕進行截屏保存圖片

僅停留在可以實現生成圖片,圖片的畫質還有截取的位置都有很大的問題

Robot robot;
try {
	robot = new Robot();

    //進行屏幕截取,根據不同電腦的分辨率設置參數
	BufferedImage bi = robot.createScreenCapture(new Rectangle(740,294,440,386));


	FileOutputStream out1 = new FileOutputStream("F:\\webproject\\image\\image1.png");
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);
	encoder.encode(bi);
	out1.close();


} catch (IOException e) {
	e.printStackTrace();
} catch (AWTException e) {
	e.printStackTrace();
}

二、利用canvas2image.js腳本

前端用js封裝,調用canvas2image.js腳本(github可以下到的)中的方法,缺點是隻能保存到電腦c盤中的downloads文件夾中,如果要佈置到服務器上,依然是下在自己的電腦上。如果不佈置到服務器上,這個方法就很簡單了。

<script type="text/javascript">
    // 點擊轉成圖片
    function savePic() {
        var oCanvas = document.getElementById("canvas");
        Canvas2Image.saveAsImage(oCanvas,420,420,"png","image1");        
    }
</script>

三、通過前後臺傳值base64進行本地保存

都知道canvas能生成base64編碼的圖片,這裏通過最簡單的表單傳值,將base64傳到後臺,後臺進行保存。畫質很高清,在服務器上也是可以的。唯一的缺點就是前端有個input框框就很難看,沒辦法,畢竟button不能傳value。可以通過ajax、php啥的對數據交互進行升級。

<form id="form1" method="post">
     <div class="mnist-pad-actions">
         <input type="button">
         <input type="button" onclick="submits();">
     </div>
     <input type="text" name="base64" id="base64">
</form>
<script type="text/javascript">

    // 點擊將base64傳到後臺
    function savePic() {
        var oCanvas = document.getElementById("canvas");
        var url = oCanvas.toDataURL();
        document.getElementById("base64").value = url.toString();

        var form = document.getElementById("form");
        form.method="post";
        form.action="single.jsp";
        form.submit();
    }
   
</script>
String data = request.getParameter("base64");
//對前端獲取的base64數據進行處理
data=data.replaceFirst("data:image/png;base64,", "");

//對base64編碼進行解碼
BASE64Decoder decoder = new BASE64Decoder();
byte[] hhh = decoder.decodeBuffer(data);
for (int i = 0; i < hhh.length; ++i) {
    if (hhh[i] < 0) {                // 調整異常數據
        hhh[i] += 256;
    }
}

//輸出保存爲本地圖片
String outFile = "F:\\images\\output\\image1.png";
OutputStream outs = new FileOutputStream(outFile);
outs.write(hhh);
outs.flush();
outs.close();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章