how can we save html5 canvas image to database in php [duplicate] - javascript

This question already has answers here:
How to save an HTML5 Canvas as an image on a server?
(8 answers)
Closed 8 years ago.
I m creating product design page for e-commerce web site...
I need to save designed image from client side to database....
I tried to save but it could'nt save...and html5 canvas is new for me...
My html code..
...................
<div id="clothing-designer">
<div class="fpd-product" title="Shirt Front" data-thumbnail="images/yellow_shirt/front/preview.png">
<img src="./images/yellow_shirt/front/base.png" title="Base Front" data-parameters='{"x": 123, "y": 81, "colors": "#d59211", "price": 20}' />
<img src="./images/yellow_shirt/front/body.png" title="Hightlights" data-parameters='{"x": 249, "y": 80}' />
<img src="./images/yellow_shirt/front/shadows.png" title="Shadow" data-parameters='{"x": 123, "y": 81}' />
<span title="Any Text" data-parameters='{"x": 243, "y": 181, "removable": true, "draggable": true, "rotatable": true, "resizable": true, "colors": "#000000"}'>Default Text</span>
<div class="fpd-product" title="Shirt Back" data-thumbnail="images/yellow_shirt/back/preview.png">
<img src="./images/yellow_shirt/back/base.png" title="Base Back" data-parameters='{"x": 123, "y": 81, "colors": "#d59211", "price": 20}' />
<img src="./images/yellow_shirt/back/body.png" title="Hightlights" data-parameters='{"x": 277, "y": 79}' />
<img src="./images/yellow_shirt/back/shadows.png" title="Shadow" data-parameters='{"x": 123, "y": 81}' />
</div>
</div>

