Showing posts with label Angularjs Image Crop. Show all posts
Showing posts with label Angularjs Image Crop. Show all posts

Angularjs Implement keyboard Shortcut keys

Angularjs Implement keyboard Shortcut keys


Hi Today discussed Angularjs implement keyboard shortcut keys.  Angularjs app submit form and goto another page used keyboard shortcut keys implemented used follows code.

Angularjs Implement keyboard Shortcut keys
Angularjs Implement keyboard Shortcut keys

Angularjs Implement keyboard first bower install or node_modules means npm install and then 

bower install chieffancypants/angular-hotkeys --save
if you used npm node_modules

use this

npm install angular-hotkeys --save

Refer Link: Click Here
Refer Link: Click Here


index.js include lib file.

$scope.submit1 = function(){  //$scope custom    })

  hotkeys.add({

    combo:'alt+s',
    description:'Save Unit Creation',
     allowIn: ['INPUT', 'SELECT', 'TEXTAREA','REQUIRED'],
  callback:function(){
$scope.submit1();

    }
  })

Angularjs WebCam Take Picture and decode base64

Angularjs WebCam Take Picture and decode base64

Today discussed Angularjs WebCam Take Picture and decode base64 image upload webcam and file upload encrypt blob type image decrypt method and image upload base64 encrypt method convert image decrypt and move folder follows code. try it.

Angularjs WebCam Take Picture and decode base64
Angularjs WebCam Take Picture and decode base64

webcam.html  html page
 <ng-camera capture-message="Cheeeese!"                                                    countdown="3"
      output-height="160"
     output-width="213"
      viewer-height="320"
       viewer-width="426"
          image-format="jpeg"
        jpeg-quality="100"
         action-message="Take picture"
       snapshot="vm.picture"
       flash-fallback-url="/vendors/webcamjs/webcam.swf"
       overlay-url="/overlay.png"
       shutter-url="img/shutter.mp3"></ng-camera>

Controller

(function (angular) {
    'use strict';

    angular.module('camera', []);

})(angular);

angular.module('camera');
app.controller('cameraController', controller);

controller.$inject = ['$scope'];

function controller($scope) {
    /* jshint validthis: true */
    var vm = this;

    vm.picture = false; // Initial state

    $scope.hshow = function (a) {
        alert(a);
    }
}




/* global Webcam */
(function (angular) {
    'use strict';

    angular.module('camera');
    app.directive('ngCamera', directive);

    directive.$inject = ['$q', '$timeout', 'photoManagerClient', '$stateParams'];

    function directive($q, $timeout, photoManagerClient, $stateParams) {
        var clientid = $stateParams.ClientID;
        return {
            'restrict': 'E',
            'scope': {
                'actionMessage': '@',
                'captureMessage': '@',
                'countdown': '@',
                'flashFallbackUrl': '@',
                'overlayUrl': '@',
                'outputHeight': '@',
                'outputWidth': '@',
                'shutterUrl': '@',
                'viewerHeight': '@',
                'viewerWidth': '@',
                'cropHeight': '@',
                'cropWidth': '@',
                'imageFormat': '@',
                'jpegQuality': '@',
                'snapshot': '='
            },

            'template': ['<div class="ng-camera">',
                '<div class="ng-camera-countdown" ng-if="countdown" ng-show="activeCountdown">',
                '<p class="tick">{{countdownText}}</p>',
                '</div>',
                '<div class="ng-camera-stack">',
                '<img class="ng-camera-overlay" ng-if="overlayUrl" ng-show="cameraLive" ng-src="{{snapshot}}" alt="overlay">',
                '<div id="ng-camera-feed"></div>',
                '</div>',
                '<button id="ng-camera-action" ng-click="getSnapshot()">{{actionMessage}}</button>',
                '</div>'].join(''),
            'link': link
        };

        function link(scope, element, attrs) {

            scope.libraryLoaded = false;
            scope.cameraLive = false;
            scope.activeCountdown = false;


            if (scope.viewerHeight === undefined) {
                scope.viewerHeight = 'auto';
            }
            if (scope.viewerWidth === undefined) {
                scope.viewerWidth = 'auto';
            }
            if (scope.outputHeight === undefined) {
                scope.outputHeight = scope.viewerHeight;
            }
            if (scope.outputWidth === undefined) {
                scope.outputWidth = scope.viewerWidth;
            }


            if (scope.cropHeight === undefined || scope.cropWidth === undefined) {
                scope.cropHeight = false;
                scope.cropWith = false;
            }

            Webcam.set({
                width: scope.viewerWidth,
                height: scope.viewerHeight,
                dest_width: scope.outputWidth,
                dest_height: scope.outputHeight,
                crop_width: scope.cropWidth,
                crop_height: scope.cropHeight,
                image_format: scope.imageFormat,
                jpeg_quality: scope.jpegQuality,
                force_flash: false
            });
            if (scope.flashFallbackUrl !== 'undefined') {
                Webcam.setSWFLocation(scope.flashFallbackUrl);
            }
            Webcam.attach('#ng-camera-feed');

            Webcam.on('load', function () {
                console.info('library loaded');
                scope.$apply(function () {
                    scope.libraryLoaded = true;
                });
            });
            Webcam.on('live', function () {
                console.info('camera live');
                scope.$apply(function () {
                    scope.cameraLive = true;
                });
            });
            Webcam.on('error', function (error) {
                console.error('WebcameJS directive ERROR: ', error);
            });

            if (scope.shutterUrl !== undefined) {
                scope.shutter = new Audio();
                scope.shutter.autoplay = false;
                if (navigator.userAgent.match(/Firefox/)) {
                    scope.shutter.src = scope.shutterUrl.split('.')[0] + '.ogg';
                } else {
                    scope.shutter.src = scope.shutterUrl;
                }
            }


            if (scope.countdown !== undefined) {
                scope.countdownTime = parseInt(scope.countdown) * 1000;
                scope.countdownText = parseInt(scope.countdown);
            }
            scope.countdownStart = function () {
                scope.activeCountdown = true;
                scope.countdownPromise = $q.defer();
                scope.countdownTick = setInterval(function () {
                    return scope.$apply(function () {
                        var nextTick;
                        nextTick = parseInt(scope.countdownText) - 1;
                        if (nextTick === 0) {
                            scope.countdownText = scope.captureMessage !== null ? scope.captureMessage : 'GO!';
                            clearInterval(scope.countdownTick);
                            scope.countdownPromise.resolve();
                        } else {
                            scope.countdownText = nextTick;
                        }
                    });
                }, 1000);
            };

            scope.getSnapshot = function () {

                if (scope.countdown !== undefined) {
                    scope.countdownStart();
                    scope.countdownPromise.promise.then(function () {
                        $timeout(function () {
                            scope.activeCountdown = false;
                            scope.countdownText = parseInt(scope.countdown);
                        }, 2000);

                        if (scope.shutterUrl !== undefined) {
                            scope.shutter.play();
                        }

                        Webcam.snap(function (data_uri) {
                            /*   function saveAs(uri, filename) {
                                   var link = document.createElement('a');
                                   if (typeof link.download === 'string') {
                                       console.log();
                                       link.href = uri;
                                       link.download = filename;
   
                                       //Firefox requires the link to be in the body
                                       document.body.appendChild(link);
   
                                       //simulate click
                                       link.click();
   
                                       //remove the link when done
                                       document.body.removeChild(link);
                                   } else {
                                       window.open(uri);
                                   }
   
                               }*/
                            scope.snapshot = data_uri;
                            //  var imageBase64 = data_uri;
                            //  var as = saveAs(imageBase64, 'as.png');
                            //   var image = new Image();
                            //   image.src = data_uri;
                            //  console.log(data_uri);

                            // alert(image);
                            //   var change = decodeBase64(data_uri);
                            // var blob = new Blob([imageBase64], { type: 'image/png' });
                            //  var file = new File([blob], 'imageFileName.png');
                            //  var photos = new File([blob], 'imageFileName.png');
                            var imageBase64 = data_uri;
                            //    var blob = new Blob([decodedImage], { type: 'image/png' });

                            ///now it should work properly
                            //  var photos = new File([blob], 'newname.png');
                            function dataURItoBlob(dataURI) {
                                // convert base64/URLEncoded data component to raw binary data held in a string
                                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 a typed array
                                var ia = new Uint8Array(byteString.length);
                                for (var i = 0; i < byteString.length; i++) {
                                    ia[i] = byteString.charCodeAt(i);
                                }

                                return new Blob([ia], { type: mimeString });
                            }
                            // var dataURL = data_uri.toDataURL('image/jpeg', 0.5);
                            var blob1 = dataURItoBlob(data_uri);
                            var blob2 = new Blob([blob1], { type: 'image/png' });
                            var blob = new File([blob2], 'image' + clientid + '.png');
                            //  var file = new File([blob], 'imageFileName.png');
                            //  var photos = new File([blob], 'imageFileName.png');
                            //  var fd = new FormData(document.forms[0]);
                            // fd.append("canvasImage", blob);
                            var formData = new FormData();

                            //   angular.forEach(imgData, function (imgData) {
                            //  alert('asdas');
                            //  console.log(imgData);
                            formData.append("canvasImage", blob);
                            //  });
                            return photoManagerClient.save(formData)
                                   .$promise


                        });
                    });
                } else {
                    if (scope.shutterUrl !== undefined) {
                        scope.shutter.play();
                    }

                    Webcam.snap(function (data_uri) {
                        scope.snapshot = data_uri;


                        var Image = scope.snapshot;
                        var st = { 'Image': Image };
                        var ss = JSON.stringify(st);
                        var postUrlna = '../api/Cameraaddimage';
                        $http.post(postUrlna, ss, {
                            transformRequest: angular.identity,
                            headers: { 'Content-Type': "application/json" }
                        }).then(function (result) {

                        });
                        //console.log(data_uri);
                    });
                }
            };

            scope.$on('$destroy', function () {
                Webcam.reset();
            });
        }
    }

})(angular);


Factory Image upload Api

app.factory('photoManager', photoManager);
photoManager.$inject = ['$q', 'photoManagerClient', 'appInfo', '$stateParams'];

function photoManager($q, photoManagerClient, appInfo, $stateParams) {
    var abc = $stateParams.ClientID;
    var service = {
        photos: [],
        load: load,
        upload: upload,
        remove: remove,
        photoExists: photoExists,
        status: {
            uploading: false
        }
    };

    return service;

    function load() {
        service.photos.length = 0;

        return photoManagerClient.query()
                            .$promise
                            .then(function (result) {
                                result.photos
                                        .forEach(function (photo) {
                                            service.photos.push(photo);
                                        });

                                appInfo.setInfo({ message: "photos loaded successfully" });

                                return result.$promise;
                            },
                            function (result) {
                                appInfo.setInfo({ message: "something went wrong: " + result.data.message });
                                return $q.reject(result);
                            })
                            ['finally'](
                            function () {
                                appInfo.setInfo({ busy: false });
                            });
    }

    function upload(photos) {
        console.log(photos);
        var formData = new FormData();

        angular.forEach(photos, function (photo) {
            console.log('photofsdfsdf');
            console.log(photo);
            formData.append(photo.name, photo);
        });
        return photoManagerClient.save(formData)
                                   .$promise
      
    }

    function remove(photo) {
        appInfo.setInfo({ busy: true, message: "deleting photo " + photo.name });

        return photoManagerClient.remove({ fileName: photo.name })
                                    .$promise
                                    .then(function (result) {
                                        //if the photo was deleted successfully remove it from the photos array
                                        var i = service.photos.indexOf(photo);
                                        service.photos.splice(i, 1);

                                        appInfo.setInfo({ message: "photos deleted" });

                                        return result.$promise;
                                    },
                                    function (result) {
                                        appInfo.setInfo({ message: "something went wrong: " + result.data.message });
                                        return $q.reject(result);
                                    })
                                    ['finally'](
                                    function () {
                                        appInfo.setInfo({ busy: false });
                                    });
    }

    function photoExists(photoName) {
        var res = false
        service.photos.forEach(function (photo) {
            if (photo.name === photoName) {
                res = true;
            }
        });

        return res;
    }
}
app.factory('photoManagerClient', photoManagerClient);

photoManagerClient.$inject = ['$resource', '$stateParams'];

function photoManagerClient($resource, $stateParams) {
    var clinetid = $stateParams.ClientID;
    //  alert('dsfsd');
    //sdafdsfds  console.log(clinetid);
    return $resource("../api/photo/:fileName",
           {
               id: "@fileName",
               id1: clinetid,
           },
           {
               'query': { method: 'GET' },
               'save': { method: 'POST', transformRequest: angular.identity, headers: { 'Content-Type': undefined } },
               'remove': { method: 'DELETE', url: '../api/photo/:fileName', params: { name: '@fileName' } }
           });
}

C# Linq Image move Local Folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using ss.Controllers.Models;
using ss.Controllers.Photo;
namespace ss.Controllers.Controllers
{
    [RoutePrefix("api/photo")]
    public class PhotoController : ApiController
    {
        private IPhotoManager photoManager;

        public PhotoController()
            : this(new LocalPhotoManager(HttpRuntime.AppDomainAppPath + @"\Customerimage"))
        {
     
        }

        public PhotoController(IPhotoManager photoManager)
        {
            this.photoManager = photoManager;
        }

        // GET: api/Photo
        public async Task<IHttpActionResult> Get()
        {
            var results = await photoManager.Get();
            return Ok(new { photos = results });
        }

        // POST: api/Photo
        public async Task<IHttpActionResult> Post()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                return BadRequest("Unsupported media type");
            }

            try
            {
              //  LaexDataContext lx = new LaexDataContext();
                var photos = await photoManager.Add(Request);
             /*   var a = "DFD";
                var sf = from l in lx.mCustomers where l.ClientID == 10371 select l;
                if (sf.Count() > 0)
                {
                    var de = sf.First();
                    de.NRIC1 = "ZZZ";
                    lx.SubmitChanges();
                }*/
                // string a1 = "update mcustomer set NRIC1='DASD' WHERE ClientID=10371";
                //   var b1 = lx.ExecuteQuery<mCustomer>(a1);
                return Ok(new { Message = "Photos uploaded ok", Photos = photos });
            }
            catch (Exception ex)
            {
                return BadRequest(ex.GetBaseException().Message);
            }

        }

        // DELETE: api/Photo/5
        [HttpDelete]
        [Route("{fileName}")]
        public async Task<IHttpActionResult> Delete(string fileName)
        {
            if (!this.photoManager.FileExists(fileName))
            {
                return NotFound();
            }

            var result = await this.photoManager.Delete(fileName);

            if (result.Successful)
            {
                return Ok(new { message = result.Message });
            }
            else
            {
                return BadRequest(result.Message);
            }
        }
    }
}



