Ok this is what I am trying to acchomplish, (As of Now)I have user select image and the image is resized and uploaded to server. What i would like to do is after the image is selected and resized then stop Script. Then i would like to create a function to upload resized image when i choose to. The reason is that i am going to add more inputs texts into my form and was user has finished completing I then want to upload image with the files. Note: I have not added the text inputs will do after just want to be able to sepearate the upload functions..I am not sure how to seperate the FormData post portion
JAVASCRIPT
<script>
function ResizeMe(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
dataurl = canvas.toDataURL("image/jpeg",.2);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
// Post the data
var fd = new FormData();
fd.append("image", files, uniq);
$.ajax({
url: 'http:///www.***/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
The code sending the formdata is
$.ajax({
url: 'http:///www.***/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
That code is the code that you will want to put in a separate function. To move it elsewhere, you have to make sure it still has access to all of the variables being sent, namely, fd. fd is connected to several variables, all leading back to canvas. You say that there will only be one canvas at a time, so we can make canvas a global variable, and then getting fd from anywhere will be easy.
<script>
//Moved to global so that sendFormStuff will see it
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
function ResizeMe(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
} // img.onload
}
function sendFormStuff() {
var dataurl = canvas.toDataURL("image/jpeg",.2);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
// Post the data
var fd = new FormData();
fd.append("image", files, uniq);
$.ajax({
url: 'http:///www.***/upload.php',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_input')[0].reset();
location.reload();
}
});
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
So really all we did here was move the request code into a separate function, and make canvas and ctx (which you were declaring twice, btw) accessible by that function.
Related
I have created a javascript function that compresses the JPEG image. It is working fine for JPEG files. But even user can upload xls,doc,pdf etc as well. So its breaking for any other files except JPG/JPEG. User can also upload other types of files as well. Only the JPG/JPEG needs to be compressed.
Else part is working perfectly fine. Need to fix the If part.
function OnClientFileSelected(radAsyncUpload, args) {
var old_uploadFile = radAsyncUpload._uploadModule._uploadFile;
var fileName = args.get_fileName();
var fileExtention = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
if (fileExtention.toLowerCase() != 'jpg' && fileExtention.toLowerCase() != 'jpeg') {
radAsyncUpload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
//return uploadFile;
var reader = new FileReader();
reader.readAsDataURL(uploadFile);
}
}
else {
radAsyncUpload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
var img = document.createElement("img");
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result
img.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var greaterDimension = 0;
var newPixelMultiplier = 1;
if (img.width > img.height)
greaterDimension = img.width;
else
greaterDimension = img.height;
if (greaterDimension > 1000) {
newPixelMultiplier = ((((greaterDimension - 1000) / 2) + 1000) / greaterDimension);
}
var MAX_WIDTH = img.width * newPixelMultiplier;
var MAX_HEIGHT = img.height * newPixelMultiplier;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function (blob) {
blob.lastModifiedDate = new Date();
blob.name = pair.file.name;
pair.file = blob;
old_uploadFile.call(this, pair)
}, 'image/jpeg', 0.6); //Set the Quality of Image...
}
}
reader.readAsDataURL(uploadFile);
}
}
}
It seems that the code for the resizing is from the following KB article: Preview uploaded image with RadAsyncUpload.
If that is the case, I can suggest that you that you keep the code as it is, or use it in the OnClientLoad event of the AsyncUpload control, as in your case it will be overridden on every file that is being selected.
Regarding your question in point, I can suggest you try to call the old_uploadFile as follows:
if (/*is not image condition here*/) {
old_uploadFile.call(radAsyncUpload, pair);
}
If the code from the KB is used, then it should be similar to this:
asyncupload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
if (/*is not image condition here*/) {
old_uploadFile.call(this, pair);
return;
}
// rest of code for resizing images here
}
I'm newbie in JS and React. I am using React and I have multiple file input in a form, I wish if the user select image the images should be resized and previewed before user click upload. Now the resizing, previewing and uploading are all fine, the problem is when I change a file input, the other file inputs preview and upload are all changed synchronously! any help will be appreciated.
This is the code:
render():
render(){
return(
...
<label>Image1
<input type="file" id="img1" on Change={this.handleChange} />
</label>
<br/>
<img id="img1_preview" src="" height="100" />
<label>Image2
<input type="file" id="img2" on Change={this.handleChange} />
</label>
<img id="img2_preview" src="" height="100" />
...
)
}
function():
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var canvas = document.createElement('canvas');
var max_size = 800; /* max size */
var width = image.width, height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) === -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[-1];
var raw = parts[1];
return new Blob([raw],{type:contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array],{type:contentType});
}
/* End Utility function to convert a canvas to a BLOB */
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
$(document).on("imageResized",function(event1){
if (event1.blob && event1.url) {
var blob = event1.blob, url = event1.url;
# set state, later will be submit to server
this.setState({[field]:blob});
/* preview */
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = url;
}, false);
reader1.readAsDataURL(blob);
/* end preview */
}
})
}
the page:
the page image
thanks #Kaiido, according to his advise, the problem has been solved(although I don't know the exact reason).
this is the working code:
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var canvas = document.createElement('canvas');
var max_size = 800; /* max size */
var width = image.width, height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
/* changed code */
canvas.toBlob(function(blob){
this.setState({[field]:blob});
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = dataUrl;
}, false);
reader1.readAsDataURL(blob);
});
/* end changed */
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
I have created a image select and resize (Client side) and upload to server. What I am asking for help is with image preview in iframe(resized) but cannot figure out. I will be only using Chrome desktop for this application. Qusetion is please help me with displaying resized image within my iframe here are my scripts below
HTML
<input type="file" input id="input" onchange="ClientSideResize()" name="Image" value="%%%img%%%"/>
HTML iframe
<img src="" id="image">
<iframe name="my_iframe" src="" id="my_iframe" style="visibility: hidden;"></iframe>
SCRIPT
<script>
function ClientSideResize(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
dataurl = canvas.toDataURL("image/jpeg",100);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "Sample"});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
Giving you a few other tips along the way... filereader is not the preferred way. and the way you build your blob afterwards is no good, use canvas#toBlob directly instead.
function ClientSideResize () {
// var uniq = 'id' + Date.now() // never used
var filesToUpload = document.getElementById('input').files
var file = filesToUpload[0]
// Create an image
var img = new Image
img.onload = () => {
const MAX_WIDTH = 200
const MAX_HEIGHT = 400
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var width = img.width
var height = img.height
// figure out new width and hight while keeping proportionally
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width
width = MAX_WIDTH
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height
height = MAX_HEIGHT
}
}
// set diminsion
canvas.width = width
canvas.height = height
// draw resized image
ctx.drawImage(img, 0, 0, width, height)
// get it as a blob
canvas.toBlob(blob => {
// Do something with blob
// let file = new File([blob], 'filename.png', {type: blob.type})
let iframe = document.querySelector('iframe')
iframe.contentWindow.postMessage(blob, '*')
}, 'image/jpeg', 100)
} // img.onload
img.src = URL.createObjectURL(file)
}
// on iframe
window.onmessage = event => {
console.log(event) // will contain your blob object
}
I want to upload a resized image to server, but I get "Required MultipartFile parameter 'file' is not present" error when I try to upload the resized image. When I upload the original file from there is no problem.
Script:
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function () {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function () {
var MAX_WIDTH = 200;
var MAX_HEIGHT = 200;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var data = new FormData();
data.append('file', dataURL);
$.ajax({
url: '/changeimage',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.alert("uploaded")
}
});
}
}
reader.readAsDataURL(file);
}
Server:
#RequestMapping(value = "/changeimage", method = RequestMethod.POST)
#ResponseBody
public String changeProfileImage(#Context HttpServletRequest request, #RequestParam("file") MultipartFile file) {
return "ok";
}
A data url is a string and will not upload as a file.
However you can use a blob instead
...
ctx.drawImage(this, 0, 0, tempW, tempH);
canvas.toBlob(function(blob){
var data = new FormData();
data.append('file', blob);
$.ajax({
url: '/changeimage',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.alert("uploaded")
}
});
});
...
I have a canvas that scales an image to fit inside of it, what I'm trying to do is export the image in a larger size than what the canvas is set to. I am using the canvas.toBlob method to get the blob data and am sending that to my server as an uploaded file.
For example, the canvas is 350px by 350px, I'd like to save the image as 800px by 1000px.
<canvas id="myCanvas" width="350" height="350"></canvas>
<script type="text/javasript">
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
var img_info = { width:527, height:350 };
var sourceX = 0;
var sourceY = 150;
var sourceWidth = 4520;
var sourceHeight = 3000;
var destWidth = img_info.width;
var destHeight = img_info.height;
var destX = canvas.width / 2 - destWidth / 2;
var destY = canvas.height / 2 - destHeight / 2;
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
imageObj.src = 'hhttp://i.imgur.com/tKplLLb.jpg';
canvas.toBlob(
function (blob) {
var formData = new FormData();
formData.append('file', blob);
jQuery.ajax({
url: "test.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (res) {
}
});
},
'image/jpg'
);
</script>
This function takes a canvas and width+height parameters. It will return a new canvas element on which you can call toBlob
function getResizedCanvas(canvas,newWidth,newHeight) {
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = newWidth;
tmpCanvas.height = newHeight;
var ctx = tmpCanvas.getContext('2d');
ctx.drawImage(canvas,0,0,canvas.width,canvas.height,0,0,newWidth,newHeight);
return tmpCanvas;
}
Working example here: http://jsfiddle.net/L4dua/