imagecreatefromgif() from base64 encoded animated gif in POST - javascript

I am trying to make animated GIFs from media streams, videos, or images using the GifShot plugin.
My problem is that the ajax part does not see webcam_image_ajax.php. isn't working. Please do not hate me so the question will be a little longer.
I have to create this ajax function for uploading image:
var pos = 0, ctx = null, saveCB, gif = [];
var createGIFButton = document.createElement("canvas");
createGIFButton.setAttribute('width', 320);
createGIFButton.setAttribute('height', 240);
if (createGIFButton.toDataURL)
{
ctx = createGIFButton.getContext("2d");
gif = ctx.getImageData(0, 0, 320, 240);
saveCB = function(data)
{
var col = data.split(";");
var img = gif;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
function(data)
{
if($.trim(data) != "false")
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: $.base_url+"webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview').attr('id');
var T= M+','+values;
if(T!='undefinedd,')
$("#uploadvalues").val(T);
}
});
}
else
{
$("#webcam").html('<div id="camera_error"><b>Camera could not connect.</b><br/>Please be sure to make sure your camera is plugged in and in use by another application.</div>');
$("#webcam_status").html("<span style='color:#cc0000'>Camera not found please try again.</span>");
$("#webcam_takesnap").hide();
return false;
}
});
pos = 0;
}
else {
saveCB = function(data) {
gif.push(data);
pos+= 4 * 320;
if (pos >= 4 * 320 * 240)
{
$.post("webcam_image_ajax.php", {type: "pixel", gif: gif.join('|')},
function(data)
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: "webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview, .gifshot-image-preview-section').attr('id');
var T= M+','+values;
if(T!='undefined,')
$("#uploadvalues").val(T);
}
});
});
pos = 0;
}
};
}
};
}
$("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function ()
{
webcam.save();
},
debug: function (type, string) {
$("#webcam_status").html(type + ": " + string);
}
});
});
/**Taking snap**/
function takeSnap(){
webcam.capture();
}
You can see this code in my ajax function:
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
the webcam_image_ajax.php is created in base64 format and then it upload the gif image from the images folder.
Also when clicked Create GIF button this JavaScript will starting: CLICK.
After that my ajax code have this line webcam_imageload_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['webcam']))
{
$newdata=$Wall->Get_Upload_Image($uid,0);
echo "<img src='uploads/".$newdata['image_path']."' class='webcam_preview gifshot-image-preview-section' id='".$newdata['id']."'/>
";
}
?>
the webcam_imageload_ajax.php working with webcam_image_ajax.php.
If webcam_image_ajax.php created image then webcam_imageload_ajax.php echoing image like:
upload/14202558.gif
But now it looks like:
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAABE...
creat a gif button:
<button type="button" id="create-gif" class="btn btn-large btn-primary create-gif-button camclick" onclick="return takeSnap();">Create GIF</button>
<input type="hidden" id="webcam_count" />

Forget the JavaScript code in the question.
If you want to use this script then use this code from demo.js inside in gifshot plugin.
function create_gif(data){
$.post(
"webcam_image_ajax.php",
{
data: data,
dataType: 'json'
},
function(js_data)
{
var js_d = $.parseJSON(js_data);
$('#gif_preview').attr('src', js_d.path);
if(js_d.id != 'error'){
$("#uploadvalues").val(js_d.id);
$('.webcam_preview, .gifshot-image-preview-section').attr('id', js_d.id);
}
}
);
}
and you can write your own php code for webcam_image_ajax.php.

Simply do like this:
file_put_contents('filename',file_get_contents(str_replace('data:','data://','<your base64 encoded data>')));
This is simply adapting your data:... into the data:// wrapper.
There is no simpler way to do this.
Notice that this is HIGHLY UNSECURE and you should validate the data (using preg_match for example) before usage.

Related

Clear bootstrap cache

