Longitude is always zero in image meta data - ios

I am taking a photo using a MediaPicker in Xamarin. I start the geolocation service and then once the picture is taken I send the byte array of the image and the position information to my own platform specific implementation to add the position information in the meta data of the image.
I then save the image as a file and then email it to myself so I can open it in an external application (Picasa) to ensure the GPS information has been stored properly.
The problem I am running into is that the Latitude and Altitude show up fine, but the Longitude is always zero. I have put break points in my app and verified that the meta data is set properly and that all the information has valid values. I am at a loss at what is going on here.
Some of the following code may be redundant or inefficient simply because I have been testing different methods of adding the meta data. I am using the following code in my application in iOS implementation of this meta data adding method:
public byte[] AddPositionInformation(byte[] bytes, SaleScribe.PCL.Services.Geolocation.Position position)
{
var data = NSData.FromArray(bytes);
UIKit.UIImage original = UIKit.UIImage.LoadFromData(data);
CGImageSource myImageSource = CGImageSource.FromData(original.AsJPEG());
var options = new CGImageDestinationOptions();
options.GpsDictionary = new CoreGraphics.CGImagePropertiesGps();
options.GpsDictionary.Latitude = (float)position.Latitude;
options.GpsDictionary.Longitude = (float)position.Longitude;
options.GpsDictionary.Altitude = (int)position.Altitude;
NSMutableData mutableData = new NSMutableData();
using(var dest = CGImageDestination.Create(mutableData, myImageSource.TypeIdentifier, 1, new CGImageDestinationOptions()))
{
dest.AddImage(myImageSource, (int)(myImageSource.ImageCount - 1), options);
dest.Close();
}
return (mutableData as NSData).ToArray();
}
In the function that receives this byte array I am simply writing the byte array directly to a file.
Any help would be very much appreciated.
Thanks!

For anyone who may interested I had to use another method to get this to work, but the underlying problem was that the GPS Lat and Long require a uint so the -94.xxx longitude was invalid. I needed to add the absolute value of the lat and long and then add the appropriate ref value based on the original signed value.
Here is the code that worked for me:
public byte[] AddPositionInformation(byte[] bytes, SaleScribe.PCL.Services.Geolocation.Position position)
{
var data = NSData.FromArray(bytes);
CGImageSource myImageSource = CGImageSource.FromData(data);
var ns = new NSDictionary();
var imageProperties = myImageSource.CopyProperties(ns, 0);
var gps = new NSMutableDictionary();
gps.SetValueForKey(NSObject.FromObject(System.Math.Abs(position.Latitude)), CGImageProperties.GPSLatitude);
gps.SetValueForKey(NSObject.FromObject(new NSString(position.Latitude < 0 ? "S" : "N")), CGImageProperties.GPSLatitudeRef);
gps.SetValueForKey(NSObject.FromObject(System.Math.Abs(position.Longitude)), CGImageProperties.GPSLongitude);
gps.SetValueForKey(NSObject.FromObject(new NSString(position.Longitude < 0 ? "W" : "E")), CGImageProperties.GPSLongitudeRef);
gps.SetValueForKey(NSObject.FromObject(position.Altitude), CGImageProperties.GPSAltitude);
gps.SetValueForKey(NSObject.FromObject(position.Altitude < 0 ? 1 : 0), CGImageProperties.GPSAltitudeRef);
var mutableDictionary = imageProperties.MutableCopy();
mutableDictionary.SetValueForKey(gps, CGImageProperties.GPSDictionary);
NSMutableData mutableData = new NSMutableData();
var dest = CGImageDestination.Create(mutableData, myImageSource.TypeIdentifier, 1);
dest.AddImage(myImageSource, 0, mutableDictionary as NSDictionary);
dest.Close();
return mutableData.ToArray();
}

Related

Using GSheets Script to increment value of duplicate by 1