You give little info, but here is a brief overview of the process you will need.
A full description of how to get design info from the client to your database is beyond the scope of a Stackoverflow discussion, but this example should get you started with the concepts involved.
Convert the canvas to an imageUrl
If you want to save the canvas content as an image you can use canvas.toDataURL() which returns a DataURL of the canvas in .png format. For example:
var canvas=document.getElementById("myCanvas");
var dataUrl=canvas.toDataURL();
Send that dataUrl back to your server with an AJAX post
$.ajax({
type: "POST",
url: "http://localhost/saveCanvasDataUrl.php",
data: {image: dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
On the PHP side, save the incoming dataURL to a database:
<?php
if(!isset($_POST["code"])){
die("Post was empty.");
}
$sql="insert into designs(image) values(:image)";
// INSERT with named parameters
$conn = new PDO('mysql:host=localhost;dbname=myDB', "root", "myPassword");
$stmt = $conn->prepare($sql);
$stmt->bindValue(":image",$_POST["image"]);
$stmt->execute();
$affected_rows = $stmt->rowCount();
echo $affected_rows;
?>
Alternatively...
With this all said, it might be more useful to save the components of the design that the user created rather than an image of that design.
Create a javascript object containing the specific info about the design:
var item1={
product:"shirt",
color:"#d59211",
price:20,
text:"Default Text",
textX:243,
textY:181
}
Use JSON to convert that object into a string
var item1Json=JSON.stringify(item1);
Then post that useful design data to your database instead of the image.

You can use HTML5 Canvas' toDataURL() which according to the docs:
Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG)
It is used like this:
var canvas = document.getElementById('thecanvaselement');
// ...maybe some more canvas drawing operations here
var url = canvas.toDataURL();
The results (stored in the url variable) can then be sent back to the server using AJAX and then saved to your database like you would normally do.

Related

how to display byte[] as picture in html with java

I use spring mvc and JPA in my project. I get file as byte[] and save in Database. but when I want to display in <img tag of html it don't display.
my entity is:
class Photo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
#Lob
private byte[] profilePic;
// getter and setter
}
value in Database is:
but my server response is:
{
"id": 4,
"title": "pic 1",
"profilePic": "ZGF0YTppb...VFtQ0M=",
}
and display in html:
<img src='ZGF0YTppb...VFtQ0M=' />
//or
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
What to do to display the photo?
thanks
Assuming it's base64 encoded:
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
Basically you can use data urls with this format depending on what content [type] you want to display:
data:[<mime type>][;charset=<charset>][;base64],<encoded data>
HTML:
<img id="profileImg" src="">
JS:
document.getElementById("profileImg").src = "data:image/png;base64," + profilePic;
This assumes that your image is stored in PNG format (and base64 encoded). For other image format (JPEG, etc.), you need to change the MIME type ("image/..." part) in the URL.

How to show a base64 image in html

I get some information from the API that has a property called pic (image) which is base64
like this:
{description: "description"
id: 1
isActive: false
max: 10
min: 1
pic: "W29iamVjdCBGaWxlXQ==" //-->is base64
rewardCategoryEnTitle: "test"
rewardCategoryId: 2
rewardCategoryTitle: "test"
scoreValue: 200
title: "test"}
How can I show it in tag <img/>?
all you have to do is include data:image/jpg;base64, infront of the base64 string. You can change jpg to whatever file type you want it to be
<img src="data:image/jpg;base64,....."/>
so if you are using react it would probably be like this
<img src={`data:image/jpg;base64,${objectName.pic}`}/>
If it is valid base64 you can show it like this
<img class="itemImage" src="{{ 'data:image/png;base64,' + photo }}"/>
Validate your base64 string here.

<kendo:pager pageSizes="pageSizes">

I'm trying to set pageSize in kendo:grid.
I've searched and I know it can be set via javascript using
pageable:{
pageSizes: [10, 20, 35, 50, 75, 100]
},
but the kendo:grid which I have does not use JavaScript. It uses Kendo-tag libraries in jsp.
This is my code structure:
<kendo:grid name="NameOfGrid" groupable="false" sortable="true">
<kendo:grid-pageable pageSizes="true" refresh="false" > </kendo:grid-pageable>
<kendo:grid-columns>
<kendo:grid-column title=" " field=" " width="60" sortable="true" />
There are new more <kendo:grid-colum>
</kendo:grid-columns>
<kendo:dataSource data="${"dataSource"}" pageSizes="[10,20,30,40]"> </kendo:dataSource>
</kendo:grid>
So, i'm using this way to set kendo:grid and everything work's perfect, but here i want to set own pageSize, by default when pageSize is kept true it has dropdown [5,10,20 and All ] but i want to change it and keep as [10, 20, 35, 50, 75, 100].
..
so can anyone help or show an example on how to set using . There are few documentation using it but i couldnot find a proper example.http://docs.telerik.com/kendo-ui/api/jsp/pager
Thank you so much for your time.
You can pass an Object array as predefined values to the pageSizes option, e.g.:
<%
Object pageSizes[] = {10, 50, 100, 250};
%>
...
<kendo:grid name="grid" groupable="true" sortable="true" style="height:550px;">
<kendo:grid-pageable refresh="true" pageSizes='<%= pageSizes %>' ...>

How to Save JPEG binary data to Django ImageField

Goal: Get users signature through browser web application and save it to Django ImageField
I'm using https://github.com/szimek/signature_pad to get users signature on client side, then first saving it within a Django ModelForm TextField using toDataURL().
Now I'm stuck at the last step of converting the data into a jpeg image file and saving it to my Django ImageField.
I followed the tip at Uploading JavaScript generated image to Django but it only covers till decoding 64 bit string into 32 bit and I can't complete the last step:
...and now ImageData contains the binary data, you can simply save to
a file..
HTML
{{ attendeeMegaForm.signatureHolder }}
<div id="signature-pad" class="m-signature-pad">
<div class="m-signature-pad--body">
<canvas></canvas>
</div>
<div class="m-signature-pad--footer text-center">
<div class="description"><strong>Please Sign above <i class="fa fa-arrow-up"></i></strong></div>
<button type="button" class="btn btn-sm btn-default clear" data-action="clear">Clear</button>
</div>
</div>
JS
signaturePad = new SignaturePad(canvas, {
backgroundColor: "rgb(255,255,255)",
minWidth: 0.4,
maxWidth: 2,
dotSize: 1.2,
onEnd: function () {
signature = signaturePad.toDataURL("image/jpeg");
document.getElementById('id_signatureHolder').value = signature;
}
});
Python
if request.POST.get('updateAttendeeKey'):
if attendeeMegaForm.is_valid():
dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
ImageData = request.POST.get('signatureHolder')
ImageData = dataUrlPattern.match(ImageData).group(2)
if ImageData == None or len(ImageData) != 0:
ImageData = base64.b64decode(ImageData)
Thanks!
Here is how I got it to work with signature_pad on the python 3.5/Django 1.9.2 backend:
import re, io
from base64 import decodestring
from django.core.files import File
data_url_pattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
signature_url = request.POST.get("sig_data_url")
signature_data = data_url_pattern.match(signature_url).group(2)
signature_data = bytes(signature_data, 'UTF-8')
signature_data = decodestring(signature_data)
img_io = io.BytesIO(signature_data)
model_instance.image_field.save(filename, File(img_io))
Basically after you decode the string, just create the io object that will be used to create the Django File object. Once you have that, you can save it to the image field with the filename you want to use.

backbone and javascript: upload and store the image data in GAE datastore?

I have been searching through wherever possible but got no help at all for this question.
I am working on a small program using python GAE with backbone javascript, I want the user can create a new book with a html form given below and store the new book in the GAE datastore, the form contains strings and an image.
<form>
<div><label>Title:</label> <input type="text" id="title" name="book_title" ></div>
<div><label>Author:</label> <input type="text" id="author" name="book_author" ></div>
<div><label>Picture:</label> <input id="image" type="file" class="upload" name="img" /></div>
<div><img id="img_preview" src="#" alt="image" ></img></div>
<div><button class="create_book">Create Book</button></div>
</form>
selecting a book picture from the local file system is handled by displayPicture method in order to load a thumbnail image on the page for preview.
clicking "Create Book" button event is handled by the createBook method in javascript file:
event:{
"click .create_book": "createBook" ,
"change .upload": "displayPicture",
......
},
createBook:function(){
this.model.set({
title: $('#title').val(),
author: $('#author').val(),
image: this.pictureFile.name
});
......
app.bookList.create(this.model,{wait:true,
success:function(){
alert("A new book has been created!");
}
});
return false;
},
......
displayPicture: function(evt){
var files = evt.target.files;
if(files){
this.pictureFile = files[0];
var reader = new FileReader();
reader.onloadend = function(){
$('#img_preview').attr('src',reader.result).width(200).height(200);
};
reader.readAsDataURL(this.pictureFile);
},
..........
at the python server end:
class Book(db.Model):
title = db.StringProperty()
author = db.StringProperty()
image = db.BlobProperty()
class createBook(webapp.RequestHandler):
def post(self):
book = Book()
book.title = self.request.get("title")
book.author = self.request.get("author")
book.image = db.Blob(self.request.get("image"))
book.put()
......
application = webapp.WSGIApplication(
[
.....
('/books/?',createBook)
],
debug=Ture
)
I can only display the thumbnail picture on the page for preview, but fail to create the new book, the line "app.bookList.create(...)" does send a POST request to the python server end, and the request is handled by the "createBook" method, but Firebug shows the "self.request.get("title"/"author"/"image")" lines are just an empty string, which means the content of the form is not retrieved from the Http request properly.
can you tell what are the problems in my code snippet ? thanks for your help.
I think that your problem is likely that you are passing a model in to create. From the Backbone docs:
create collection.create(attributes, [options])
Convenience to create a new instance of a model within a collection.
create isn't expecting a model, because it creates a model; what it's expecting is a raw JSON object (eg. {foo: bar}).
*EDIT* Actually, that's incorrect, create can accept an (un-saved) model; leaving the next few lines here any way so this doesn't get too confusing.
You could fix this by doing:
app.bookList.create(this.model.attributes, {wait:true,
or:
app.bookList.create(this.model.toJSON(), {wait:true,
but really you don't need to use create at all because you don't need to create a model (you already have one). What you (probably) want to do is add the model you have to the collection:
app.bookList.add(this.model)
and then sync it with the server separately:
this.model.save(null, {wait:true,
success:function(){
alert("A new book has been created!");
}
});
In the python side, you should get the data from
self.request.body
Not
self.request.get('xxx')

Categories

Resources