I developed a dynamic carousel. Within a form I show several records and the ID of these records is related to n number of images that I show in a carousel, making it have n number of the carousel with n number of images each.
The problem is in the visualization. When I start to play with the carousels several times, they start to show the superimposed images mixing both images, for example.
My question is, what should I "clean" when loading the images so that things like this don't happen?
I execute this function JavaScript, Ajax to arm the carousel:
function GetEvidenceScrap(id)
{
var idcompleto = id.id;
var i = 0;
var idbutton = idcompleto.substring(2, idcompleto.length);
$.ajax({
method: "GET",
url: "Coordinador/GetEvidenceScrap",
contentType: "aplication/json; Charset=utf-8",
data: { 'idscrap': idbutton },
async: true,
success: function (result) {
console.log("Longitud: " + result.length);
while (i < result.length)
{
var carousel = document.getElementById('CI_' + idbutton);
if (i == 0)
{
var div = document.createElement('div');
div.setAttribute('class','carousel-item active');
var img = document.createElement("img");
img.setAttribute('class', 'd-block w-100');
div.appendChild(img);
img.setAttribute('src', '/Evidence/' + result[i].rutevidencia);
carousel.appendChild(div);
i++;
}
else
{
var div = document.createElement('div');
div.setAttribute('class', 'carousel-item');
var img = document.createElement('img');
img.setAttribute('class', 'd-block w-100');
div.appendChild(img);
img.setAttribute('src', '/Evidence/' + result[i].rutevidencia);
carousel.appendChild(div);
i++;
}
}
console.log(result);
}
});
Function in C#:
[HttpGet]
public List<Evidencia> GetEvidenceScrap(int idscrap)
{
var idscrapparametro = new SqlParameter("#idscrap", idscrap);
var listaevidencescrap = _context.Evidencias.FromSqlRaw($"SELECT IDRegistro, IDScrap, rutevidencia FROM dbo.F_GetEvidenceScrap(#idscrap)", idscrapparametro);
return listaevidencescrap.ToList();
}
Thank you

Jquery UI Progressbar filling reduced progress

$.get('jobs', {
}, function (responseText) {
rt = JSON.parse(responseText);
console.log(rt);
for (i = 0; i < rt.length; i++)
{
$("#jobs").append("<tr><td><div id='progressbar"+i+"' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar"+i).progressbar({
value: pval,
max: 100
});
}
});
I have written this code to make progressbar on a td of each row of a table. When i was doing it for 1 row it worked fine, but after I've added multiple rows in my Db, the values are not coming to be accurate.
even when value of pvalis 100, it is filling like 1/4th of the progress bar.
I was unable to replicate the issue. You may want to edit your post and include more details, example data, and any errors generated by Console.
I created the following test: https://jsfiddle.net/Twisty/0v4q5a8z/
HTML
<div class="ui-widget">
Get Progress
<table id="jobs" width="100%">
<tbody>
</tbody>
</table>
</div>
JavaScript
var progress = [
["p1", 100, 100],
["p2", 100, 75],
["p3", 100, 22]
];
function getProgress(source, target) {
/* Ajax Post used for Example purposes
** Example response:
** Array [
** ["p1", 100, 100],
** ["p2", 100, 80],
** ["p3", 100, 75]
** ]
*/
$.ajax({
url: source,
data: {
json: JSON.stringify(progress)
},
type: "POST",
dataType: "json",
success: function(responseText) {
var rt, pval;
rt = responseText
console.log(rt.toString());
for (i = 0; i < rt.length; i++) {
target.append("<tr><td><div id='progressbar-" + i + "' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar-" + i).progressbar({
value: pval,
max: 100
});
}
}
});
}
$(function() {
$(".button").button();
$("#getProgress").click(function(e) {
e.preventDefault();
getProgress("/echo/json/", $("#jobs"));
});
});
This test works as expected. Your code could be less intense. The function could be:
function getProgress(source, target) {
$.getJSON(source, function(responseText) {
var rt, pval;
rt = responseText
for (i = 0; i < rt.length; i++) {
target.append("<tr><td><div id='progressbar-" + i + "' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar-" + i).progressbar({
value: pval,
max: 100
});
}
}
});
}

HTML5 Canvas image upload - uploads blank image or destroyed

