Image size validation - javascript

is it possible to validate file image size with jquery class orjavascript ?
Can i do that ? I made some research but did not reach anything
Thank you

If you want to check image file being uploaded on client side, check HTML5 File API. Here are some samples at:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can get file size, find it's type and access binary content.
I was using File API to read EXIF headers from image without uploading image to server.
Here is a source code:
https://gist.github.com/980275/85da4a96a3bb23bae97c3eb7ca777acdea7ed791

Try this:
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="Size()" />
Script:
function Size() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').fileSize;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}

Related

How do I show an uploaded image in Jquery? [duplicate]

This question already has answers here:
Preview an image before it is uploaded
(29 answers)
Closed 3 years ago.
<html>
<head><script src = "/jquery.js"></script></head>
Test Image Upload
<input type = "file" id = "chooseimage" name = "chooseimage" accept = ".jpg, .jpeg, .png" multiple><br>
<input type = "button" id = "submitimages" value = "Send Image">
<br>
<div id = "test"></div>
<script>
$("#submitimages").click(function(){
var imageinput = $("#chooseimage")[0].files[0];
var reader = new FileReader();
var a = reader.readAsDataURL(imageinput);
reader.onload = function(e)(){}; // what do i do with this?
$("#test").html(a);
});
</script>
</html>
For the Jquery, let me quickly run down my thought process.
1) I get the input id "chooseimage" and grab the files using .files command. I assume .files[0] means to select the first file from the HTML element (but it only selects it, not actually reading it)?
2) create a new FileReader(). I'm not quite sure what this does, I think it allows me to... read the file?
3) But to first read the file using FileReader, we need to convert the file to a base64 encoded string, so we use readAsDataURL to convert.
4) And then I do somrthing with reader.onload(), but I am not sure what this does. I was reading other tutorials on this and they all had it but no explanation what it does. I read the Mozilla Documentation but didn.t quite understand it. I've done nothing with it so far.
5) I want to show the base64 string in the div element with id "test". I think the browser will automatically interpret the string into an image. Either way, it's not showing anything.
Can someone walk me through what I do or do not understand correctly and what I'm doing wrong?
Check this out, and let me know how it goes. :)
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgPreview").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
<input type='file' id="imgPreview" />
<img id="imageShow" src="#" alt="your image" />
</form>

Get the image as file in angular

I am making angular application with image upload option which has the,
Html :
<label class="hoverable" for="fileInput">
<img [src]="url ? url : avatarImage">
<div class="hover-text">Choose file</div>
<div class="background"></div>
</label>
<br/>
<input id="fileInput" type='file' (change)="onSelectFile($event)">
<button *ngIf="url" (click)="delete()" >delete</button>
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
Here what i am having is if the user clicks over the image he can select and update whatever image he has in local.
Same way if the user was not interested to update the profile image but interested to select any of the avatar image as per his/her wish which i have given like,
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
And in ts made something like this,
uploadPersonaImage(e) {
this.url = e.target.src;
}
So on the click function the src that comes from the event.target was set to this.url..
But i need to convert it as file.. Because i need to send it as file to the service call so i need to update the avatar image.
So please help me to convert the avatar image selected/clicked by the user to the file/formdata so that it can be sent to the service as file format and can be updated as user selected image..
Example: https://stackblitz.com/edit/angular-file-upload-preview-85v9bg
You can use FormData to attach the read file and send to the API.
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
this.uploadToServer(event.target.files[0]);
... rest of the code
}
uploadToServer(file) {
let formData: FormData = new FormData();
formData.append('fileName', file);
// call your api service to send it to server, send formData
}
EDIT:
Try this out if you have no option to touch onSelectFile() or trigger a different function when you upload the file.
_url = ''
set url(val) {
this._url = val;
if (val) {
this.dataURLtoFile(val);
}
}
get url() {
return this._url;
}
uploadedImage: File ;
dataURLtoFile(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const imageExtension = mime.split('/')[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
this.uploadedImage = new File([u8arr], `uploaded.${imageExtension}`);
}
On your API call, maybe when you click on a button,
uploadPersonaImage(e) {
// this.apiService.someMethod(this.uploadedImage);
}
If you want to trigger the API call just when you upload the image, add the code of dataURLtoFile() to uploadPersonaImage() and call uploadPersonaImage() from url setter
Clarification
Do you understand what does event.target.src mean (considering e as event)?
Here event means the click/change event you triggered when you
clicked onto upload photo.
event.target means the DOM element on which the event took place.
event.target.src will give you the src attribute value of the
DOM element on which you triggered the change event.
Now, you say won't it work? No, it won't because the element which you clicked is an HTMLInputElement but the src resides under the image in under the label tag. And how are you intending to call uploadPersonaImage()? what calls your method? You haven't answered that even after asking so many times.
In my last edit, I have added code under the setter of the url which will convert the dataUrlFile to an actual File, It completely depends on your server how you want to store the file. As a file or as a dataUrl? If you want to send it as a file then follow the conversions I added in the answer if you want to save as dataUrl then directly save the content of this.url on your API call.

How to access image file from HTML or Javascript for Windows Phone

I have a requirement in wp8, where the picture selected by the user needs to be shown in the browser. To browse and select the photo, I am using photo chooser task.
I am able to get the physical location of the selected image, but on passing the same to JavaScript from c# its not displaying the image.
On googling came across the following link How to access isolated storage file from HTML or Javascript for Windows Phone and PhoneGap Application But it did not solve my issue.
For reference, the location of the image I am using was:
C:\Data\Users\DefApps\AppData{FA586990-6E21-0130-BF9E-3C075409010C}\Local\sample_photo_00.jpg
This is my Javascript code:
function myPicture(data) {
document.getElementById("capturedImage").src = data.imageUri;
alert("data.imageUri " + document.getElementById("capturedImage").src );
var width = data.imageWidth;
var height = data.imageHeight;
alert("image width" + width );
alert("image height" + height );
}
And this is my C# code:
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string[] picList = Directory.GetFiles(localFolder.Path, "*.jpg");
foreach (string DeleteFile in picList) {
File.Delete(DeleteFile);
}
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
send (storageFile.Path);
Now send function should add MyHTML in picture.
You can call JavaScript function from C# by WebBrowser.InvokeScript and send image in args parameter. But args is string(s), so you will have to encode your image to string using some algorithm... Base64 for example:
string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
return Convert.ToBase64String(stream.ToArray());
}
}
You will get some long string like this iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
On other side - in the JavaScript function you calling you will get that Base64 string and use it like this as src attribute of img element:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />
More info about data uri scheme.
UPDATE: The easer solution. I think you can send your image path, width and height:
ImageProperties properties = await storageFile.Properties.GetImagePropertiesAsync();
webBrowser.InvokeScript("myPicture", storageFile.Path, (string)properties.Width, (string)properties.Height);
function myPicture(src, width, height) {
document.getElementById("capturedImage").src = src;
alert("data.imageUri " + document.getElementById("capturedImage").src );
alert("image width" + width );
alert("image height" + height );
}

