Dropzone js Not Load Video Thumbnail From Server - javascript

i have problem with dropzone js when loading Uploaded video from server .
dropzone load picture thumbnails but video thumbnail not loaded .
check it from this link
i want to load videos from ajax request . this is my code :
this.on("error", function(file, response) {
$(file.previewElement).find('.dz-error-message').tooltip().attr('data-original-title',response);
});
$.ajax({
url: 'https://localhost/asnaf2019/userpanel/uploader.php',
type: 'post',
data: {request: 2},
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name };
myDropzone_video.emit("addedfile", mockFile);
myDropzone_video.emit("thumbnail", mockFile, value.path);
myDropzone_video.emit("complete", mockFile);
});
}
});
this.on('addedfile', function(origFile) {
var fileReader = new FileReader();
fileReader.addEventListener("load", function(event) {
var origFileIndex = myDropzone_video.files.indexOf(origFile);
myDropzone_video.files[origFileIndex].status = Dropzone.ADDED;
var blob = new Blob([fileReader.result], {type: origFile.type});
var url = URL.createObjectURL(blob);
var video = document.createElement('video');
var timeupdate = function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
video.pause();
}
};
video.addEventListener('loadeddata', function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
}
});
if (!origFile.type.match(/mp4|MP4/)) {
myDropzone_video.enqueueFile(origFile);
myDropzone_video.removeFile(origFile);
return;
}
var snapImage = function() {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var arrText = new Array();
var image = canvas.toDataURL();
var success = image.length > 100000;
if (success) {
var img = document.getElementsByClassName('img-preview');
var l = img.length;
$.each(img,function(){
arrText.push(image);
});
for(var i=0; i < l; i++){
var t = img[i];
myDropzone_video.emit("thumbnail", origFile, arrText[i]);
}
URL.revokeObjectURL(url);
}
return success;
};
video.addEventListener('timeupdate', timeupdate);
video.preload = 'metadata';
video.src = url;
video.muted = true;
video.playsInline = true;
video.play();
});
fileReader.readAsArrayBuffer(origFile);
});
this error shown when code run :
TypeError: Argument 1 of FileReader.readAsArrayBuffer does not
implement interface Blob.
how i can fix this problem

I used this way for the problem
$.each(response, function(key,value) {
var mockFile = { name: value.name};
if (value.type.match(/mp4|MP4/)){ // Preview video only from type mp4
myDropzone_video.options.addedfile.call(myDropzone_video, mockFile);
var src = value.path;
var video = document.createElement('video');
video.src = src;
video.addEventListener('loadeddata', function() {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var dataURI = canvas.toDataURL('image/png');
myDropzone_video.emit("thumbnail", mockFile, dataURI);
});
myDropzone_video.emit("complete", mockFile);
}
});
I have solved ,this problem in this way.

Related

Save div on the server as image and download it

In my Asp.NET MVC application, in a div I have superpositioned images in to show how it seem an insole model.
I should download this image when the model is ready.
What I did works on my pc and download the image.
But when I publish the application, it opens the image instead of downloading it.
Any idea please ?
Here is what I did :
Controller :
public JsonResult SaveModelImage(string dynamicImage)
{
try
{
var buffer = Convert.FromBase64String(dynamicImage.Replace("data:image/png;base64,", ""));
//For capron modesls, there is more than one model with the same reference. For every model, must save image to the related folder.
var imageName = Guid.NewGuid().ToString().Substring(0, 10);
var imagePath = Path.Combine(Server.MapPath("/MyApplicationRoot/Images/Temp/" + imageName + ".jpg"));
using (MemoryStream ms = new MemoryStream(buffer))
{
using (var bmp = Bitmap.FromStream(ms, true))
{
bmp.Save(imagePath);
}
}
return Json(System.Configuration.ConfigurationManager.AppSettings["RootLink"] + "/Images/Temp/" + imageName + ".jpg");
}
catch (Exception ex)
{
UserMethods.ParseError(ex, "UploadModelImage");
return Json(ex.Message);
}
}
HTMLCS :
<a onclick="downloadImage()" class="download-image"></a>
function downloadImage() {
html2canvas(document.getElementById("reviewTopLeft1"), {
onrendered: function (canvas) {
var tempcanvas = document.createElement('canvas');
tempcanvas.width = 640;
tempcanvas.height = 480;
var context = tempcanvas.getContext('2d');
context.drawImage(canvas, 0, 0, 640, 480);
var val = tempcanvas.toDataURL();
$.ajax({
url: '#Url.Action("SaveModelImage", "Admin")',
type: 'post',
data: { dynamicImage: val},
dataType: 'json',
success: function (iudata) {
downloadURI(iudata, "Model.jpg");
},
error: function (err) {
hideLoader();
}
});
}
});
}
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.target = "_blank";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}