Angularjs Compress Image Before Upload

Angularjs Compress Image Before Upload



Angularjs Compress Image
Angularjs Compress Image

Angularjs  Uploading the image compressed method. AnguarJs Image Crop Click Here  Here Code But This method is very slow loading. try this

View.html

<div>
    <div class="rating-camera-icon">
        <input type="file" accept="image/*" name="file" ng-file-
         select="onFileSelect($files)">
    </div>
    <img ng-show="fileName" ng-src="server/{{fileName}}" width="40"
     style="margin-left:10px">
</div>


Controller.js

$scope.onFileSelect = function($files) {
        for (var i = 0; i < $files.length; i++) {
            var file = $files[i];
            if (!file.type.match(/image.*/)) {
                // this file is not an image.
            };
            $scope.upload = $upload.upload({
                url: BASE_URL + 'upload.php',
                data: {myObj: $scope.myModelObj},
                file: file
            }).progress(function(evt) {
                    // console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
                    // $scope.fileProgress = evt.loaded / evt.total * 100.0;
                }).success(function(data, status, headers, config) {
                    // file is uploaded successfully
                    $scope.fileName = data;
                });
        }
    };


Angularjs Image Compress is very slow load so another method is  Angularjs  Resize Image and Uploading.

// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();  
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
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);