i am using the code bellow to mix two images and upload it to server as a new single image. For this i am using Canvas.
My html code is:
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('https://xxxdomain.com/image1.jpg', main);
var img2 = loadImage('https://xxxdomain.com/image2.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
var myimage = canvas.toDataURL();
var datasendervars = "myimage="+ myimage;
alert(myimage);
$.ajax({
type: "POST",
url: "save.php",
data: datasendervars,
cache: false,
success: function(html){
alert(html);
}
});
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
<script>
<canvas width="700" height="367" id="canvas"></canvas>
And my upload php script is:
$img = $_POST['myimage'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'tester/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "<p>The canvas was saved as $file.</p>";
} else {
echo "<p>The canvas could not be saved.</p>";
}
Image uploads successful but its blank and all uploaded images are the same filesize.
Any idea?
You are sending the ajax post request incorrectly. It should be ...
$.ajax({
type: "POST",
url: "save.php",
data: {"myimage": myimage},
cache: false,
success: function(html) {
alert(html);
}
});
** also make sure the images are hosted on your local server (same domain)

Check the image dimensions/size before upload

How I can check the dimensions of a image using this function? I just want to check before the upload...
$("#LINK_UPLOAD_PHOTO").submit(function () {
var form = $(this);
form.ajaxSubmit({
url: SITE_URL + 'functions/_app/execute/link_upload_photo.php',
dataType: 'html',
beforeSubmit: function () {
//CHECK DE IMAGE DIMENSIONS, SIZE, AND SHOW ERRORS
},
uploadProgress: function (event, position, total, complete) {
$(".j_progressbar").fadeIn();
$(".j_progressbar .bar").width(complete + "%");
},
success: function (data) {
$("#PHOTO_UPLOADED").css("background-image","url("+window.URL.createObjectURL(document.getElementById('ADD_FIGURE').files[0])+")");
$("#PHOTO_UPLOADED").css("background-size","462px");
$("#UPLOAD_STATUS").css("opacity", "0.5");
$("#UPLOAD_STATUS").css("-moz-opacity", "0.5");
$("#UPLOAD_STATUS").css("filter", "alpha(opacity=50)");
$(".j_progressbar").hide();
$(".ADD_FIGURE").attr("rel",data);
}
});
return false;
});
Thank you for everything.
Refer the docs for the use of .naturalWidth & .naturalWidth read-only properties of the HTMLImageElement.
var x = document.getElementById("myImg").naturalWidth;
function myFunc() {
var x = document.getElementById("myImg").naturalWidth;
var y = document.getElementById("myImg").naturalHeight;
alert(x + "X" + y);
}
<img id="myImg" src="http://www.w3schools.com/jsref/compman.gif" style="width:500px;height:98px;">
<button onclick=myFunc()>GET DETAILS</button>

How do can I get links to act independent of each other?

My code currently allows any link clicked under citations to open a new page. I'm trying to exclude the "More..." links from performing this function since these are used to add more links to the current page. Is there a way to do this?
Here's the jsfiddle
Here's my javascript
$(document).ready(function ($) {
var url = 'https://www.sciencebase.gov/catalog/item/504216b6e4b04b508bfd333b?
format=jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
var citeCount = 0;
var piCount = 0;
$('#project').append('<li><b>' + json.title + ' - </b>' + json.body + '</li>');
$('#project a').on('click', function (e) {
e.preventDefault();
if (citeCount == 1) {
return;
}
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
// Loop function for each section (10 citations per section)
var loopSection = function (start, stop) {
// Http setup for all links
var linkBase = "http://www.sciencebase.gov/catalog/item/";
// Link for citation information
var link = "";
for (var j = start; j < stop; j++) {
// Create a link using the realtedItemId
link = linkBase + json[j].relatedItemId;
// Title links
var $anchor = $("<a>", {
href: link,
id: "id" + j,
text: json[j].title
});
// .parent() will get the <li> that was just created and append to
//the first citation element
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
}
var itemCount = json.length;
var numSections = Math.floor((itemCount / 10));
var moreLinks = $('More...');
var loopCount = 1;
loopSection(0, 10);
$('#citations').append(moreLinks);
$(moreLinks).on('click', function (e) {
e.preventDefault();
if (numSections > 1) {
loopSection((loopCount * 10), ((loopCount + 1) * 10));
$('#citations').append(moreLinks);
numSections -= 1;
loopCount++;
} else if (numSections <= 1) {
$("#nextLink").closest('a').remove();
loopSection((loopCount * 10), json.length);
}
});
},
error: function (e) {
console.log(e.message);
}
}); // END Second .ajax call
$('#project').on('click', function (e) {
e.preventDefault();
if (piCount == 1) {
return;
}
for (var i = 1; i < json.contacts.length; i++) {
$('#piHeading').append('<ul>' + "Name: " + json.contacts[i].name + ', ' + "Email: " + json.contacts[i].email + ', ' + "Phone: " + json.contacts[i].phone + '</ul>');
}
piCount++;
});
citeCount++;
}); // END Project link click event
$('#citations').on('click', function (e) {
e.preventDefault();
window.open('CitationsInfo.html', '_self');
});
},
error: function (e) {
console.log(e.message);
}
}); // END First .ajax call
}); // END Doc.ready
and Here's my html,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="MainPage4.js"></script>
<script src="Citations.js"></script>
</head>
<body>
<h2>Project</h2>
<div class='wrapper'>
<ul id='project'></ul>
</div>
<h3>Citations</h3>
<div class='wrapper'>
<ul id='citations'></ul>
</div>
<h3>Principal Investigators</h3>
<div class='wrapper'>
<ul id='piHeading'></ul>
</div>
</body>
</html>
Thanks for the help
If you change the part of your code that is handling the global click event for the #citations container to include logic to filter out clicks where the target is the #nextLink, it should do what you want.
$('#citations').on('click', function (e) {
e.preventDefault();
if (!$(e.target).is($('#nextLink'))) {
window.open('CitationsInfo.html', '_self');
}
});
Removing the above section entirely also allow the "More..." link to work correctly, while still maintaining functionality on the individual links. The citations click event is masking the other behaviors.
jsfiddle

Categories

Resources