How to save canvas animation as gif or webm?

i have written this function to capture each frame for the GIF but the output is very laggy and crashes when the data increases. Any suggestions ?
Code :
function createGifFromPng(list, framerate, fileName, gifScale) {
gifshot.createGIF({
'images': list,
'gifWidth': wWidth * gifScale,
'gifHeight': wHeight * gifScale,
'interval': 1 / framerate,
}, function(obj) {
if (!obj.error) {
var image = obj.image;
var a = document.createElement('a');
document.body.append(a);
a.download = fileName;
a.href = image;
a.click();
a.remove();
}
});
}
/////////////////////////////////////////////////////////////////////////
function getGifFromCanvas(renderer, sprite, fileName, gifScale, framesCount, framerate) {
var listImgs = [];
var saving = false;
var interval = setInterval(function() {
renderer.extract.canvas(sprite).toBlob(function(b) {
if (listImgs.length >= framesCount) {
clearInterval(interval);
if (!saving) {
createGifFromPng(listImgs, framerate, fileName,gifScale);
saving = true;
}
}
else {
listImgs.push(URL.createObjectURL(b));
}
}, 'image/gif');
}, 1000 / framerate);
}
In modern browsers you can use a conjunction of the MediaRecorder API and the HTMLCanvasElement.captureStream method.
The MediaRecorder API will be able to encode a MediaStream in a video or audio media file on the fly, resulting in far less memory needed than when you grab still images.
const ctx = canvas.getContext('2d');
var x = 0;
anim();
startRecording();
function startRecording() {
const chunks = []; // here we will store our recorded media chunks (Blobs)
const stream = canvas.captureStream(); // grab our canvas MediaStream
const rec = new MediaRecorder(stream); // init the recorder
// every time the recorder has new data, we will store it in our array
rec.ondataavailable = e => chunks.push(e.data);
// only when the recorder stops, we construct a complete Blob from all the chunks
rec.onstop = e => exportVid(new Blob(chunks, {type: 'video/webm'}));
rec.start();
setTimeout(()=>rec.stop(), 3000); // stop recording in 3s
}
function exportVid(blob) {
const vid = document.createElement('video');
vid.src = URL.createObjectURL(blob);
vid.controls = true;
document.body.appendChild(vid);
const a = document.createElement('a');
a.download = 'myvid.webm';
a.href = vid.src;
a.textContent = 'download the video';
document.body.appendChild(a);
}
function anim(){
x = (x + 1) % canvas.width;
ctx.fillStyle = 'white';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = 'black';
ctx.fillRect(x - 20, 0, 40, 40);
requestAnimationFrame(anim);
}
<canvas id="canvas"></canvas>
You can also use https://github.com/spite/ccapture.js/ to capture to gif or video.

crop image with jcrop I get a black image when decode it in base64

