use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class Image method exifRotation.
/**
* <p>
* The main use case of this method is the automatic rotation and flipping
* of an image returned from the camera or from the gallery, preserving the
* original format (jpeg or png); it detects the Exif Orientation Tag, if
* available (all the possible Exif Orientation Tag values are
* supported); transparency is not preserved.</p>
* <p>
* However, rotating and/or flipping an hi-res image is very inefficient,
* that's why you should consider to pass a maxSize value as small as
* possible: it makes this method working faster.</p>
* <p>
* If there is no rotation or flipping, the image is only copied or scaled
* if necessary; if the capturedImage has a format different from jpeg and
* png, it is copied as it is.<br>Note that this method doesn't rely on the
* file extension, but on the mime type of the capturedImage, since some
* devices don't give appropriate extension to images returned from the
* gallery.</p>
* <p>
* You can test all the possible orientation values downloading the images
* from the repository
* <a href="https://github.com/recurser/exif-orientation-examples">EXIF
* Orientation-flag example images</a></p>
* <p>
* Code example:</p>
* <script src="https://gist.github.com/jsfan3/7fc101523955e8179fadd2c713a09e05.js"></script>
*
* @param capturedImage is the FileSystemStorage path of a captured photo,
* usually inside a temporary directory
* @param rotatedImage is the FileSystemStorage path in which the rotated
* photo is stored, normally this should be inside the
* FileSystemStorage.getAppHomePath(); it can be null if you don't want to
* save the rotated image to the FileSystemStorage.
* @param maxSize is the maximum value of the width and height of the
* rotated images, that is scaled if necessary, keeping the ratio.
* @return the com.codename1.ui.Image
* @throws java.io.IOException
*/
public static Image exifRotation(String capturedImage, String rotatedImage, int maxSize) throws IOException {
FileSystemStorage fss = FileSystemStorage.getInstance();
boolean isJpeg = isJPEG(fss.openInputStream(capturedImage));
boolean isPNG = isPNG(fss.openInputStream(capturedImage));
String format;
// because some Android devices return images from the gallery without extension!
if (!isJpeg && !isPNG) {
// In this case, we simply copy the file.
if (rotatedImage != null) {
Util.copy(fss.openInputStream(capturedImage), fss.openOutputStream(rotatedImage));
}
return EncodedImage.create(fss.openInputStream(capturedImage), (int) fss.getLength(capturedImage));
} else if (isJpeg) {
format = ImageIO.FORMAT_JPEG;
} else {
format = ImageIO.FORMAT_PNG;
}
int orientation = getExifOrientationTag(fss.openInputStream(capturedImage));
Image img = EncodedImage.create(fss.openInputStream(capturedImage), (int) fss.getLength(capturedImage));
img.lock();
if (maxSize > 0 && (img.getWidth() > maxSize || img.getHeight() > maxSize)) {
// Tested that scaling the image before rotating is a lot more efficient than rotating before scaling
Image scaled = img.scaledSmallerRatio(maxSize, maxSize);
img.unlock();
img = scaled;
img.lock();
}
Image result, temp;
switch(orientation) {
case 0:
case 1:
// no rotation (but the image may have been scaled)
result = img;
break;
case 2:
// action required: flip horizontally
result = img.flipHorizontally(false);
break;
case 3:
// action required: rotate 180 degrees
result = img.rotate180Degrees(false);
break;
case 4:
// action required: flip vertically
result = img.flipVertically(false);
break;
case 5:
// action required: rotate 270 degrees
result = img.rotate270Degrees(false);
break;
case 6:
// action required: rotate 90 degrees
result = img.rotate90Degrees(false);
break;
case 7:
// action required: flip horizontally and rotate 90 degrees
temp = img.flipHorizontally(false);
temp.lock();
result = temp.rotate90Degrees(false);
temp.unlock();
break;
case 8:
// action required: flip horizontally and rotate 270 degrees
temp = img.flipHorizontally(false);
temp.lock();
result = temp.rotate270Degrees(false);
temp.unlock();
break;
default:
// this never should happen
throw new IllegalStateException("Unsupported rotation");
}
img.unlock();
if (rotatedImage != null) {
OutputStream out = fss.openOutputStream(rotatedImage);
ImageIO.getImageIO().save(result, out, format, 0.9f);
Util.cleanup(out);
}
return EncodedImage.createFromImage(result, isJpeg);
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class IOSImplementation method showNativePicker.
@Override
public Object showNativePicker(final int type, final Component source, final Object currentValue, final Object data) {
datePickerResult = -2;
int x = 0, y = 0, w = 20, h = 20, preferredHeight = 0, preferredWidth = 0;
if (source != null) {
x = source.getAbsoluteX();
y = source.getAbsoluteY();
w = source.getWidth();
h = source.getHeight();
}
if (source instanceof Picker) {
Picker p = (Picker) source;
preferredHeight = p.getPreferredPopupHeight();
preferredWidth = p.getPreferredPopupWidth();
}
if (type == Display.PICKER_TYPE_STRINGS) {
String[] strs = (String[]) data;
int offset = -1;
if (currentValue != null) {
int slen = strs.length;
for (int iter = 0; iter < slen; iter++) {
if (strs[iter].equals(currentValue)) {
offset = iter;
break;
}
}
}
nativeInstance.openStringPicker(strs, offset, x, y, w, h, preferredWidth, preferredHeight);
} else if (type == Display.PICKER_TYPE_DURATION) {
long time;
if (currentValue instanceof Long) {
time = (Long) currentValue;
} else {
time = 0l;
}
int minuteStep = 5;
if (data instanceof String) {
String strData = (String) data;
String[] parts = Util.split(strData, "\n");
for (String part : parts) {
if (part.indexOf("minuteStep=") != -1) {
minuteStep = Integer.parseInt(part.substring(part.indexOf("=") + 1));
}
}
}
nativeInstance.openDatePicker(type, time, x, y, w, h, preferredWidth, preferredHeight, minuteStep);
} else {
long time;
if (currentValue instanceof Integer) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.set(java.util.Calendar.HOUR_OF_DAY, ((Integer) currentValue).intValue() / 60);
c.set(java.util.Calendar.MINUTE, ((Integer) currentValue).intValue() % 60);
time = c.getTime().getTime();
} else if (currentValue != null) {
time = ((java.util.Date) currentValue).getTime();
} else {
time = new java.util.Date().getTime();
}
int minuteStep = 5;
if (data instanceof String) {
String strData = (String) data;
String[] parts = Util.split(strData, "\n");
for (String part : parts) {
if (part.indexOf("minuteStep=") != -1) {
minuteStep = Integer.parseInt(part.substring(part.indexOf("=") + 1));
}
}
}
nativeInstance.openDatePicker(type, time, x, y, w, h, preferredWidth, preferredHeight, minuteStep);
}
// wait for the native code to complete
Display.getInstance().invokeAndBlock(new Runnable() {
public void run() {
while (datePickerResult == -2) {
synchronized (PICKER_LOCK) {
try {
PICKER_LOCK.wait(100);
} catch (InterruptedException err) {
}
}
}
}
}, true);
if (datePickerResult == -1) {
// }
return null;
}
if (type == Display.PICKER_TYPE_STRINGS) {
if (datePickerResult < 0) {
return null;
}
return ((String[]) data)[(int) datePickerResult];
}
Object result;
if (type == Display.PICKER_TYPE_DURATION || type == Display.PICKER_TYPE_DURATION_HOURS || type == Display.PICKER_TYPE_DURATION_MINUTES) {
if (datePickerResult < 0) {
return null;
}
return new Long(datePickerResult);
}
if (type == Display.PICKER_TYPE_TIME) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(new Date(datePickerResult));
result = new Integer(c.get(java.util.Calendar.HOUR_OF_DAY) * 60 + c.get(java.util.Calendar.MINUTE));
} else {
result = new Date(datePickerResult);
}
return result;
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class DatabaseTests method testSimpleQueries.
private void testSimpleQueries() throws Exception {
String dbName = "testdb";
Database.delete(dbName);
Database db = Database.openOrCreate(dbName);
db.execute("create table tests (name text)");
db.execute("insert into tests values ('Steve'), ('Mike'), ('Ryan')");
Cursor c = db.executeQuery("select count(*) from tests");
c.next();
this.assertEqual(3, c.getRow().getInteger(0), "Expected result of 3 for count(*) after inserting 3 rows");
}
use of com.codename1.rad.processing.Result in project CodeRAD by shannah.
the class ResultParser method parseRow.
/**
* Parse a single row of a result into the given row entity.
* @param rowResult The rowResult.
* @param rowEntity The row entity.
* @return The resulting entity. Same as input rowEntity.
* @throws IOException if parsing fails.
*/
public Entity parseRow(Result rowResult, Entity rowEntity) throws IOException {
if (rowEntity.getEntity().getEntityType() != entityType) {
ResultParser matchingParser = getParserFor(rowEntity.getEntity().getEntityType());
if (matchingParser == null) {
throw new IOException("No parser found for type " + rowEntity.getEntity().getEntityType());
}
return matchingParser.parseRow(rowResult, rowEntity);
}
for (PropertyParser propertyParser : propertyParsers) {
String rs = propertyParser.resultPropertySelector;
Property prop = propertyParser.property;
if (prop == null) {
if (propertyParser.tags != null) {
prop = rowEntity.getEntity().findProperty(propertyParser.tags);
}
}
if (prop == null) {
throw new IOException("Property not found for property selector when parsing selector " + rs);
}
if (propertyParser.entityParser != null) {
// same row data - not a sub-object in the dataset.
if (prop.getContentType().isEntity()) {
EntityProperty eProp = (EntityProperty) prop;
Class cls = eProp.getRepresentationClass();
Entity e;
try {
e = createEntity(cls);
} catch (Throwable t) {
throw new IOException("Failed to create new entity instance for property " + prop + " of type " + cls);
}
e = propertyParser.entityParser.parseRow(rowResult, e);
rowEntity.getEntity().set(prop, e);
} else {
throw new IOException("Property " + prop + " is assigned an EntityParser, but the property is not an entity type.");
}
continue;
}
// This is just a simple property selector
Getter getter = propertyParser.getter;
if (getter == null && propertyParser.parserCallback == null) {
getter = createGetter(prop);
}
Object val;
if (getter == null) {
val = rowResult.get(rs);
} else {
val = getter.get(rowResult, rs);
}
if (propertyParser.parserCallback != null) {
val = propertyParser.parserCallback.parse(val);
}
if (val == null) {
rowEntity.getEntity().set(val, null);
} else if (val.getClass() == Double.class) {
rowEntity.getEntity().setDouble(prop, (Double) val);
} else if (val.getClass() == Integer.class) {
rowEntity.getEntity().setInt(prop, (Integer) val);
} else if (val.getClass() == Long.class) {
rowEntity.getEntity().setLong(prop, (Long) val);
} else if (val.getClass() == Float.class) {
rowEntity.getEntity().setFloat(prop, (Float) val);
} else if (val.getClass() == Boolean.class) {
rowEntity.getEntity().setBoolean(prop, (Boolean) val);
} else if (val.getClass() == String.class) {
rowEntity.getEntity().setText(prop, (String) val);
} else if (val.getClass() == Date.class) {
rowEntity.getEntity().setDate(prop, (Date) val);
} else if (val instanceof List) {
if (prop.getContentType().isEntityList()) {
parse((List) val, rowEntity.getEntity().getEntityListNonNull(prop));
} else {
throw new IOException("Property type mismatch. Value " + val + " for property selector " + rs + " is a list, but the property " + prop + " is not an entity list type.");
}
} else if (val instanceof Map) {
if (prop.getContentType().isEntity()) {
EntityProperty eProp = (EntityProperty) prop;
Class cls = eProp.getRepresentationClass();
Entity e;
try {
e = createEntity(cls);
} catch (Throwable t) {
throw new IOException("Failed to create new entity instance for property " + prop + " of type " + cls);
}
e = parseRow(Result.fromContent((Map) val), e);
rowEntity.getEntity().set(prop, e);
} else {
throw new IOException("Property type mismatch. Value " + val + " for property selector " + rs + " is a map, but the property " + prop + " is not an entity type.");
}
} else if (val instanceof Element) {
if (prop.getContentType().isEntity()) {
EntityProperty eProp = (EntityProperty) prop;
Class cls = eProp.getRepresentationClass();
Entity e;
try {
e = createEntity(cls);
} catch (Throwable t) {
throw new IOException("Failed to create new entity instance for property " + prop + " of type " + cls);
}
e = parseRow(Result.fromContent((Element) val), e);
rowEntity.getEntity().set(prop, e);
} else {
throw new IOException("Property type mismatch. Value " + val + " for property selector " + rs + " is a map, but the property " + prop + " is not an entity type.");
}
} else {
throw new IOException("Unsupported content type for property " + prop + ". Value was " + val + " of type " + val.getClass());
}
}
return rowEntity;
}
use of com.codename1.rad.processing.Result in project CodeRAD by shannah.
the class ResultParserTest method testResultJSON.
private void testResultJSON() throws Exception {
String json = "{\"name\":\"Paul\", \"email\":\"paul@example.com\", \"dob\":\"December 27, 1978\" " + ", \"children\": [{\"name\":\"Jim\", \"email\":\"jim@example.com\", \"dob\":\"January 10, 1979\"}," + "{\"name\"=\"Jill\", \"email\"=\"jill@example.com\", \"dob\":\"January 11, 1979\"}]}";
Result r = Result.fromContent(json, Result.JSON);
assertEqual("Paul", r.get("name"));
assertEqual("Paul", r.getAsString("name"));
assertEqual("Paul", r.get("name"));
assertEqual("Jim", r.get("./children[0]/name"));
assertEqual("Jim", r.get("children[0]/name"));
assertNull(r.get("./children/person[0]/name"));
assertNull(r.getAsString("./children/person/name"));
assertEqual("Jim", r.getAsString("./children[0]/name"));
assertEqual(2, r.getAsStringArray("./children/name").length);
assertArrayEqual(new String[] { "Jim", "Jill" }, r.getAsStringArray("./children/name"));
assertEqual("Jim", r.get("./children/name"));
assertNull(r.getAsString("children/person/name"));
assertNull(r.getAsString("children[0]/person/name"));
assertEqual(0, r.getAsStringArray("children/person/name").length);
json = "{\"numbers\" : [1, 2, 3, 4]}";
r = Result.fromContent(json, Result.JSON);
assertEqual(1, r.getAsInteger("numbers[0]"));
String jsonData = "{\n" + " \"colors\": [\n" + " {\n" + " \"color\": \"black\",\n" + " \"category\": \"hue\",\n" + " \"type\": \"primary\",\n" + " \"code\": {\n" + " \"rgba\": [255,255,255,1],\n" + " \"hex\": \"#000\"\n" + " }\n" + " },\n" + " {\n" + " \"color\": \"white\",\n" + " \"category\": \"value\",\n" + " \"code\": {\n" + " \"rgba\": [0,0,0,1],\n" + " \"hex\": \"#FFF\"\n" + " }\n" + " },\n" + " {\n" + " \"color\": \"red\",\n" + " \"category\": \"hue\",\n" + " \"type\": \"primary\",\n" + " \"code\": {\n" + " \"rgba\": [255,0,0,1],\n" + " \"hex\": \"#FF0\"\n" + " }\n" + " },\n" + " {\n" + " \"color\": \"blue\",\n" + " \"category\": \"hue\",\n" + " \"type\": \"primary\",\n" + " \"code\": {\n" + " \"rgba\": [0,0,255,1],\n" + " \"hex\": \"#00F\"\n" + " }\n" + " },\n" + " {\n" + " \"color\": \"yellow\",\n" + " \"category\": \"hue\",\n" + " \"type\": \"primary\",\n" + " \"code\": {\n" + " \"rgba\": [255,255,0,1],\n" + " \"hex\": \"#FF0\"\n" + " }\n" + " },\n" + " {\n" + " \"color\": \"green\",\n" + " \"category\": \"hue\",\n" + " \"type\": \"secondary\",\n" + " \"code\": {\n" + " \"rgba\": [0,255,0,1],\n" + " \"hex\": \"#0F0\"\n" + " }\n" + " },\n" + " ]\n" + "}";
r = Result.fromContent(jsonData, Result.JSON);
assertEqual("black", r.getAsString("colors[0]/color"));
assertEqual(255, r.getAsInteger("colors[0]/code/rgba[0]"));
}
Aggregations