I am using leaflet with openstreetmaps to generate a map on Ext js panel.
As maps are coming as tiles in openstreet maps, I need to combine these tiles to create a single image in order to save as an image .
You can save a Leaflet Map as a PNG file by using this resource
Saving a Leaflet Map to a PNG Example using Javascript and PHP
I do this using the so called Tile Stitching method (server side). Steps are:
On the client side collect all the tile images in your document, for example using jQuery you could do:
$('[class^="leaflet-tile leaflet-tile-loaded"]')
That will give you an array with all the img elements of the tiles for your map.
get the width and height, x and y, and the url of the images and put in a data structure of your liking
send the data structure to a function on your server that will retrieve the urls and stitch the images together using the x,y,width,height attributes.
I got the idea from this article used with openlayers: http://trac.osgeo.org/openlayers/wiki/TileStitchingPrinting. In the article you will find a working php example. Using the information above the javascript portion for Leaflet should not be difficult.
This seems to work for me:
http://www.yncoder.com/save-leaflet-map-as-image/
var images = container.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].setAttribute('crossOrigin', 'anonymous');
images[i].src = images[i].src;
}
var canvas = document.getElementById('dumb');
var context = canvas.getContext('2d');
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
for (i = 0; i < images.length; i++) {
if (typeof images[i] != 'undefined') {
context.drawImage(images[i],
images[i].style.left.slice(0, -2), // slice off 'px' from end of str
images[i].style.top.slice(0, -2),
images[i].clientWidth,
images[i].clientHeight
);
}
}
window.open(canvas.toDataURL());
Related
I'm creating the the image cropper by using fengyuanchen cropper library it is work as well but I want to use it for multiples images as the below screenshot But it'm simply difficult for me to reinitialize this plugin because it support only one avata images.
CropperJs supports that feature.
You can do it in javascript like this:
<script>
window.addEventListener('DOMContentLoaded', function () {
var images = document.querySelectorAll('img');
var length = images.length;
var croppers = [];
var i;
for (i = 0; i < length; i++) {
croppers.push(new Cropper(images[i]));
}
});
</script>
This code snippet could be found on the official Github repository
https://github.com/fengyuanchen/cropperjs/blob/35c6ce5bc345317c1acfb39e1ceab8af6dee1247/examples/multiple-croppers.html
I am fetching contacts from phone along with their images in phonegap.I have to save those images to my local database in Base64 or byte-array, So that later i can send those data to server also.
I am able to convert image into Base64 but this process is synchronous.
Let suppose i have 10 Contacts in my phone in which 5 contacts have image and rest has not.
so when i am applying loop for saving those images,so that time contacts who have images takes time to change images to Base64 mean while contacts who doesn't have images store in database because for these 5 contacts no need to change image to Base64.
So only 5 contacts get inserted in database and i get the Base64 of those 5 contacts after completing the loop.
I want that in loop untill i get the Base64 of any image, loop index should not increase by 1. As i get the Base64 of image after that i should move to next index.
This is the method which i am using for Converting any image to Base64.
function convertImgToBase64(url, callback, outputFormat){
alert(url);
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
//alert("URL "+url);
//alert("dataURL " + dataURL);
alert(dataURL);
callback.call(this, dataURL);
// Clean up
canvas = null;
};
img.src = url;
}
Can anyone please help me.
this is a post I have made on the adobe forum...
I'm newish to flash and i'm doing a presentation as part of a University assignment.
My problem is basically this. As part of my presentation I have a photo gallery which uses thumbnail images as buttons and then a UI loader to load a pop up version of the larger image from my webserver - as per https://www.youtube.com/watch?v=Peo_nT9HHa0
The image was created on photoshop. It is a .jpg and has text within the image that describes underneath it what the image is all about. The text within photoshop is set to anti-aliasing 'smooth' and when I test the movie within flash, the text underneath the image looks fine - just as it does in photoshop.
However, when I publish and upload the .swf file to my webserver and view the image through a browser, the text looks awful - all jaggy and broken if that makes sense.
Any ideas why?
I was given a reply of...
If you are loading the images dynamically then you will have to set the smoothing property true after the file(s) has been loaded. So if you don't currently have a listener for the images finishing loading, you will need one, and an event handler function to assign the smoothing property to true for each of them.
Can anyone help with creating the actionscript for this listener and event handler function?
I basically have a gallery movie clip with buttons that act as clickable thumbnails. The actionscript for that is...
btnImage1.addEventListener(MouseEvent.CLICK, loadimage1);
function loadimage1 (event:MouseEvent):void{
imagetxt.text = "a";
togglewindow.gotoAndPlay(2)
}
and then a UI loader that displays the larger image when a thumbnail is clicked
if (MovieClip(this.parent).imagetxt.text == "a"){
var imgurl:String ="IMAGE URL";
var myrequest:URLRequest = new URLRequest(imgurl);
myloader.load(myrequest);
}
As indicated, you should always turn smoothing on if the image is going to be scaled at all. It uses a different scaling algorithm that blurs pixels rather than deletes them. Take note that it is substantially slower to smooth, but on modern machines you shouldn't notice the difference unless you are doing it to thousands of images all at once.
After instantiation, add a Event.COMPLETE handler to Loader.contentLoaderInfo.
var myLoader = new Loader();
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
Then in the handler, you can access the Bitmap and turn smoothing on.
function loaderCompleteHandler(e:Event):void {
var image:Bitmap = myLoader.content as Bitmap; //Loader.content is typed as a DisplayObject, so we need to cast it as a Bitmap
image.smoothing = true;
}
And that should solve the issue. You may need to add the image object to the stage rather than the myLoader object. I don't think you'll have to, but I can't remember.
Just add event an event listener to your loader. Like this:
load.addEventListener(Event.COMPLETE,doneLoad);
then in the doneLoad function get the event.data and cast it to Bitmap and set the bitmap smoothing to true:
var myBitmap:Bitmap= e.target.data as Bitmap;
myBitmap.smoothing=true;
//add bitmap to parent ....
I wrote you universal method for loading images, you should pass 3 arguments to the method: holder for big images, image path, and rectangle to restrict image bounds and resize them. This method should be sufficient for your task.
private function loadImage(holder:DisplayObjectContainer, path:String, bounds:Rectangle):void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function (e:Event):void {
var bitmap:Bitmap = loader.content as Bitmap;
if (bitmap != null) {
bitmap.smoothing = true;
//Resize bitmap to fit bounds
var availableRatio:Number = bounds.width / bounds.height;
var componentRatio:Number = bitmap.width / bitmap.height;
if (componentRatio > availableRatio) {
bitmap.width = bounds.width;
bitmap.height = bounds.width / componentRatio;
} else {
bitmap.width = bounds.height * componentRatio;
bitmap.height = bounds.height;
}
//Clear previous
var i:uint, len: uint = holder.numChildren, old: Bitmap;
for(i; i < len; ++i){
old = holder.removeChildAt(0) as Bitmap;
old.bitmapData.dispose();
}
//Here you can add some appear animation
bitmap.x = bounds.x + ((bounds.width - bitmap.width) >> 1);
bitmap.y = bounds.y + ((bounds.height - bitmap.height) >> 1);
holder.addChild(bitmap);
}
});
loader.load(new URLRequest(path));
}
Usage:
loadImage(myContainer, "Path-to-Image", new Rectangle(20, 20, 400, 200));
I'm trying to allow users to upload images and then store the images, base64 encoded, in firebase. I'm trying to make my firebase structured as follows:
|--Feed
|----Feed Item
|------username
|------epic
|---------name,etc.
|------images
|---------image1, image 2, etc.
However, I can't get the remote data in firebase to mirror the local data in the client. When I print the array of images to the console in the client, it shows that the uploaded images have been added to the array of images...but these images never make it to firebase. I've tried doing this multiple ways to no avail. I tried using implicit syncing, explicit syncing, and a mixture of both. I can;t for the life of me figure out why this isn;t working and I'm getting pretty frustrated. Here's my code:
$scope.complete = function(epicName){
for (var i = 0; i < $scope.activeEpics.length; i++){
if($scope.activeEpics[i].id === epicName){
var epicToAdd = $scope.activeEpics[i];
}
}
var epicToAddToFeed = {epic: epicToAdd, username: $scope.currUser.username, userImage: $scope.currUser.image, props:0, images:['empty']};
//connect to feed data
var feedUrl = "https://myfirebaseurl.com/feed";
$scope.feed = angularFireCollection(new Firebase(feedUrl));
//add epic
var added = $scope.feed.add(epicToAddToFeed).name();
//connect to added epic in firebase
var addedUrl = "https://myfirebaseurl.com/feed/" + added;
var addedRef = new Firebase(addedUrl);
angularFire(addedRef, $scope, 'added').then(function(){
// for each image uploaded, add image to the added epic's array of images
for (var i = 0, f; f = $scope.files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
$scope.added.images.push(filePayload);
};
})(f);
reader.readAsDataURL(f);
}
});
}
EDIT: Figured it out, had to connect to "https://myfirebaseurl.com/feed/" + added + "/images"
I'm generating street view static images like so:
https://maps.googleapis.com/maps/api/streetview?size=1080x400&location=%s&fov=90&heading=235&pitch=0&key=%s
If you visit that link you see an image that says, "Sorry, we have no imagery for this..."
Is there any way to detect this "sorry" state so that I can fall back to another image?
One quick solution would be to load the image file using xmlrpc and check that its md5sum is 30234b543d5438e0a0614bf07f1ebd25, or that its size is 1717 bytes (it's unlikely that another image can have exactly the same size), but that's not very robust since I have seen Google change the position of the text in the image. Though it's a very good start for a prototype.
You could go for image processing instead. Note that it's still not perfectly robust since Google could decide to change the looks of the image anytime. You'll have to decide whether it's worth it.
Anyway, here is how I would do it using jQuery:
load the image and open a 2D context for direct pxiel access (see this question for how to do it)
analyse the image:
sample groups of 2×2 pixels at random locations; I recommend at least 30 groups
a group of 2×2 pixels is good if all the pixels have the same value and their R/G/B values do not differ by more than 10% (ie. they're grey)
count the ratio of good pixel groups in the image
if there are more than 70% good pixel groups, then we are pretty sure this is the “no imagery” version: replace it with another image of your choice.
The reason I do not recommend testing directly for an RGB value is because JPEG decompression may have slightly different behaviours on different browsers.
this situation is already build in in the 3.0 version due
the boolean test status === streetviewStatus.Ok, here is a snippet from my situation solving
if (status === google.maps.StreetViewStatus.OK) {
var img = document.createElement("IMG");
img.src = 'http://maps.googleapis.com/maps/api/streetview?size=160x205&location='+ lat +','+ lng +'&sensor=false&key=AIzaSyC_OXsfB8-03ZXcslwOiN9EXSLZgwRy94s';
var oldImg = document.getElementById('streetViewImage');
document.getElementById('streetViewContainerShow').replaceChild(img, streetViewImage);
} else {
var img = document.createElement("IMG");
img.src = '../../images/ProfilnoProfilPicture.jpg';
img.height = 205;
img.width = 160;
var oldImg = document.getElementById('streetViewImage');
document.getElementById('streetViewContainerShow').replaceChild(img, streetViewImage);
}
As of 2016, you can use the new Street View Image Metadata API.
Now you just need the status field to know if a panorama is found.
Example requests:
https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=78.648401,14.194336&fov=90&heading=235&pitch=10&key=YOUR_API_KEY
{
"status" : "ZERO_RESULTS"
}
https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=eiffel%20tower,%20paris,%20france&heading=-45&pitch=42&fov=110&key=YOUR_API_KEY
{
...
"status" : "OK"
}
You can use the getPanoramaByLocation function (see http://code.google.com/apis/maps/documentation/javascript/services.html#StreetViewService).
try something like this:
function handleMapClick()
{
var ll= new google.maps.LatLng(latitude,longitude);
sv.getPanoramaByLocation(ll, 50, processSVData);
}
function processSVData(data, status) {
if (status==google.maps.StreetViewStatus.ZERO_RESULTS)
{
<DO SOMETHING>
}
}
Request a google street view image and if it has a specific file size it is a 'Not street view avaible'. I did the follwing:
var url = 'google street view url';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
try {
var image = new Blob([this.response], {type: 'image/jpeg'});
if (image.size) {
if (url.indexOf('640x640') > -1 && image.size === 8410) {
// Not street view
}
if (url.indexOf('400x300') > -1 && image.size === 3946) {
// Not street view
}
}
} catch (err) {
// IE 9 doesn't support blob
}
}
};
xhr.send();
Another way is to load the image and then compare some pixels colors. The "no streetview" image from google is always the same. Here is how you would compare 2 pixels:
var url = STREETVIEWURL
var img = new Image();
// Add some info to prevent cross origin tainting
img.src = url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '');
img.crossOrigin = "Anonymous";
img.onload = function() {
var context = document.createElement('CANVAS').getContext('2d');
context.drawImage(img, 0, 0);
//load 2 pixels. I chose the first one and the 5th row
var data1 = context.getImageData(0, 0, 1, 1).data;
var data2 = context.getImageData(0, 5, 1, 1).data;
console.log(data1);
// google unknown image is this pixel color [228,227,223,255]
if(data1[0]==228 && data1[1]==227 && data1[2]==223 && data1[3]==255 &&
data2[0]==228 && data2[1]==227 && data2[2]==223 && data2[3]==255){
console.log("NO StreetView Available");
}else{
console.log("StreetView is Available");
}
};
Some potential issues:
I've seen some errors with CrossOrigin tainting. Also, if google changes the image returned this code will break.