From 1f02bc43ac713c207e931b7c56a63f4f387912a9 Mon Sep 17 00:00:00 2001 From: Georgy Litvinov Date: Mon, 7 Dec 2020 19:22:53 +0100 Subject: [PATCH] Added dimensions converter --- .../w2phtml/util/DimensionsConverter.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/w2phtml/util/DimensionsConverter.java diff --git a/src/main/java/w2phtml/util/DimensionsConverter.java b/src/main/java/w2phtml/util/DimensionsConverter.java new file mode 100644 index 0000000..f854929 --- /dev/null +++ b/src/main/java/w2phtml/util/DimensionsConverter.java @@ -0,0 +1,59 @@ +package w2phtml.util; + +public class DimensionsConverter { + + public static float pixelsPerInch = 96.0F; + public static final float length2px(String input, float ppi) { + if ( input.equals("0")) { + return 0; + } + if (ppi <= 0) { + ppi = pixelsPerInch; + } + String unit = input.replaceAll("[^a-zA-Z]", ""); + String dimension = input.replaceAll("[^0-9.]", ""); + float length = parseNumber(dimension, 0); + float pixels = ppi / getUnitsPerInch(unit) * length; + if (Math.abs(pixels) < 0.01) { + // Very small, treat as zero + return 0; + } else if (pixels > 0) { + // Never return less that 1px + return pixels < 1 ? 1 : pixels; + } else { + // Or above -1px + return pixels > -1 ? -1 : pixels; + } + } + + public static final float parseNumber(String input, float defaultValue) { + float result; + try { + result = Float.parseFloat(input); + } catch (NumberFormatException e) { + return defaultValue; + } + return result; + } + + private static final float getUnitsPerInch(String unit) { + if (unit == null) { + unit = ""; + } + switch (unit) { + case "in": + return 1.0F; + case "mm": + return 25.4F; + case "cm": + return 2.54F; + case "pc": + return 6F; + case "pt": + return 72F; + default: + return 72; + } + } + +}