Uploading a cropped image not working CropperJs - javascript

I have 2 questions, i am working on a javascript script where i have the following code
<script type="text/javascript" >
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageId').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper(){
var image = document.getElementById('blah');
var cropper = new Cropper(image, {
aspectRatio: 1 / 1,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
//sending cropped image to server
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
path = 'C:/Users/Andy/Desktop/javascript/croppingwcropperjs/uploads';
$.ajax(path, {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
})
}
</script>
here is the html part of it
<! DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script name="jquery-croper-script">
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(require("jquery"),require("cropperjs")):"function"==typeof define&&define.amd?define(["jquery","cropperjs"],r):r(e.jQuery,e.Cropper)}(this,function(c,s){"use strict";if(c=c&&c.hasOwnProperty("default")?c.default:c,s=s&&s.hasOwnProperty("default")?s.default:s,c.fn){var e=c.fn.cropper,d="cropper";c.fn.cropper=function(p){for(var e=arguments.length,a=Array(1<e?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];var u=void 0;return this.each(function(e,r){var t=c(r),n="destroy"===p,o=t.data(d);if(!o){if(n)return;var f=c.extend({},t.data(),c.isPlainObject(p)&&p);o=new s(r,f),t.data(d,o)}if("string"==typeof p){var i=o[p];c.isFunction(i)&&((u=i.apply(o,a))===o&&(u=void 0),n&&t.removeData(d))}}),void 0!==u?u:this},c.fn.cropper.Constructor=s,c.fn.cropper.setDefaults=s.setDefaults,c.fn.cropper.noConflict=function(){return c.fn.cropper=e,this}}});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css" />
</head>
<body>
<input type="file" name="image" id="image" onchange="readURL(this);"/>
<div class="image_container">
<img id="imageId" src="#" alt="your image" />
</div>
<div id="cropped_result"></div>
<button id="crop_button">Crop</button>
</body>
</html>
Okay. with the code above i intent to crop an image and save the cropped version in my a folder named uploads. I have managed to crop the image however i couldnt save the cropped image. My question are :
what should be the path format in order to successfully commit the cropped image into an upload folder?
i have seen some creating a php script for path like uploads.php is it mandatory for the path to be a script in php.

Related

single and multiple file upload

I'm facing issue. single and multiple file uploaded file. Then multiple file upload successfully but when single file one by one upload then last one upload other are override by last one. Please help me to find out this problem solution. As you can see below code it's work properly for multiple upload file and send data by ajax then get array value all images but when upload single upload one by one then last one image data get only in ajax data in. please help me to provide me solution.
index.php
`
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
</style>
<body>
<form id="myForm" method="post">
<input type="file" id="files" class="file_uploader_file" name="files[]" multiple="true" accept="image/*" />
<p class="validateError" id="imgerror" style="color:red;display:none;">Please select your design.</p>
<input type="button" id="fees_stream_submit1" name="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
(function () {
$(document).on('click', '#fees_stream_submit1', function (e) {
var myfiles = document.getElementById("files");
// var myfiles = $('#files').val();
var files = myfiles.files;
var form = new FormData();
alert(files.length);
for (i = 0; i < files.length; i++) {
form.append('file' + i, files[i]);
}
$.ajax({
url: "fileuploadmultidata.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function (result) {
// alert(result);
}
});
});
})();
$(document).ready(function () {
var imgCnt = 0;
var onebyoneImg = [];
var countImg = 1;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
// var f = new File([""], files[i]);
var fileReader = new FileReader();
fileReader.onload = (function (e) {
imgCnt++;
alert(imgCnt);
var file = e.target;
$("<span class='pip'><div class=\"file_uploaded_view img-thumb-wrapper image-preview-height\">" +
"<img class=\"img-thumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\" style='heigh:100px;width:100px'/>" +
"<br/><span class='remove'><i class='fa fa-trash'></i></span></span>" +
"</div>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".img-thumb-wrapper").remove();
imgCnt--;
});
});
fileReader.readAsDataURL(f);
}
console.log(f);
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
</body>
</html>
`
**fileuploadmultidata.php**
`<?php
echo "<pre>";
print_r($_FILES);die();
?>`
The behaviors of file uploading will be like that only see https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
To achieve your requirement you need to store file values in variable and use.
var storeMultiFiles = [];
var file = $(file_id)[0].files;
for(var l=0; l<file.length; l++){
var fileData = file[l];
(function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(oFREvent){
storeMultiFiles.push(oFREvent.target.result)
};
})(fileData);
}
Use files details using "storeMultiFiles" for show, save, update and delete for selected.

html2canvas iframe and image capture and save to server

