1

Recently I started using canvas and was successful in drawing lines on a image using different colours, sizes and finally save it using dataUrl. Now I need to save this image into mySQL database. By surfing internet..., yes; I found lot of code which does this work; but using php and jquery. Seriously, I don't know ABCD of both of them. Is there any way to save the image into mySQL database without using php and jquery. Here I paste my code which I am using for annotating the image and saving it as image.

<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
    <title>Success: Upload User Image</title>   
    <style>
        #myCanvas { background:url("images/<s:property value="userImageFileName"/>") ;
                 background-size: 100% 100%;
                 background-repeat: no-repeat;}
    </style>    
</head>
<body>
    <img id="result" src="images/<s:property value="userImageFileName"/>" hidden="true" width="565" height="584" class="annotatable"/>
    <canvas id="myCanvas" width="565" height="584" style="border:1px solid #d3d3d3;">Please use a modern browser like Firefox, Chrome, Safari</canvas>
    <textarea rows="10" cols="100">
        Write your feed back with respect to colors you used to draw on image
    </textarea> 


    <form>
        <select name='color' onChange="split()">
            <option>Red</option>
            <option>Blue</option>
            <option>Green</option>
            <option>White</option>
        </select>

        <select name='tool' onChange="split()">
            <option value='1'>Pen</option>
            <option value='5'>Sketch</option>
        </select>
    </form>

    <input type="button" value="draw" onClick="draw()">
    <input type="button" value="eraser" onClick="erase()">
    <input type="submit" value="save" onClick="save()">
    <br>
    <canvas id="canvas2" width="565" height="584" hidden="true"></canvas>
    <img id="canvasImg" alt="No annotated image found">


    <script>
        var canvas = document.getElementById('myCanvas');             
        var coord = document.getElementById('coord');
        var context = canvas.getContext('2d');

        var color;

        var select = document.forms[0].color;
        select.onchange = function(){
            color =  select.options[select.selectedIndex].text;
            context.strokeStyle = color; 
        };

        var select2 = document.forms[0].tool;
        select2.onchange = function(){
            tool = select2.options[select2.selectedIndex].value;
            context.lineWidth = tool;
        };

        function draw(){
            operate("draw");
        }

        function erase(){
            operate("erase");
        }

        function operate(mode)
        {
            var mousedown = false;                

            color =  select.options[select.selectedIndex].text;     
            context.strokeStyle = color; 
            tool = select2.options[select2.selectedIndex].value;
            context.lineWidth = tool;

            canvas.onmousedown = function(e) {
                var pos = fixPosition(e, canvas);
                mousedown = true;
                context.beginPath();
                context.moveTo(pos.x, pos.y);                         
                  //return false;
            };

            canvas.onmousemove = function(e) {
                var pos = fixPosition(e, canvas);                   
                if (mousedown) {
                    if(mode=="draw"){
                        context.lineTo(pos.x, pos.y);
                        context.stroke();
                    }
                    if(mode=="erase"){
                        context.clearRect(pos.x,pos.y,10,10);                             
                    };
                };
            };

            canvas.onmouseup = function(e) {
                mousedown = false;
            };

            function fixPosition(e, gCanvasElement) {
                var x;
                var y;

                x = e.pageX;
                y = e.pageY;

                x -= gCanvasElement.offsetLeft;
                y -= gCanvasElement.offsetTop;

                return {x:x, y:y};
            };
        };

        function save(){
            var canvas2 = document.getElementById('canvas2');
            var context2 = canvas2.getContext('2d');

            var img=document.getElementById("result");
            context2.drawImage(img, 0, 0, 565, 584);
            context2.drawImage(canvas, 0, 0);

            var dataURL = canvas2.toDataURL();
            document.getElementById('canvasImg').src = dataURL;
        };

    </script>
</body>
</html>

It is working fine. I am just pasting code for a reference. Also here I am having a 'textarea' which is also needed to be saved in mySQL. Thankyou in advance

1
  • 1
    You'll need some sort of transport mechanism between your browser and your server. Generically (JavaScript rather than JQuery), you can use XMLHttpRequest which you can learn more about here: en.wikipedia.org/wiki/XMLHttpRequest. After your server has the .toDataURL, be sure you strip off the leading type indicator from the dataURL string (everything up to the first comma). You don't mention your server type but then just use your server's scripting language to save the stripped dataURL string to MySQL. Cheers! Commented Oct 12, 2014 at 16:54

2 Answers 2

1

I'm sorry, can't help myself: you can use another client-side library instead of jQuery (like Prototype, YUI, MooTools, Underscore etc. etc. etc.) and instead of the server-side language PHP you could use ASP, JSP, ColdFusion etc. etc. etc. (I am trying to make a point with this tough..)

Actually you could even do both

  • client (you don't need jQuery on the client-side for this, in fact you're not using it now)
  • and server-side (using node.js)

in pure javascript.

But what you really want to do (skipping learning a server-side language and SQL) is probably nowhere supported (I wrote probably because.. well.. almost everything is possible.. if you (can) code it).

From a more realistic real-world point-of-view:
Most hosts will support the PHP/MySQL combo by default.. Finding a 'regular' and 'cost-effective' host and an 'easy' migration plan (to just about any other average host), I'd highly recommend just biting the bullet and start toying with PHP and some SQL.

Sign up to request clarification or add additional context in comments.

Comments

0

Found a way to save a canvas as an image without using php. I got the canvas in a jsp and then I used Ajax to send the imageData to a java class.

var ajax = new XMLHttpRequest();
ajax.open("POST","upload",false);
ajax.send(canvasData); 

Received the image as a byte array in action file (I am using struts2) and then the code is as follows

HttpServletRequest req=null;
StringBuffer buffer = new StringBuffer();
try{
    Reader reader = req.getReader(); 
    int current;
    while((current = reader.read()) >= 0) {
        buffer.append((char) current);
}
}catch(IOException ioe){
    ioe.printStackTrace();
}

String data = new String(buffer); 
data = data.substring(data.indexOf(",") + 1); 
File outputImage = new File("Sairam.jpg");
FileOutputStream outputStream = new FileOutputStream(outputImage); 

try {
    outputStream.write(new BASE64Decoder().decodeBuffer(data));
    outputStream.flush();
    outputStream.close();
} catch (IOException e) {           
    e.printStackTrace();
} 

This is working fine and I am posting this after saving the image into database and also i am able to retrieve the saved image successfully.

2 Comments

Ahh, I see you did exactly what I told you in my answer :). You used JSP instead of PHP on the client-side, and you used pure javascript on the client-side. So, you got your canvas in pure javascript, you send this using a simple XMLHttpRequest (no AJAX lib) and your server uses JSP (using struts2 lib) to receive and further handle your upload. Finally I don't really see where/how your struts-code in your answer does anything with MySQL, but.. I'm glad my answer helped you getting started!
Here I have not written the code for saving image in mySQL. By the above code I am avle to get the image on server side. Then there is other code which will take this image and inserts in mySQL. Can you please tell me difference between XMLHttpRequest and Ajax. (You wrote I have not used ajax).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.