I used a lot time, trying to get a successful decode image in base64, but I get a black image. I don't know what is wrong.
I am using jcrop
I need yo two thing.
Get a successful image when decode it base64 and I can rotate image before to crop. Appreciate your help or recommendations.
I am using this example is not mine in jisfidle
var cropCoords,
file,
uploadSize = 360,
previewSize = 500;
$("input[type=file]").on("change", function(){
file = this.files[0];
readFile(file, {
width: previewSize,
height: previewSize
}).done(function(imgDataUrl, origImage) {
$("input, img, button").toggle();
initJCrop(imgDataUrl);
}).fail(function(msg) {
alert(msg);
});
});
$("button[type=submit]").on("click", function(){
$(this).text("Uploading...").prop("disabled", true);
readFile(file, {
width: uploadSize,
height: uploadSize,
crop: cropCoords
}).done(function(imgDataURI) {
var data = new FormData();
var blobFile = dataURItoBlob(imgDataURI);
data.append('file', blobFile);
$.ajax({
url: "/upload",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function() {
alert("Yay!");
},
error: function(xhr) {
alert("Well, obviously we can't upload the file here."+
"This is what the data looks like: " +
imgDataURI.substr(0,128)+"...");
console.log(imgDataURI);
}
});
});
});
/*****************************
show local image and init JCrop
*****************************/
var initJCrop = function(imgDataUrl){
var img = $("img.crop").attr("src", imgDataUrl);
var storeCoords = function(c) {
cropCoords = c;
};
var w = img.width();
var h = img.height();
var s = uploadSize;
img.Jcrop({
onChange: storeCoords,
onSelect: storeCoords,
aspectRatio: 1,
setSelect: [(w - s) / 2, (h - s) / 2, (w - s) / 2 + s, (h - s) / 2 + s]
});
};
/*****************************
Read the File Object
*****************************/
var readFile = function(file, options) {
var dfd = new $.Deferred();
var allowedTypes = ["image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/bmp"];
if ($.inArray(file.type, allowedTypes) !== -1) {
//define FileReader object
var reader = new FileReader();
var that = this;
//init reader onload event handlers
reader.onload = function(e) {
var image = $('<img/>')
.load(function() {
//when image is fully loaded
var newimageurl = getCanvasImage(this, options);
dfd.resolve(newimageurl, this);
})
.attr('src', e.target.result);
};
reader.onerror = function(e) {
dfd.reject("Couldn't read file " + file.name);
};
//begin reader read operation
reader.readAsDataURL(file);
} else {
//some message for wrong file format
dfd.reject("Selected file format (" + file.type + ") not supported!");
}
return dfd.promise();
};
/*****************************
Get New Canvas Image URL
*****************************/
var getCanvasImage = function(image, options) {
//define canvas
var canvas = document.createElement("canvas"),
ratio = {
x: 1,
y: 1
};
if (options) {
if (image.height > image.width) {
ratio.x = image.width / image.height;
} else {
ratio.y = image.height / image.width;
}
}
canvas.height = options.crop ? Math.min(image.height, options.height) : Math.min(image.height, Math.floor(options.height * ratio.y));
canvas.width = options.crop ? Math.min(image.height, options.width) : Math.min(image.width, Math.floor(options.width * ratio.x));
var ctx = canvas.getContext("2d");
if (options.crop) {
//get resized width and height
var c = options.crop;
var f = image.width / options.previewWidth;
var t = function(a) {
return Math.round(a * f);
};
ctx.drawImage(image, t(c.x), t(c.y), t(c.w), t(c.h), 0, 0, canvas.width, canvas.height);
} else {
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}
//convert canvas to jpeg url
return canvas.toDataURL("image/jpeg");
};
/*****************************
convert dataURI to blob
*****************************/
var dataURItoBlob = function(dataURI) {
var blob = window.Blob || window.WebKitBlob || window.MozBlob;
//skip if browser doesn't support Blob object
if (typeof blob === "undefined") {
alert("Oops! There are some problems with your browser! <br/>New image produced from canvas can\'t be upload to the server...");
return dataURI;
}
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString;
if (dataURI.split(',')[0].indexOf("base64") >= 0) {
byteString = atob(dataURI.split(',')[1]);
} else {
byteString = unescape(dataURI.split(',')[1]);
}
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new blob([ab], {
type: mimeString
});
};
html
<input type="file" />
<img class="crop" style="display:none" />
<button type="submit" style="display:none">Upload</button>
I get a black image when decode it in base64
Example image
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCABLAEsDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8qqKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/2Q==