I want to save the screenshot to server when click on div on page. It's a few problems. I'm rookie. Please help.
1)The picture is being saved but also shown at the bottom of the page. just want to be saved.
2)This is the most important. page contains iframe and image files. my main goal is to take images of them. but I was not successful. please help.
my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="mydiv">
here is iframe
</div>
<div>
bla bla bla
image
</div>
<script type="text/javascript" src="html2canvas.js"></script>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var mydiv = document.getElementById('mydiv');
mydiv.style.cursor = 'pointer';
mydiv.onclick = function () {
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
});
};
mydiv.onmouseover = function() {
this.style.backgroundColor = 'white';
};
mydiv.onmouseout = function() {
this.style.backgroundColor = '';
};
</script>
</body>
</html>
please edit the code for me. how it works the way I want.
ajaxfile.php I have no problem with this
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);

Convert the html into image , and save it ?(use html2canvas.js)

I have a big problem,
please help me !
This is my code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.1.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="jquery.plugin.html2canvas.js"></script>
<script type="text/javascript">
$(function() {
$("#show_button").click(function() {
html2canvas(document.body, {
onrendered: function(canvas) {
$("<img/>", {
id: "image",
src: canvas.toDataURL("image/png"),
width: '95%',
height: '95%'
}).appendTo($("#show_img").empty());
}
});
});
});
</script>
</head>
<body>
<h1>test</h1>
<button id="show_button">Show Image</button>
//this is a problem
download
<div id="show_img"></div>
</body>
</html>
If my viewpoint is correct .
To save image,the download need the correct file path and file name.
And i use the html2canvas.js , convert the target into image .
But when i want to save the image , i don't know the correct file path and file name.(Because the image is dynamic file ,not a static file?)
How can i get the correct value to save this image?
Thank you!
OK, I've discovered canvas2image.js that does what you need with this function
downloadPNG = function () {
html2canvas(document.body, {
onrendered: function (canvas) {
Canvas2Image.saveAsPNG(canvas);
}
});
}
Here is a fiddle
http://jsfiddle.net/link2twenty/w8Lk3znf/
Use html2canvas it will convert html to canvas and use canvas2image packages to convert canvas to image (or) you can pass canvas data .toDataURL("image/png");
example:
var imagename = '<YOUR_IMAGE_NAME>';
var link = event.target;
var canvasData = '<YOUR_CANVAS_DATA>'.toDataURL("image/png");
downloadImageFormat(link, canvasData, imagename);
function downloadImageFormat(link, canvasData, imagename) {
link.href = canvasData;
link.download = imagename;
}
Here is fiddle demo
Just Use html2canvas library just include plugin and call method to convert HTML to Canvas then download as image PNG
html2canvas(document.getElementById("image-wrap")).then(function(canvas) {
var link = document.createElement("a");
document.body.appendChild(link);
link.download = "manpower_efficiency.jpg";
link.href = canvas.toDataURL();
link.target = '_blank';
link.click();
});
Source: http://www.freakyjolly.com/convert-html-document-into-image-jpg-png-from-canvas/

How to create file on iphone using phonegap2.0

I am new to iphone and phonegap also. Now i want to create file in iphone using phonegap. I followed the below link:
"http://docs.phonegap.com/en/2.0.0/cordova_file_file.md.html#File"
In this link there is one html file with javascript. So i followed the coding. When i run that coding i got the output only in html tag content.
I have attach that coding with my output.
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>![enter image description here][1]
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(error) {
console.log(error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
"TestPhonegapApp[9589:707] CDVPlugin class CDVDevice (pluginName: Device) does not exist.
2012-09-11 12:02:13.719 TestPhonegapApp[9589:707] ERROR: Plugin 'Device' not found, or is not a CDVPlugin. Check your plugin mapping in Cordova.plist.
2012-09-11 12:02:13.722 TestPhonegapApp[9589:707] FAILED pluginJSON = {"className":"Device","methodName":"getDeviceInfo","arguments":["Device1"]}"

Displaying the content of a file with jQuery and HTML5 file API

I am trying to use the HTML5 file API and jQuery to show the content of a file, but it is not working. I am really new to jQuery, so the problem is probably with my code.
Here is the code I'm using:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
</head>
<body>
<input type="file" id="file" /> </br>
<textarea id="list"></textarea> </br>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
alert("Si esta soportado el API!");
} else {
alert('The File APIs are not fully supported in this browser.');
}
var manejarArchivos = function(archivo) {
var reader = new FileReader();
reader.onload = function(event) {
var content = event.target.result;
alert(content);
};
reader.readAsText(archivo);
}
try {
$('#file').change(function() {
manejarArchivos(this.files);
});
}
catch (e) {
alert(e);
}
</script>
</body>
</html>
How can I get this block of code to display the contents of my archivo file?
In your code archivo is a FileList, not a File. You should do something like:
reader.readAsText(archivo[0]);
instead of
reader.readAsText(archivo);

Categories