Ask your WordPress questions! Pay money and get answers fast! (more info)

Save canvas in wp-upload

  • SOLVED

Hi,

In wp-admin/post.php, I have a metabox where I generate an image using Canvas.
This image is made of the featured image and the post title.
I need to save this image into wp-uploads as an attachment to the post.
Can someone help?

----------------------------
<canvas id="canvas1" width="468" height="60" style="background:#ffffff; border:1px solid #cacaca;"></canvas>

<?php

//This is the php - we get image size to set a nice layout - simple php variables

$id = get_the_ID();
$thumb_id = get_post_thumbnail_id($id);
$thumb_url_thumbnail = wp_get_attachment_image_src($thumb_id,'thumbnail', true);
$thumb_url_medium = wp_get_attachment_image_src($thumb_id,'medium', true);
$thumb_url_large = wp_get_attachment_image_src($thumb_id,'large', true);

list($width_thumb_url_large, $height_thumb_url_large) = getimagesize($thumb_url_large[0]);
$woc_ratio = 227/$width_thumb_url_large;
$woc_height_thumb_url_large = $height_thumb_url_large*$woc_ratio;

// We cut the title if it's too long.
$text_base = get_the_title();
$length = strlen($text_base);
if($length >=30) {
$text_court = substr($text_base,0,30);
$text_court = $text_court . '...';
}
else{
$text_court=$text_base;
}
?>

<script>
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
//Image (featured image)
var img=new Image() //creates a variable for a new image
img.src= "<?php echo $thumb_url_large[0]; ?>" // Lien de l'image
context.save();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(187, 0);
context.lineTo(227, 68);
context.lineTo(0, 68);
context.closePath();
context.clip();
context.drawImage(img, -5, -5, 227, <?php echo $woc_height_thumb_url_large; ?>);
context.restore();

//Path element
context.save();
context.beginPath();
context.moveTo(187, 0);
context.lineTo(200, 0);
context.lineTo(222, 60);
context.fillStyle = "<?php echo $color2; ?>";
context.fill();
context.closePath();
context.restore();
//Icon
var img2=new Image() //creates a variable for a new image
img2.src= "<?php echo WES_URL . 'img/arrow.png'; ?>"
context.drawImage(img2, 430, 15); // Show the image

//Text
var text = "<?php echo $text_court; ?>";
context.font = "600 13px Helvetica,Geneva,Arial";
context.textAlign="left";
context.fillStyle = '#000';
context.fillText(text, 224, 36);
//Stroke around the Canvas
context.strokeStyle = '#cacaca';
context.lineWidth = 1; // thickness
context.strokeRect(0, 0, 468, 60);

//This is where we need the save function into wp-uploads.
//
//
</script>

Answers (2)

2017-04-05

Francisco Javier Carazo Gil answers:

Good afternoon,

The first thing you need is save the canvas in a variable:

var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL();

Then you need some AJAX call in some action (for example some button to save the image):

$( '#save_image' ).submit( function(){
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'save_image_canvas',
imgBase64: dataURL,
post_id: '<?php global $post; echo $post->ID; ?>',
}
}).done(function(o) {
console.log('saved');
});
} );

And then you will need the PHP-AJAX part:

add_action( 'wp_ajax_save_image_canvas', 'save_image_canvas' );

function save_image_canvas(){
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);

//saving
$attachment = wp_upload_bits( 'name_file.png', null, $fileData );

$filetype = wp_check_filetype( basename( $attachment['file'] ), null );

$postinfo = array(
'post_mime_type' => $filetype['type'],
'post_title' => 'Canvas uploaded image',
'post_content' => '',
'post_status' => 'inherit',
);
$filename = $attachment['file'];
$attach_id = wp_insert_attachment( $postinfo, $filename, $postid );

set_post_thumbnail( $_POST["post_id"], $attach_id );
}


User162095 comments:

Hi Francisco
Thank you for your message. I aready did this in my tests, it works and return an image made from the canvas.
What I want to do is to save the image in wp-uploads as post atachment when we save the post.
As all is in JS, there is probably some piece of Ajax to make.


User162095 comments:

Sorry, I saw only the 2 first lines of your comment. I'll try your code.


Francisco Javier Carazo Gil comments:

Try it but take care, this is not tested but the idea is this.


User162095 comments:

something seems to happen. This is what I did :
I added a button <button id="save_image">Save</button>
because I see '#save_image' ).submit( function in your code.
When I click on this button, I can see something happening (wheel) - and then nothing, the image is not created.


Francisco Javier Carazo Gil comments:

Ok, let's go.

Are you seeing something in console?


User162095 comments:

I am out for 1h


Francisco Javier Carazo Gil comments:

Ok, don't worry. If need something more write again.

If I am online I will be able to ask you.


User162095 comments:

In console, I get: : GET http://localhost:8888/wordpress/wp-admin/admin-ajax.php?action=oembed-cache&post=1
200 OK 487ms
When I load the page or I click on the button with ID: save_image.


Francisco Javier Carazo Gil comments:

That's not correct.

Change this part:

$( '#save_image' ).click( function( e ){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'save_image_canvas',
imgBase64: dataURL,
post_id: '<?php global $post; echo $post->ID; ?>',
}
}).done(function(o) {
console.log('saved');
});
} );

2017-04-05

Rempty answers:

Is this canvas created after you save the post?


User162095 comments:

no, before.


Rempty comments:

that's mean if you upload the post thumbnail in wp-admin automatically generate the canvas image (in real time), right?


User162095 comments:

Yes


Rempty comments:

Hey i have a solution
First add a textarea after your canvas
<textarea id="image_canvas_base64" name="image_canvas_base64"></textarea>

and in your script here
//This is where we need the save function into wp-uploads.
//
//add
//I am going to asign the canvas image to a text area
var dataURL = canvas.toDataURL();
jQuery("#image_canvas_base64").val(dataURL);


Now add this code to your functions.php
function save_canvas_meta_box( $post_id ){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ){
return;
}
if(isset($_POST['image_canvas_base64'])){
$have_canvas_title=get_post_meta($post_id,'title-canvas',true);
if($have_canvas_title!=0 && $have_canvas_title){
wp_delete_attachment($have_canvas_title,true);
}
$image=$_POST['image_canvas_base64'];
$data = substr($image, strpos($image, ",") + 1);
$decodedData = base64_decode($data);
$filename='title-canvas-'.$post_id.'.png';
echo $filename;
$attachment = wp_upload_bits( $filename, null, $decodedData );


$filetype = wp_check_filetype( basename( $attachment['file'] ), null );
$attdata = array(
'post_mime_type' => $filetype['type'],
'post_title' => 'Canvas Title',
'post_content' => '',
'post_status' => 'inherit',
);
$filename = $attachment['file'];
$attach_id = wp_insert_attachment( $attdata, $filename, $post_id );

require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta($post_id,'title-canvas',$attach_id);
}
}
add_action( 'save_post', 'save_canvas_meta_box' );


In this code i also saved the ID of the image attachment to detect if already have created the image and don't duplicate images