How to minimize requested image using jquery cropit plugin?

My code is cropping an image but cropped image is very large. I'm using the Cropit jQuery plugin.
My View has an div mask on the image. When the form post, the hidden input has cropped image through the following script.
<div class="image-editor" style="margin-left:120px; margin-bottom:25px; margin-top:25px;">
<input id="fileinput" type="file" name="filex" class="cropit-image-input">
<div class="cropit-image-preview" style="background-image:url()"></div>
<input type="range" class="cropit-image-zoom-input">
<input type="hidden" name="image-data" value="" class="hidden-image-data" />
<button type="submit" class="export">Crop</button>
</div>
<script>
$(function () {
$('.image-editor').cropit({});
$('.export').click(function () {
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
});
});
</script>
In my Controller Create function gets cropped image via Request and write to file but the new file is too large. For example, input file is 50kb and cropped output file is 600kb. Normally the cropped image must be smaller than input image. How to fix the problem?
[HttpPost]
public ActionResult Create()
{
var dataurl = Request["image-data"];
var data = dataurl.Substring(dataurl.IndexOf(",") + 1);
var newfile = Convert.FromBase64String(data);
var layoutfilename = Guid.NewGuid().ToString() + "_imgage.jpg";
var dataFile = Server.MapPath(#"~/Img/" + layoutfilename);
System.IO.File.WriteAllBytes(dataFile, newfile);
}
Looking at Cropit's source code, here's the relevant bit of code to the output data size:
Cropit.prototype.getCroppedImageData = function(exportOptions) {
var canvas, canvasContext, croppedSize, exportDefaults, exportZoom;
if (!this.imageSrc) {
return null;
}
exportDefaults = {
type: "image/png",
quality: .75,
originalSize: false,
fillBg: "#fff"
};
exportOptions = $.extend({}, exportDefaults, exportOptions);
This is the beginning of the function eventually called by cropit('export').
What's happened here is your input data's compression yields a smaller input than what a quality (7, 8, not sure here) PNG image would output.
You can specify options in the cropit() call - from the plugin's documentation:
$imageCropper.cropit('export', {
type: 'image/jpeg',
quality: .9,
originalSize: true
});

convert to base64 and send image using ajax in Javascript

I need to send selected image to the server, here is already I have tried
here is HTML part
<div class="row">
<input type="file" name="filUpload" id="filUpload" onchange="showimagepreview(this)">
<br />
<img id="imgprvw" alt="uploaded image preview" class="img-thumbnail" />
</div>
I need to get encoded image into javascript variable,But I have no idea
for uploading image on to server you need to send image data via AJAX to server side.
for reference you can see this link :
http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php
http://phppot.com/php/php-ajax-image-upload/
you can try using jquery's base64 plugin. Jquery.Base64 plugin
and do it like this:
function showimagepreview(c) {
var file = c;
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
var b = $.base64.encode(e.target.result);
$("#imgprvw").attr("src", "data:image/png;base64," + b);
};
reader.readAsBinaryString(file.files[0]);
}
}

Categories