var dataurl = canvas.toDataURL("image/png");

Angularjs Image Crop

A simply way to crop image using  Angularjs



Image Croping
Angularjs Image Crop


Angularjs Image Crop

Whenever we allowing a user upload image, it's better to provide cropping option for them.  Touch support, swipe to move and drag handle to zoom image. Output as a base64 encoded data Url
Uses HTML5 Canvas to display image in a flexible context, to allow dragging and zooming.
Angularjs

Try this following code

Style.css

.cropImage {
  background: #E4E4E4;
  overflow: hidden;
  width:500px;
  height:350px;
}


View.html

<body ng-app="app" ng-controller="Ctrl">
  <div>Select an image file: <input type="file" id="fileInput" /></div>
  <div class="cropImage">
    <img-crop image="myImage" result-image="myCroppedImage"></img-crop>
  </div>
  <div>Cropped Image:</div>
  <div><img ng-src="{{myCroppedImage}}" /></div>
</body>


Controller.js

angular.module('app', ['ngImgCrop'])
  .controller('Ctrl', function($scope) {
    $scope.myImage='';
    $scope.myCroppedImage='';

    var handleFileSelect=function(evt) {
      var file=evt.currentTarget.files[0];
      var reader = new FileReader();
      reader.onload = function (evt) {
        $scope.$apply(function($scope){
          $scope.myImage=evt.target.result;
        });
      };
      reader.readAsDataURL(file);
    };
    angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
  });