I want to check a row for duplicates and if match increment these by 1.
The data I want to manipulate this way is LAT LONG Coordinates.
They originate from an aggregated data acquisition, where users can only insert country and city. Via an Add-On these will get GEO coded.
Problem is, that I need to slightly change the values of duplicate entries, in order to display them on a map. Easiest way (I think) is to increment a LAT or LONG coordinate by 1 if there is already an entry with the same value.
Data sample & results of script
Any idea how to do this via Script?
My code, originally intended to delete duplicate rows:
function overwriteDuplicates() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Formularantworten 2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
hA.forEach(function(e,i){hObj[e]=i;});//header title to index
var uA=[];
var d=0;
for(var i=0;i<vA.length;i++) {
if(uA.indexOf(vA[i][hObj['Latitude']])==-1) {
uA.push(vA[i][hObj['Latitude']]);
}else{
function increment() {
SpreadsheetApp.getActiveSheet().getRange('K').setValue(SpreadsheetApp.getActiveSheet().getRange('K').getValue() + 1);
}
}}}
You want to modify the latitude whenever duplicate coordinates (latitude and longitude is found).
In this case, you can do the following:
Get all the values in the sheet, and retrieve the indexes where Latitude and Longitude are, based on the headers.
Loop through all rows (excluding headers), and for each row, check whether a previous row contains these coordinates.
If that's the case (isDuplicate), increment the last number in the latitude (after the last .), or decrement it if it's close to 999 (I assume there's always 3 digits).
Store the new latitude in an array after modification.
Use setValues to write the modified latitudes to the sheet.
Below is a possible code snippet to do this (see inline comments for details).
Code snippet:
function overwriteDuplicates() {
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName("Formularantworten 2");
const values = sheet.getDataRange().getValues();
const headers = values.shift(); // Retrieve first row (headers)
const latColumn = headers.indexOf("Latitude"); // Latitude column index
const longColumn = headers.indexOf("Longitude"); // Longitude column index
let outputLocations = [];
for (let i = 0; i < values.length; i++) { // Loop through rows
const newLocation = { // Store object with current location
"latitude": values[i][latColumn],
"longitude": values[i][longColumn]
}
let isDuplicate;
do { // Check if location is duplicate, and increment if necessary
isDuplicate = outputLocations.some(location => {
const sameLatitude = location["latitude"] === newLocation["latitude"];
const sameLongitude = location["longitude"] === newLocation["longitude"];
return sameLatitude && sameLongitude;
});
if (isDuplicate) newLocation["latitude"] = modifyCoord(newLocation["latitude"]);
} while (isDuplicate);
outputLocations.push(newLocation); // Store new location in array
}
let outputLatitudes = outputLocations.map(location => [location["latitude"]]); // Retrieve latitudes from array
sheet.getRange(2, latColumn+1, sheet.getLastRow()-1).setValues(outputLatitudes); // Write updated latitudes to sheet
}
function modifyCoord(coordinates) {
let coordArray = coordinates.split(".");
let lastCoord = coordArray.pop();
if (lastCoord > 990) lastCoord--;
else lastCoord++;
coordArray.push(lastCoord);
return coordArray.join(".");
}
Output:

Writing a native messaging host in GJS

I'm trying to write a native messaging host for a chrome/firefox extension in GJS (since it will rely on code already written in GJS) but encountering some hurdles. I'm using chrome-gnome-shell as a rough template since it also uses GLib/Gio instrospection and GApplication, but it has the advantage of python struct that I don't have.
Quickly, native messaging hosts exchange messages through stdin/stdout which are an Int32 (4-bytes) length following by a string of utf-8 encoded JSON.
chrome-gnome-shell uses GLib.IOChannel with set_encoding('utf-8') and struct to handle int32 bytes. I've had trouble using that class in GJS and don't have struct so have been trying Gio.UnixInputStream wrapped in Gio.DataInputStream (and output counterparts), with put_int32()/read_int32() and put_string()/read_string().
Apparently I'm mightily confused about what I'm doing. If I call Gio.DataInputStream.read_int32() it returns a number 369098752, so I'm guessing the int32 is not being converted to a regular Number. If I call Gio.DataInputStream.read_bytes(4, null).unref_to_array() to get a ByteArray; ByteArray.toString() returns '\u0016' while ByteArray[0] returns '22' which appears to be the actual length.
Some pointers on reading/writing int32's to a datastream and would be much appreciated.
chrome-gnome-shell references:
on_input()
send_message()
I don't know if this is the best way to solve this, but here's what I came up with.
Two functions using the ByteArray import (modified from somewhere on SO):
const ByteArray = imports.byteArray;
function fromInt32 (byteArray) {
var value = 0;
for (var i = byteArray.length - 1; i >= 0; i--) {
value = (value * 256) + byteArray[i];
}
return value;
};
function toInt32 (num) {
var byteArray = [0, 0, 0, 0];
for (var index_ = 0; index_ < byteArray.length; index_++) {
var byte = num & 0xff;
byteArray [index_] = byte;
num = (num - byte) / 256 ;
}
return ByteArray.fromArray(byteArray);
};
For receiving/sending:
const Gio = imports.gi.Gio;
// Receiving
let stdin = new Gio.DataInputStream({
base_stream: new Gio.UnixInputStream({ fd: 0 })
});
let int32 = stdin.read_bytes(4, null).toArray();
let length = fromInt32(int32);
let data = stdin.read_bytes(length, null).toArray().toString();
let message = JSON.parse(data);
// Sending
let stdout = new Gio.DataOutputStream({
base_stream: new Gio.UnixOutputStream({ fd: 1 })
});
let data = JSON.stringify(message);
let int32 = toInt32(data.length);
stdout.write(int32, null);
stdout.put_string(data, null);
Of course, you should wrap these in try-catch as appropriate and you'll probably want to connect a source to the input (you can use the Gio.UnixInputStream):
let source = stdin.base_stream.create_source(null);
source.set_callback(onReceiveFunc);
source.attach(null);
You may be able to use Gio.DataOutputStream.put_int32() and Gio.DataInputStream.read_int32() the same way as you use read_bytes() and put_string().

save data depending on passed value in swift

I'm trying to save time taken to complete each level. so im looking for a better way to save data, i have 100 variables for all levels i.e, leveltime1, levetime2....and so on..leveltime100
I have this code which is not working
var leveltime : [Int] = [leveltime1, levetime2, leveltime3......leveltime100]
defaults.setInteger("leveltime[Currentlevel -1]")
leveltime[Currentlevel -1] = defaults.integerForKey("leveltime[Currentlevel -1]")
so this is not working. is there any other way ? other than if else and switch statement?
lets assume you are in level 3 and want to save the time you needed
var level = 3
var time = 21
now you want to safe this to your defaults, for this you generate a key (string)
var key = "leveltime-\(level)"
and store the time
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(time,key)
done.
to retrieve this at some point in time
var level = 3
var key = "leveltime-\(level)"
var defaults = NSUserDefaults.standardUserDefaults()
var time = defaults.integerForKey(key)

Convert NSData bytes to custom object

I am starting a project to create an iOS app to communicate with a device over BLE. Being a new effort, I am trying to do this is Swift if possible. The interface uses GATT and an existing set of custom message structures. I get to a point where I have the data from BLE in an NSData object. I'd like to cast it or directly convert it to my message structure in a fairly generic way.
I know that I can extract the data by hand either directly from the byte array from the NSData object or using an NSInputStream. While that works, it could be a maintenance issue and the interface has a number of different messages in it.
Is there an easier ways to do this?
I'd be willing to create the message structures in Objective-C and do the casting there, but my knowledge of Objective-C is not much better than my knowledge of Swift.
Some sample code of what I've been playing in my playground is shown below. It all works as expected.
func getBytesFromNSData(data: NSData, start: Int) -> [UInt8] {
let count = data.length / sizeof(UInt8)
let remaining = count - start
let range = NSMakeRange(start, remaining )
var dataArray = [UInt8](count: remaining, repeatedValue: 0)
data.getBytes(&dataArray, range: range)
return dataArray
}
class TestObject {
var a: Byte
var b: Byte
init() {
a = 0x01
b = 0x02
}
init(data: NSData) {
let dataBytes = getBytesFromNSData(data, 0)
a = Byte(dataBytes[0])
b = Byte(dataBytes[1])
}
func populateFromStream(data: NSData) {
var stream = NSInputStream(data: data)
stream.open()
var bytesRead = stream.read(&a, maxLength: 1)
println("\(bytesRead)")
bytesRead = stream.read(&b, maxLength: 1)
println("\(bytesRead)")
}
func toArray() -> [Byte] {
var result = [Byte](count: 2, repeatedValue: 0)
result[0] = a
result[1] = b
return result
}
}
let test = TestObject()
let testArray = test.toArray()
let length = testArray.count
let testData = NSData(bytes: testArray, length: length)
println("\(testData)")
let testIn = [ Byte(0x0d), Byte(0x0e) ]
let testDataIn = NSData(bytes: testIn, length: testIn.count)
println("\(testDataIn)")
let testConstructor = TestObject(data: testDataIn)
var testObject = TestObject()
testObject.populateFromStream(testDataIn)
I found a method that is fairly generic that may work is some cases.
Create an Objective-C riding header
Create the data structure as an Objective-C structure
Import the header with the data structure into the bridging header
Assuming that you have a struct called Foo and an NSData object called rawData:
Use the following code to get an cast a pointer.
let structureSize = sizeof(Foo)
var myObject = UnsafeMutablePointer<Foo>.alloc(1).memory
rawData.getbytes(&myObject, length: structureSize)
This will not work in all instances and unfortunately does work in my particular case. The specific problems I have found are:
The Objective-C structure is word aligned. If your structure is not properly aligned to work boundaries, you may have a size that is incorrect. (something I ran into in my particular interface)
If you and dealing with a system that doesn't send the data in the same order you are expecting, this will not handle any byte order conversion, that would still need to be done and the structure would possibly need to be reordered to compensate. That work might negate any saving from this method.
This is the most concise method I have found if it happens to work with your particular message formats.

Actionscript ByteArray (from NFC) to String

I'm reading an NFC tag in my Adobe AIR mobile app. The data is read as a ByteArray, but I'm having difficulty pulling the full text. The sample text on the tag is "http://www.google.com"
Using this method, I get a portion of the String "http://www.goog", but not all of it. I'm assuming because each character is not a single byte:
private static function convertToString(byte_array : ByteArray) : String {
var arr : Array = [];
for (var i : Number = 1 ; i <= byte_array.bytesAvailable; i++) {
arr.push(byte_array.readUTFBytes(i));
}
var finalString : String = "";
for (var t : Number = 0; t < arr.length;t++) {
finalString = finalString + arr[t].toString();
}
return finalString;
}
I've also tried the method below, but it returns null:
bytes.readUTF();
I'm wondering if I need to convert the byteArray to a base64 string and then decode that. It seems like an extra step, but that's how I've done it before when sending data to/from a server using AMFPHP.
Thanks in advance for any input.
You could even simplify this code by simply calling
private static function convertToString(bytes:ByteArray):String {
bytes.position = 0;
var str:String = bytes.readUTFBytes(bytes.length);
return str;
}
This way you will read all contents of the bytearray in one single method call into your destination string.
Figured it out in the code below.
There were 2 errors, plus some cleanup:
private static function convertToString(bytes : ByteArray) : String {
bytes.position = 0;
var str : String = '';
while (bytes.bytesAvailable > 0) {
str += bytes.readUTFBytes(1);
}
return str;
}
the "bytesAvailable" property decreases as you read from the ByteArray. Here, I'm checking if the bytes > 0 instead of the length
the "readUTFBytes" method takes a length parameter (not position). Position is automatically updated as you read from the ByteArray. I'm passing in "1" instead of "i"

Resources