2017-01-22 5 views
0

私はキャンバスを持っていて、サーバーからサーバーに送るbase64エンコーディングを取得したいのですが、これは.toDataURL()で行うことができます。しかし、問題は私が全体のイメージを送信したくないということです、私はそれの一部を送信したいです。私はその部分の画像データを得るために、キャンバスからのデータurlベース64エンコーディングを取得するにはどうすればよいですか?

.getImageData(x、y、w、h)を持っています。しかし、今私はどのようにこのデータのURLをサーバーに送ることができますか?

誰でも知っていますか?

ありがとうございました

答えて

1

ちょうどそのキャンバス

// context is the context from which to copy 
// x,y,w,h is the sub area to copy ar data URL 
function getDataURLSubImage(context,x,y,w,h){ 
    var can = document.createElement("canvas"); 
    can.width = w; 
    can.height = h; 
    var ctx = can.getContext("2d"); 
    ctx.drawImage(context.canvas,-x,-y); 
    return can.toDataURL(); 
} 

それともだけimageData次の操作を行うことができます持っていますが、それは上記よりも効率が低い場合のデータのURLを取得し、その後一時キャンバスを作成して、キャンバスにピクセルをコピー方法。

function imageDataToDataURL(imageData){ 
    var can = document.createElement("canvas"); 
    can.width = imageData.width; 
    can.height = imageData.height; 
    var ctx = can.getContext("2d"); 
    ctx.putImageData(imageData,0,0); 
    return can.toDataURL(); 
} 
0

JavaScriptでは、dataURLはJSON形式で送信できます。 $ scope.canvasObject = { "screenName": 'testName'、 "screenObject":JSON.stringify(canvas.toDataURL()) };

サーバ側では、これはバイト配列形式で受信されます。

byte[] bytes = null; 
    File file = null; 
    BufferedImage bfi = null; 
    try { 
     if (entity != null && entity.getScreenObject() != null) { 
      bytes = DatatypeConverter 
        .parseBase64Binary(entity.getScreenObject().replaceAll("data:image/png;base64,", "")); 
      file = new File(entity.getScreenName() + System.currentTimeMillis() + ".png"); 
      bfi = ImageIO.read(new ByteArrayInputStream(bytes)); 
      ImageIO.write(bfi, "png", file); 
      bfi.flush(); 
     } 
    } catch (Exception e) { 
     // handle exception 
    } 

これにより、サーバーにイメージが保存されます。

関連する問題