Can't post a Base64Image on IOS/Safari

I have got some script that gets an image from the first frame of a video and returns a base64image encoding.
I am then posting this image to the server back end to be saved to the uploads directory..
It works fine on chrome on a desktop, but when I test on iPhone7 IOS10 Safari it does not work.
I have tried to use both blobs and base64image but none work on iOS and both do work on chrome desktop.
Here is the javascript I'm currently using to get the image..
$('#upload').bind('change', function(event) {
console.log("input");
var file = event.target.files[0];
var fileReader = new FileReader();
if (file.type.match('image')) {
fileReader.onload = function() {
var img = document.createElement('img');
img.src = fileReader.result;
document.getElementsByTagName('div')[0].appendChild(img);
};
fileReader.readAsDataURL(file);
} else {
fileReader.onload = function() {
var blob = new Blob([fileReader.result], {type: file.type});
var url = URL.createObjectURL(blob);
var video = document.createElement('video');
var timeupdate = function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
video.pause();
}
};
video.addEventListener('loadeddata', function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
}
});
var snapImage = function() {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var image = canvas.toDataURL(); // Base64Image source
var success = image.length > 100000;
if (success) {
var img = document.createElement('img');
img.src = image;
document.getElementsByTagName('div')[0].appendChild(img);
URL.revokeObjectURL(url);
$.ajax({
url : "uploadApi.php",
type: "POST",
data : {"videoThumb" : image},
success: function(data)
{
alert(data);
},
error: function (data)
{
alert(data);
}
});
console.info("image");
$('#b64image').val(image);
}
return success;
};
video.addEventListener('timeupdate', timeupdate);
video.preload = 'metadata';
video.src = url;
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
video.play();
};
fileReader.readAsArrayBuffer(file);
}
});
uploadApi.php
var_dump($_POST["videoThumb"];
$data = $_POST["videoThumb"];
$videoId = 1;
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$fileDirSrc = "../thumbs/"vid_".$videoId."_videoThumb.png";
$fileDirSrcNoTrailingDots = "vid_".$videoId."_videoThumb.png";
file_put_contents($fileDirSrc, $data);
Wierdly, the ajax response returns the dump of the base64image in an alert when on the desktop. But on iOS safari it returns [object Object]
You can try upload a video to his js fiddle, get an mp4 video file from http://techslides.com/sample-webm-ogg-and-mp4-video-files-for-html5 first.
https://jsfiddle.net/jvftb0gt/2/

how to covert base64 string to file object in javascript?

I have to convert a base64 encoded string to file object in java script so that i can pass that object to php and access that object by FILE variable.
Here is my code:
$(document).delegate(':file', 'change', function () {
files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
filenum = $(this).attr('data');
$("form#cropmodal #filenum").val(filenum);
var oMyForm = new FormData();
for (i = 0; i < files.length; i++) {
var ext = $("#ImgId" + filenum).val().split('.').pop().toLowerCase();
output_format = ext;
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('Invalid extension');
return false;
}
var mime_type = "image/jpeg";
if (typeof output_format !== "undefined" && output_format == "png") {
mime_type = "image/png";
}
var reader = new FileReader();
reader.readAsArrayBuffer(files[i]);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
//preview.appendChild(image);
// preview commented out, I am using the canvas instead
image.onload = function () {
// have to wait till it's loaded
var cvs = document.createElement('canvas');
cvs.width = image.naturalWidth;
cvs.height = image.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(image, 0, 0);
var newImageData = cvs.toDataURL(mime_type, 50 / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
var cvs = document.createElement('canvas');
cvs.width = result_image_obj.naturalWidth;
cvs.height = result_image_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(result_image_obj, 0, 0);
var type = "image/jpeg";
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var the_file = new Blob([window.atob(data)], {type: 'image/jpeg', encoding: 'utf-8'});
oMyForm.append("media[]", the_file);
oMyForm.append("_token", "{{ csrf_token() }}");
}
};
}
});
When i alert "the_file" it will show "Object Blob", but i need "Object File"
You can use like this:
base64 decode javascript

Categories

Resources