Force image orientation angularjs - angularjs

I have this odd behavior when I upload an image and if this image size has more height than with I get the image rotated 90 degrees.
check this fiddle that's using ngImgCrop and this is the image that I'm uploading
the code of the ngDmgCrop it's pretty standard:
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);
});
how can I fix this behavior?

You'll have to parse the exif data in the image header, examine the Orientation tag, and rotate accordingly.
I just solved the same problem with this library: Javascript Load Image
In your app.js
var handleFileSelect = function(evt) {
var target = evt.dataTransfer || evt.target;
var file = target && target.files && target.files[0];
var options = {canvas:true};
var displayImg = function(img) {
$scope.$apply(function($scope){
$scope.myImage=img.toDataURL();
});
}
loadImage.parseMetaData(file, function (data) {
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file, displayImg, options );
});
};
Demo : Plunker
Cheers.

Related

AngularJS simple image preview on file input

Can someone tell me why this code does not work?
this my preview area: <div class="preview"><img src="" alt=""></div>
and this my input:<input type="file" file-input> and follow my directive code:
var cmos = angular.module('cmos', ['simditor']);
// controller
cmos.controller('cmosCtrl', function( $scope ){}
// directive
cmos.directive("fileInput", function( $parse ){
return{
link: function($scope, element, attrs){
element.on('change', function(event){
var files = event.target.files;
var reader = new FileReader();
var img = document.querySelector(".preview > img");
reader.addEventListener("load", function(){
img.src = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}
// console.log(files[0]);
});
}
}
});
When I insert an image on input would like to take an image and show it to preview area.
you can use $scope like this..
<div class="preview"><img src="{{imageUrl}}" alt=""></div>
and in js.
var files = event.target.files;
var reader = new FileReader();
reader.addEventListener("load", function(){
$scope.imageUrl = reader.result;
}, false);
if(files){
reader.readAsDataURL(files[0]);
}

Unable to get $scope variables inside the fileReader.onload function

I am using something like this in angular
app.controller('techiesClub', function($scope, $http) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.asdf = "ankur";
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent, ss) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad, $scope);
}
}
});
Using uploadImage method on onchange of a input like this
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage()">
I am unable to get the srcData i.e. the base64 data into a variable that i can use else where.
Ankur,
We can rewrite html in this way.
<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage(this);">
JS snippet here.. i'm trying with Blob version.
$scope.uploadImage = function ($event) {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = $event.files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var _ULR = window.URL || window.webkitURL;
var img = new Image();
img.onload = function() {
var srcData = this.src; // <--- data: blob
$scope.asdf = srcData; //////////////////NOT WORKING
};debugger;
img.src =_ULR.createObjectURL(fileToLoad);
}
}
I think you are missing the key point in your solution. I just change the way you are accessing the base64 contents. It should work.
$scope.uploadImage = function () {
alert($scope.asdf); ////////////WORKS WELL
var filesSelected = document.getElementById("upload").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileReader.result; // <--- data: base64
$scope.asdf = srcData; //////////////////NOT WORKING
}
debugger;
fileReader.readAsDataURL(fileToLoad);
}
}

Collect Images from Local Server(Acquia Dev Desktop)

I am try to collect data and images from local server (Acquia Dev Desktop) using this Angular Js code
controller
var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $http) {
$scope.images = [];
$http({
method : "GET",
url : 'http://docroot.com.dd:8083/catalogue/11/images/json'
}).then(function mySucces(response) {
$scope.images = response.data;
}, function myError(response) {
$scope.images = response.statusText;
});
});
Json
[{"image":" <a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>"}]
// i got out put like this :
<a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>
i need to collect only image url instead of the whole link ,
Well, sending HTML elements in a JSON doesn't seem good to but, anyway if you cannot change it...
For my part, I would parse the html string with the built-in XML parser.
Here is the code taken from this answer
//XML parser
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
//should work with any recent browser
return ( new window.DOMParser()).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
//This part is intended to very old browsers
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
//Your code
var jsonContent= [{"image":" <a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>"}];
var elem = jsonContent[0].image;
var link = parseXml(elem);
try {
document.getElementById("out").innerHTML = link.documentElement.getAttribute("href");
} catch (e) {
alert(e);
}
<span id="out" />

Ionic/Cordova. Save image to photo gallery

I have a URLs to external PNG images. I want to download it directly to Camera Roll (iOS) or Photo Gallery(Android). How I can manage it with Ionic
try this:
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add cordova-plugin-file
add file link in index.
<script src="js/ng-cordova.js"></script>
<script src="js/FileTransferController.js"></script>
in controller:
$scope.downloadFile = function() {
var url = "http://your_ip_address/images/my.png";
var filename = url.split("/").pop();
alert(filename);
var targetPath = cordova.file.externalRootDirectory + filename;
var trustHosts = true
var options = {};
alert(cordova.file.externalRootDirectory);
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
alert(JSON.stringify(result));
}, function(error) {
// Error
alert(JSON.stringify(error));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}
From HERE
hope its helpful to someone.

Markers click events are not working in mobile device

I have created google maps for Nearby food courts. In this markers are displayed in browser and clickable and giving info window data.But same thing coming to mobile, markers are displayed and when am clicking the marker(tap the marker) info window data is not displayed.I tried with so many forums and changes lot of code and debug but i couldn't find the solution.
foodFactory.js
var foodModule = angular.module('foodModule', []);
foodModule.factory("foodFactory", ['$rootScope', '$window','foodServices', 'localStorageService', '$state', '$ionicLoading','$stateParams',
function($rootScope, $window, foodServices, localStorageService, $state, $ionicLoading, $stateParams, $cordovaGeolocation ) {
var foodCourtmap = {};
var marker = {};
var directionsDisplay = new google.maps.DirectionsRenderer({'draggable': true });
var directionsService = new google.maps.DirectionsService();
foodCourtmap.centerOnMe = function() {
initialize();
};
//intialze the google map it's show current location.
function initialize() {
var infowindow = new google.maps.InfoWindow();
navigator.geolocation.getCurrentPosition(function(pos) {
foodCourtmap.latitude = pos.coords.latitude;
foodCourtmap.longitude = pos.coords.longitude;
var site = new google.maps.LatLng( foodCourtmap.latitude, foodCourtmap.longitude);
var currentmapOptions = {
center: site,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//current location address based on Latitude and Longitude
var lat = parseFloat(foodCourtmap.latitude);
var lng = parseFloat(foodCourtmap.longitude);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var contentString = "Location: " + results[1].formatted_address;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Current Location'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
}
});
var map = new google.maps.Map(document.getElementById("food_map_canvas"), currentmapOptions);
// Places
var request = {
location:site,
radius: '5000',
name: ['restaurent']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
else
{
alert('No results found');
}
}
var image = new google.maps.MarkerImage('img/Restaurant.png');
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
title: place.name+","+place.vicinity,
position: place.geometry.location,
icon:image
});
var contentString = place.name+","+place.vicinity;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
foodCourtmap.map = map;
});
};
$rootScope.createFoodCourt = function() {
foodCourtmap.centerOnMe();
}
return {
init: function() {
foodCourtmap.centerOnMe();
return foodCourtmap;
}
};
}
]);
food.html
<ion-view>
<ion-content scroll="false">
<div id="food_map_canvas" data-tap-disabled="true" style="float:right;width:100%; height:100%"></div>
</ion-content>
</ion-view>
So please anyone help in these regards.
The mousedown event was an improvement, however, on iOS the events still fired intermittently for me. After more investigation I found a solution that works 100% of the time by setting optimized: false when creating the marker in addition to using the mousedown event.
E.g.
var newMarker = new google.maps.Marker({
position: latLong,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
optimized: false
});
https://code.google.com/p/gmaps-api-issues/issues/detail?id=3834
I had the same issue. The problem was 'click' event is not triggering when we touch on the mobile screen. So I changed to 'mousedown' event. Now I am able to add markers

Resources