repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseSysTableController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseSysTableController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.BaseTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; /** * @param <P> Data * @Author Mara * @CreateDate 2019-12-18 * @License Apache License Version 2.0 */ public abstract class BaseSysTableController<P> extends BaseTablePagesController<P> { protected BaseTable tableDefinition; @FXML protected Button examplesButton, resetButton, importButton, exportButton, chartsButton, queryButton, moveDataButton, orderby; @FXML protected Label queryConditionsLabel; public BaseSysTableController() { tableName = ""; TipsLabelKey = "TableTips"; } @Override public void initValues() { try { super.initValues(); setTableDefinition(); setTableDefinition(tableDefinition); } catch (Exception e) { MyBoxLog.error(e); } } // define tableDefinition here public void setTableDefinition() { } public void setTableDefinition(BaseTable t) { tableDefinition = t; if (tableDefinition != null) { tableName = tableDefinition.getTableName(); idColumnName = tableDefinition.getIdColumnName(); } } @Override public void postLoadedTableData() { super.postLoadedTableData(); if (queryConditionsLabel != null) { queryConditionsLabel.setText(queryConditionsString); } } @Override public List<P> readPageData(FxTask currentTask, Connection conn) { if (tableDefinition != null) { return tableDefinition.queryConditions(conn, queryConditions, orderColumns, pagination.startRowOfCurrentPage, pagination.pageSize); } else { return null; } } @Override public long readDataSize(FxTask currentTask, Connection conn) { long size = 0; if (tableDefinition != null) { if (queryConditions != null) { size = tableDefinition.conditionSize(conn, queryConditions); } else { size = tableDefinition.size(conn); } } dataSizeLoaded = true; return size; } @Override protected int deleteData(FxTask currentTask, List<P> data) { if (data == null || data.isEmpty()) { return 0; } if (tableDefinition != null) { return tableDefinition.deleteData(data); } return 0; } @Override protected long clearData(FxTask currentTask) { if (tableDefinition != null) { return tableDefinition.deleteCondition(queryConditions); } else { return 0; } } @FXML @Override public void refreshAction() { loadTableData(); } @FXML protected void importAction() { File file = FxFileTools.selectFile(this); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { importData(file); return true; } @Override protected void whenSucceeded() { popSuccessful(); refreshAction(); } }; start(task); } protected void importData(File file) { DerbyBase.importData(tableName, file.getAbsolutePath(), false); } @FXML protected void exportAction() { final File file = chooseFile(defaultTargetPath(), Languages.message(tableName) + ".txt", FileFilters.AllExtensionFilter); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { DerbyBase.exportData(tableName, file.getAbsolutePath()); recordFileWritten(file); return true; } @Override protected void whenSucceeded() { popSuccessful(); TextEditorController.open(file); } }; start(task); } @FXML protected void analyseAction() { } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/SvgRectangleController.java
released/MyBox/src/main/java/mara/mybox/controller/SvgRectangleController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.XmlTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2023-12-31 * @License Apache License Version 2.0 */ public class SvgRectangleController extends BaseSvgShapeController { @FXML protected ControlRectangle rectController; @Override public void initMore() { try { shapeName = message("Rectangle"); rectController.setParameters(this); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean elementToShape(Element node) { try { float x, y, w, h, rx = 0, ry = 0; try { x = Float.parseFloat(node.getAttribute("x")); } catch (Exception e) { popError(message("InvalidParameter") + ": x"); return false; } try { y = Float.parseFloat(node.getAttribute("y")); } catch (Exception e) { popError(message("InvalidParameter") + ": y"); return false; } try { w = Float.parseFloat(node.getAttribute("width")); } catch (Exception e) { w = -1f; } if (w <= 0) { popError(message("InvalidParameter") + ": " + message("Width")); return false; } try { h = Float.parseFloat(node.getAttribute("height")); } catch (Exception e) { h = -1f; } if (h <= 0) { popError(message("InvalidParameter") + ": " + message("Height")); return false; } try { rx = Float.parseFloat(node.getAttribute("rx")); } catch (Exception e) { } try { ry = Float.parseFloat(node.getAttribute("ry")); } catch (Exception e) { } maskRectangleData = DoubleRectangle.xywh(x, y, w, h); maskRectangleData.setRoundx(rx); maskRectangleData.setRoundy(ry); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void initShape() { rectController.setRoundList(); } @Override public void showShape() { showMaskRectangle(); } @Override public void setShapeInputs() { rectController.loadValues(); } @Override public boolean shape2Element() { try { if (maskRectangleData == null) { return false; } if (shapeElement == null) { shapeElement = doc.createElement("rect"); } shapeElement.setAttribute("x", scaleValue(maskRectangleData.getX())); shapeElement.setAttribute("y", scaleValue(maskRectangleData.getY())); shapeElement.setAttribute("width", scaleValue(maskRectangleData.getWidth())); shapeElement.setAttribute("height", scaleValue(maskRectangleData.getHeight())); shapeElement.setAttribute("rx", scaleValue(maskRectangleData.getRoundx())); shapeElement.setAttribute("ry", scaleValue(maskRectangleData.getRoundy())); return true; } catch (Exception e) { MyBoxLog.error(e); } return false; } @Override public boolean pickShape() { return rectController.pickValues(); } /* static */ public static SvgRectangleController drawShape(SvgEditorController editor, TreeItem<XmlTreeNode> item, Element element) { try { if (editor == null || item == null) { return null; } SvgRectangleController controller = (SvgRectangleController) WindowTools.childStage( editor, Fxmls.SvgRectangleFxml); controller.setParameters(editor, item, element); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/DoubleArrayTools.java
released/MyBox/src/main/java/mara/mybox/tools/DoubleArrayTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @Description * @License Apache License Version 2.0 */ public class DoubleArrayTools { public static double[] sortArray(double[] numbers) { List<Double> list = new ArrayList<>(); for (double i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Double>() { @Override public int compare(Double p1, Double p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); double[] sorted = new double[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } public static double[] array(double x, double y, double z) { double[] xyz = new double[3]; xyz[0] = x; xyz[1] = y; xyz[2] = z; return xyz; } public static double[] scale(double[] data, int scale) { try { if (data == null) { return null; } double[] result = new double[data.length]; for (int i = 0; i < data.length; ++i) { result[i] = DoubleTools.scale(data[i], scale); } return result; } catch (Exception e) { return null; } } public static double[] normalizeMinMax(double[] array) { try { if (array == null) { return null; } double[] result = new double[array.length]; double min = Double.MAX_VALUE, max = -Double.MAX_VALUE; for (int i = 0; i < array.length; ++i) { double d = array[i]; if (d > max) { max = d; } if (d < min) { min = d; } } if (min == max) { return normalizeSum(array); } else { double s = 1d / (max - min); for (int i = 0; i < array.length; ++i) { result[i] = (array[i] - min) * s; } } return result; } catch (Exception e) { return null; } } public static double[] normalizeSum(double[] array) { try { if (array == null) { return null; } double[] result = new double[array.length]; double sum = 0; for (int i = 0; i < array.length; ++i) { sum += Math.abs(array[i]); } if (sum == 0) { return null; } double s = 1d / sum; for (int i = 0; i < array.length; ++i) { result[i] = array[i] * s; } return result; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/DateTools.java
released/MyBox/src/main/java/mara/mybox/tools/DateTools.java
package mara.mybox.tools; import java.text.DateFormat; import java.text.MessageFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Random; import java.util.TimeZone; import mara.mybox.data.Era; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.TimeFormats; /** * @Author Mara * @CreateDate 2018-6-11 9:44:53 * @License Apache License Version 2.0 */ public class DateTools { /* parse to date */ // strDate does not contain ear code(bc/ad) public static String parseFormat(String strDate) { try { if (strDate == null || strDate.isBlank()) { return null; } String fullString = strDate.trim().replace("T", " "); String parsed = fullString, format; if (parsed.startsWith("-")) { parsed = fullString.substring(1); } int len = parsed.length(); if (len <= 4) { format = TimeFormats.YearA; } else if (parsed.contains("/")) { if (parsed.charAt(4) == '/') { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsC; } else { format = TimeFormats.DatetimeC; } } else if (parsed.indexOf("/") == parsed.lastIndexOf("/")) { format = TimeFormats.MonthC; } else { format = TimeFormats.DateC; } } else { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsB; } else { format = TimeFormats.DatetimeB; } } else if (parsed.indexOf("/") == parsed.lastIndexOf("/")) { format = TimeFormats.MonthB; } else { format = TimeFormats.DateB; } } } else if (parsed.contains("-")) { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsA; } else { format = TimeFormats.DatetimeA; } } else if (parsed.indexOf("-") == parsed.lastIndexOf("-")) { format = TimeFormats.MonthA; } else { format = TimeFormats.DateA; } } else if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.TimeMs; } else { format = TimeFormats.Time; } } else { format = TimeFormats.YearA; } if (parsed.contains("+")) { format += " Z"; } return format; } catch (Exception e) { return null; } } public static Date encodeDate(String strDate, int century) { if (strDate == null) { return null; } try { long lv = Long.parseLong(strDate); if (lv >= 10000 || lv <= -10000) { return new Date(lv); } } catch (Exception e) { } String s = strDate.trim().replace("T", " "), format; Locale locale; int len = s.length(); if (s.startsWith(message("zh", "BC") + " ")) { locale = Languages.LocaleZhCN; format = "G " + parseFormat(s.substring((message("zh", "BC") + " ").length(), len)); } else if (s.startsWith(message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = "G" + parseFormat(s.substring((message("zh", "BC")).length(), len)); } else if (s.startsWith(message("zh", "AD") + " ")) { locale = Languages.LocaleZhCN; format = "G " + parseFormat(s.substring((message("zh", "AD") + " ").length(), len)); } else if (s.startsWith(message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = "G" + parseFormat(s.substring((message("zh", "AD")).length(), len)); } else if (s.startsWith(message("en", "BC") + " ")) { locale = Languages.LocaleEn; format = "G " + parseFormat(s.substring((message("en", "BC") + " ").length(), len)); } else if (s.startsWith(message("en", "BC"))) { locale = Languages.LocaleEn; format = "G" + parseFormat(s.substring((message("en", "BC")).length(), len)); } else if (s.startsWith(message("en", "AD") + " ")) { locale = Languages.LocaleEn; format = "G " + parseFormat(s.substring((message("en", "AD") + " ").length(), len)); } else if (s.startsWith(message("en", "AD"))) { locale = Languages.LocaleEn; format = "G" + parseFormat(s.substring((message("en", "AD")).length(), len)); } else if (s.endsWith(" " + message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - (" " + message("zh", "BC")).length())) + " G"; } else if (s.endsWith(message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - message("zh", "BC").length())) + "G"; } else if (s.endsWith(" " + message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - (" " + message("zh", "AD")).length())) + " G"; } else if (s.endsWith(message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - message("zh", "AD").length())) + "G"; } else if (s.endsWith(" " + message("en", "BC"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - (" " + message("en", "BC")).length())) + " G"; } else if (s.endsWith(message("en", "BC"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - message("en", "BC").length())) + "G"; } else if (s.endsWith(" " + message("en", "AD"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - (" " + message("en", "AD")).length())) + " G"; } else if (s.endsWith(message("en", "AD"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - message("en", "AD").length())) + "G"; } else { locale = Languages.locale(); format = parseFormat(s); } Date d = encodeDate(s, format, locale, century); return d; } public static Date encodeDate(String strDate) { return encodeDate(strDate, 0); } public static Date encodeDate(String strDate, Locale locale, int century) { return encodeDate(strDate, parseFormat(strDate), locale, century); } public static Date encodeDate(String strDate, String format) { return encodeDate(strDate, format, Locale.getDefault(), 0); } public static Date encodeDate(String strDate, String format, int century) { return encodeDate(strDate, format, Locale.getDefault(), century); } // century. 0: not fix -1:fix as default others:fix as value public static Date encodeDate(String strDate, String format, Locale locale, int century) { if (strDate == null || strDate.isEmpty() || format == null || format.isEmpty()) { return null; } // MyBoxLog.debug(strDate + " " + format + " " + locale + " " + century); try { SimpleDateFormat formatter = new SimpleDateFormat(format, locale); if (century >= 0) { formatter.set2DigitYearStart(new SimpleDateFormat("yyyy") .parse(century > 0 ? century + "" : "0000")); } return formatter.parse(strDate, new ParsePosition(0)); } catch (Exception e) { try { return new Date(Long.parseLong(strDate)); } catch (Exception ex) { return null; } } } public static Date thisMonth() { return DateTools.encodeDate(nowString().substring(0, 7), "yyyy-MM"); } public static Date localDateToDate(LocalDate localDate) { try { ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zdt = localDate.atStartOfDay(zoneId); Date date = Date.from(zdt.toInstant()); return date; } catch (Exception e) { return null; } } public static LocalDate dateToLocalDate(Date date) { try { Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDate localDate = instant.atZone(zoneId).toLocalDate(); return localDate; } catch (Exception e) { return null; } } public static LocalDate stringToLocalDate(String strDate) { return dateToLocalDate(encodeDate(strDate)); } /* return string */ public static String nowFileString() { return datetimeToString(new Date(), TimeFormats.Datetime2); } public static String nowString() { return datetimeToString(new Date()); } public static String nowString3() { return datetimeToString(new Date(), TimeFormats.Datetime3); } public static String nowDate() { return datetimeToString(new Date(), TimeFormats.Date); } public static String textEra(Era era) { if (era == null || era.getValue() == AppValues.InvalidLong) { return ""; } return textEra(era.getValue(), era.getFormat()); } public static String textEra(String value) { return textEra(encodeDate(value)); } public static String textEra(Date value) { return value == null ? null : textEra(value.getTime()); } public static String textEra(long value) { if (value == AppValues.InvalidLong) { return ""; } return textEra(value, null); } public static String textEra(long value, String format) { if (value == AppValues.InvalidLong) { return ""; } return datetimeToString(new Date(value), format, Languages.locale(), null); } public static String localDateToString(LocalDate localDate) { return dateToString(localDateToDate(localDate)); } public static String datetimeToString(long dvalue) { if (dvalue == AppValues.InvalidLong) { return null; } return datetimeToString(new Date(dvalue)); } public static String datetimeToString(Date theDate) { return datetimeToString(theDate, null, null, null); } public static String datetimeToString(long theDate, String format) { if (theDate == AppValues.InvalidLong) { return null; } return datetimeToString(new Date(theDate), format); } public static String datetimeToString(Date theDate, String format) { return datetimeToString(theDate, format, null, null); } public static String datetimeToString(Date theDate, String inFormat, Locale inLocale, TimeZone inZone) { if (theDate == null) { return null; } String format = inFormat; if (format == null || format.isBlank()) { format = isBC(theDate.getTime()) ? bcFormat() : TimeFormats.Datetime; } Locale locale = inLocale; if (locale == null) { locale = Languages.locale(); } TimeZone zone = inZone; if (zone == null) { zone = getTimeZone(); } SimpleDateFormat formatter = new SimpleDateFormat(format, locale); formatter.setTimeZone(zone); String dateString = formatter.format(theDate); return dateString; } public static String dateToString(Date theDate) { return datetimeToString(theDate, TimeFormats.Date); } public static String dateToMonthString(Date theDate) { return datetimeToString(theDate).substring(0, 7); } public static String dateToYearString(Date theDate) { return datetimeToString(theDate).substring(0, 4); } public static String datetimeMsDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); String date = dateDuration(ms); String timeMs = timeMsDuration(ms); return f + (date.isBlank() ? timeMs : date + " " + timeMs); } public static String dateDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); int days = (int) (ms / (24 * 3600 * 1000)); int years = days / 365; days = days % 365; int month = days / 12; days = days % 12; return f + dateDuration(years, month, days); } public static String dateDuration(Date time1, Date time2) { Period period = period(time1, time2); if (period == null) { return null; } String date = dateDuration(period.getYears(), period.getMonths(), period.getDays()); return (period.isNegative() ? "-" : "") + date; } public static String dateDuration(int years, int months, int days) { String date; if (years > 0) { if (months > 0) { if (days > 0) { date = MessageFormat.format(message("DurationYearsMonthsDays"), years, months, days); } else { date = MessageFormat.format(message("DurationYearsMonths"), years, months); } } else if (days > 0) { date = MessageFormat.format(message("DurationYearsDays"), years, days); } else { date = MessageFormat.format(message("DurationYears"), years); } } else { if (months > 0) { if (days > 0) { date = MessageFormat.format(message("DurationMonthsDays"), months, days); } else { date = MessageFormat.format(message("DurationMonths"), months); } } else if (days > 0) { date = MessageFormat.format(message("DurationDays"), days); } else { date = ""; } } return date; } public static String yearsMonthsDuration(Date time1, Date time2) { Period period = period(time1, time2); String date; if (period.getYears() > 0) { date = MessageFormat.format(message("DurationYearsMonths"), period.getYears(), period.getMonths()); } else if (period.getMonths() > 0) { date = MessageFormat.format(message("DurationMonths"), period.getYears(), period.getMonths()); } else { date = ""; } return (period.isNegative() ? "-" : "") + date; } public static String yearsDuration(Date time1, Date time2) { Period period = period(time1, time2); String date; if (period.getYears() > 0) { date = MessageFormat.format(message("DurationYears"), period.getYears()); } else { date = ""; } return (period.isNegative() ? "-" : "") + date; } public static String timeDuration(Date time1, Date time2) { Duration duration = duration(time1, time2); return (duration.isNegative() ? "-" : "") + timeDuration(duration.getSeconds() * 1000); } public static String msDuration(Date time1, Date time2) { return timeMsDuration(time1.getTime() - time2.getTime()); } public static String datetimeDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeDuration(Math.abs(time1.getTime() - time2.getTime())); } public static String datetimeZoneDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeDuration(Math.abs(time1.getTime() - time2.getTime())) + " " + TimeZone.getDefault().getDisplayName(); } public static String datetimeMsDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeMsDuration(Math.abs(time1.getTime() - time2.getTime())); } public static String datetimeMsZoneDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeMsDuration(Math.abs(time1.getTime() - time2.getTime())) + " " + TimeZone.getDefault().getDisplayName(); } public static String timeDuration(long milliseconds) { long seconds = milliseconds / 1000; String f = seconds < 0 ? "-" : ""; long s = Math.abs(seconds); if (s < 60) { return f + String.format("00:%02d", s); } long minutes = s / 60; s = s % 60; if (minutes < 60) { return f + String.format("%02d:%02d", minutes, s); } long hours = minutes / 60; minutes = minutes % 60; return f + String.format("%02d:%02d:%02d", hours, minutes, s); } public static String timeMsDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); if (ms < 1000) { return f + String.format("00:00:0.%03d", ms); } long seconds = ms / 1000; ms = ms % 1000; if (seconds < 60) { return f + String.format("00:%02d.%03d", seconds, ms); } long minutes = seconds / 60; seconds = seconds % 60; if (minutes < 60) { return f + String.format("%02d:%02d.%03d", minutes, seconds, ms); } long hours = minutes / 60; minutes = minutes % 60; return f + String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, ms); } public static String duration(Date time1, Date time2, String format) { if (time1 == null || time2 == null) { return null; } String dFormat = format; if (dFormat == null) { dFormat = TimeFormats.Datetime; } switch (dFormat) { case TimeFormats.Date: return dateDuration(time1, time2); case TimeFormats.Month: return yearsMonthsDuration(time1, time2); case TimeFormats.Year: return yearsDuration(time1, time2); case TimeFormats.Time: return DateTools.timeDuration(time1, time2); case TimeFormats.TimeMs: return msDuration(time1, time2); case TimeFormats.DatetimeMs: return datetimeMsDuration(time1, time2); case TimeFormats.DatetimeZone: return datetimeZoneDuration(time1, time2); case TimeFormats.DatetimeMsZone: return datetimeMsZoneDuration(time1, time2); default: return datetimeDuration(time1, time2); } } public static String randomDateString(Random r, String format) { if (r == null) { r = new Random(); } return datetimeToString(randomTime(r), format); } /* others */ public static void printFormats() { MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.CHINESE).format(new Date())); } public static TimeZone getTimeZone() { return TimeZone.getDefault(); } public static Duration duration(Date time1, Date time2) { if (time1 == null || time2 == null) { return null; } Instant instant1 = Instant.ofEpochMilli​(time1.getTime()); Instant instant2 = Instant.ofEpochMilli​(time2.getTime()); return Duration.between(instant1, instant2); } public static Period period(Date time1, Date time2) { if (time1 == null || time2 == null) { return null; } LocalDate localDate1 = LocalDate.ofEpochDay(time1.getTime() / (24 * 3600000)); LocalDate localDate2 = LocalDate.ofEpochDay(time2.getTime() / (24 * 3600000)); return Period.between(localDate1, localDate2); } public static long zeroYear() { Calendar ca = Calendar.getInstance(); ca.set(0, 0, 1, 0, 0, 0); return ca.getTime().getTime(); } public static long randomTime(Random r) { if (r == null) { r = new Random(); } return r.nextLong(new Date().getTime() * 100); } public static String bcFormat() { return TimeFormats.Datetime + " G"; } public static boolean isBC(long value) { if (value == AppValues.InvalidLong) { return false; } String s = datetimeToString(new Date(value), bcFormat(), Languages.LocaleEn, null); return s.contains("BC"); } public static boolean isWeekend(long time) { try { Calendar cal = Calendar.getInstance(); cal.setTime(new Date(time)); if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { return true; } else { return false; } } catch (Exception e) { return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/IntTools.java
released/MyBox/src/main/java/mara/mybox/tools/IntTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2019-5-28 15:28:13 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class IntTools { public static boolean invalidInt(Integer value) { return value == null || value == AppValues.InvalidInteger; } public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Integer.parseInt(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Integer.parseInt(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } return FloatTools.compare(f1, f2, desc); } public static int random(int max) { return new Random().nextInt(max); } public static int random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); int i = r.nextInt(max); return sign == 1 ? i : -i; } public static String format(int v, String format, int scale) { if (invalidInt(v)) { return null; } return NumberTools.format(v, format, scale); } public static int[] sortArray(int[] numbers) { List<Integer> list = new ArrayList<>(); for (int i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer p1, Integer p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); int[] sorted = new int[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } public static void sortList(List<Integer> numbers) { Collections.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer p1, Integer p2) { return p1 - p2; } }); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/DoubleTools.java
released/MyBox/src/main/java/mara/mybox/tools/DoubleTools.java
package mara.mybox.tools; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Random; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @License Apache License Version 2.0 */ public class DoubleTools { public static NumberFormat numberFormat; public static boolean invalidDouble(Double value) { return value == null || Double.isNaN(value) || Double.isInfinite(value) || value == AppValues.InvalidDouble; } public static double value(InvalidAs invalidAs) { if (invalidAs == InvalidAs.Zero) { return 0d; } else { return Double.NaN; } } public static String scaleString(String string, InvalidAs invalidAs, int scale) { try { if (scale < 0) { return string; } double d = toDouble(string, invalidAs); return scaleString(d, scale); } catch (Exception e) { return string; } } public static double scale(String string, InvalidAs invalidAs, int scale) { try { double d = toDouble(string, invalidAs); return scale(d, scale); } catch (Exception e) { return value(invalidAs); } } public static double toDouble(String string, InvalidAs invalidAs) { try { double d = Double.parseDouble(string.replaceAll(",", "")); if (invalidDouble(d)) { if (StringTools.isTrue(string)) { return 1; } else if (StringTools.isFalse(string)) { return 0; } return value(invalidAs); } else { return d; } } catch (Exception e) { return value(invalidAs); } } public static double[] toDouble(String[] sVector, InvalidAs invalidAs) { try { if (sVector == null) { return null; } int len = sVector.length; double[] doubleVector = new double[len]; for (int i = 0; i < len; i++) { doubleVector[i] = DoubleTools.toDouble(sVector[i], invalidAs); } return doubleVector; } catch (Exception e) { return null; } } public static double[][] toDouble(String[][] sMatrix, InvalidAs invalidAs) { try { if (sMatrix == null) { return null; } int rsize = sMatrix.length, csize = sMatrix[0].length; double[][] doubleMatrix = new double[rsize][csize]; for (int i = 0; i < rsize; i++) { for (int j = 0; j < csize; j++) { doubleMatrix[i][j] = DoubleTools.toDouble(sMatrix[i][j], invalidAs); } } return doubleMatrix; } catch (Exception e) { return null; } } public static String percentage(double data, double total) { return percentage(data, total, 2); } public static String percentage(double data, double total, int scale) { try { if (total == 0) { return message("Invalid"); } return scale(data * 100 / total, scale) + ""; } catch (Exception e) { return data + ""; } } public static int compare(String s1, String s2, boolean desc) { return compare(toDouble(s1, InvalidAs.Empty), toDouble(s2, InvalidAs.Empty), desc); } // invalid values are counted as smaller public static int compare(double d1, double d2, boolean desc) { if (Double.isNaN(d1)) { if (Double.isNaN(d2)) { return 0; } else { return desc ? 1 : -1; } } else { if (Double.isNaN(d2)) { return desc ? -1 : 1; } else { double diff = d1 - d2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } /* https://stackoverflow.com/questions/322749/retain-precision-with-double-in-java "Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it" "BigDecimal is much slower than double" "The solution depends on what exactly your problem is: - If it's that you just don't like seeing all those noise digits, then fix your string formatting. Don't display more than 15 significant digits (or 7 for float). - If it's that the inexactness of your numbers is breaking things like "if" statements, then you should write if (abs(x - 7.3) < TOLERANCE) instead of if (x == 7.3). - If you're working with money, then what you probably really want is decimal fixed point. Store an integer number of cents or whatever the smallest unit of your currency is. - (VERY UNLIKELY) If you need more than 53 significant bits (15-16 significant digits) of precision, then use a high-precision floating-point type, like BigDecimal." */ public static double scale3(double invalue) { return DoubleTools.scale(invalue, 3); } public static double scale2(double invalue) { return DoubleTools.scale(invalue, 2); } public static double scale6(double invalue) { return DoubleTools.scale(invalue, 6); } public static double imageScale(double invalue) { return DoubleTools.scale(invalue, UserConfig.imageScale()); } public static double scale(double v, int scale) { try { if (scale < 0) { return v; } return Double.parseDouble(scaleString(v, scale)); } catch (Exception e) { return v; } } public static NumberFormat numberFormat() { numberFormat = NumberFormat.getInstance(); numberFormat.setMinimumFractionDigits(0); numberFormat.setGroupingUsed(false); numberFormat.setRoundingMode(RoundingMode.HALF_UP); return numberFormat; } public static String scaleString(double v, int scale) { try { if (scale < 0) { return v + ""; } if (numberFormat == null) { numberFormat(); } numberFormat.setMaximumFractionDigits(scale); return numberFormat.format(v); } catch (Exception e) { MyBoxLog.console(e); return v + ""; } } public static double random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); sign = sign == 1 ? 1 : -1; double d = r.nextDouble(); int i = max > 0 ? r.nextInt(max) : 0; return sign == 1 ? i + d : -(i + d); } public static String format(double v, String format, int scale) { if (invalidDouble(v)) { return null; } return NumberTools.format(v, format, scale); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/SystemTools.java
released/MyBox/src/main/java/mara/mybox/tools/SystemTools.java
package mara.mybox.tools; import java.awt.MouseInfo; import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2019-1-3 20:51:26 * @License Apache License Version 2.0 */ public class SystemTools { public static float jreVersion() { return Float.parseFloat(System.getProperty("java.version").substring(0, 3)); } public static String os() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("windows")) { return "win"; } else if (os.contains("linux")) { return "linux"; } else if (os.contains("mac")) { return "mac"; } else { return "other"; } } public static boolean isLinux() { return os().contains("linux"); } public static boolean isMac() { return os().contains("mac"); } public static boolean isWindows() { return os().contains("win"); } public static void currentThread() { Thread thread = Thread.currentThread(); MyBoxLog.debug(thread.threadId() + " " + thread.getName() + " " + thread.getState()); for (StackTraceElement element : thread.getStackTrace()) { MyBoxLog.debug(element.toString()); } } public static long getAvaliableMemory() { Runtime r = Runtime.getRuntime(); return r.maxMemory() - (r.totalMemory() - r.freeMemory()); } public static long getAvaliableMemoryMB() { return getAvaliableMemory() / (1024 * 1024L); } public static long freeBytes() { return getAvaliableMemory() - 200 * 1024 * 1024; } public static Point getMousePoint() { return MouseInfo.getPointerInfo().getLocation(); } public static String IccProfilePath() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("windows")) { return "C:\\Windows\\System32\\spool\\drivers\\color"; } else if (os.contains("linux")) { // /usr/share/color/icc // /usr/local/share/color/icc // /home/USER_NAME/.color/icc return "/usr/share/color/icc"; } else if (os.contains("mac")) { // /Library/ColorSync/Profiles // /Users/USER_NAME/Library/ColorSync/Profile return "/Library/ColorSync/Profiles"; } else { return null; } } // https://bugs.openjdk.org/browse/JDK-8266075 // https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Process.html#inputReader() public static Charset ConsoleCharset() { try { return Charset.forName(System.getProperty("native.encoding")); } catch (Exception e) { return Charset.defaultCharset(); } } public static String run(String cmd) { try { if (cmd == null || cmd.isBlank()) { return null; } List<String> p = new ArrayList<>(); p.addAll(Arrays.asList(StringTools.splitBySpace(cmd))); return run(p, Charset.defaultCharset()); } catch (Exception e) { return e.toString(); } } public static String run(List<String> command) { return run(command, Charset.defaultCharset()); } public static String run(List<String> command, Charset charset) { try { if (command == null || command.isEmpty()) { return null; } ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); StringBuilder s = new StringBuilder(); try (BufferedReader inReader = process.inputReader(charset)) { String line; while ((line = inReader.readLine()) != null) { s.append(line).append("\n"); } } process.waitFor(); return s.toString(); } catch (Exception e) { return e.toString(); } } public static File runToFile(List<String> command, Charset charset, File file) { try { if (command == null || command.isEmpty() || file == null) { return null; } ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); try (BufferedReader inReader = process.inputReader(charset); BufferedWriter writer = new BufferedWriter(new FileWriter(file, Charset.forName("UTF-8"), false))) { String line; while ((line = inReader.readLine()) != null) { writer.write(line + "\n"); } writer.flush(); } process.waitFor(); return file; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/MessageDigestTools.java
released/MyBox/src/main/java/mara/mybox/tools/MessageDigestTools.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.security.MessageDigest; import java.security.Provider; import java.security.Security; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * * @author mara */ public class MessageDigestTools { public static byte[] SHA256(byte[] bytes) { return messageDigest(bytes, "SHA-256"); } public static byte[] SHA256(FxTask task, File file) { return messageDigest(task, file, "SHA-256"); } public static byte[] SHA256(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "SHA-256"); } public static byte[] SHA1(byte[] bytes) { return messageDigest(bytes, "SHA-1"); } public static byte[] SHA1(FxTask task, File file) { return messageDigest(task, file, "SHA-1"); } public static byte[] SHA1(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "SHA-1"); } public static void SignatureAlgorithms() { try { for (Provider provider : Security.getProviders()) { for (Provider.Service service : provider.getServices()) { if (service.getType().equals("Signature")) { MyBoxLog.debug(service.getAlgorithm()); } } } } catch (Exception e) { MyBoxLog.debug(e); } } public static byte[] MD5(byte[] bytes) { return messageDigest(bytes, "MD5"); } public static byte[] MD5(FxTask task, File file) { return messageDigest(task, file, "MD5"); } public static byte[] MD5(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "MD5"); } // https://docs.oracle.com/javase/10/docs/specs/security/standard-names.html#messagedigest-algorithms public static byte[] messageDigest(byte[] bytes, String algorithm) { try { if (bytes == null || algorithm == null) { return null; } MessageDigest md = MessageDigest.getInstance(algorithm); byte[] digest = md.digest(bytes); return digest; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static byte[] messageDigest(FxTask task, File file, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = in.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } md.update(buf, 0, len); } } byte[] digest = md.digest(); return digest; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.debug(e); } return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileCopyTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileCopyTools.java
package mara.mybox.tools; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import mara.mybox.data.FileSynchronizeAttributes; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileCopyTools { public static boolean copyFile(String sourceFile, String targetFile) { return copyFile(new File(sourceFile), new File(targetFile)); } public static boolean copyFile(File sourceFile, File targetFile) { return copyFile(sourceFile, targetFile, false, true); } public static boolean copyFile(File sourceFile, File targetFile, boolean isCanReplace, boolean isCopyAttrinutes) { try { if (sourceFile == null || !sourceFile.isFile() || !sourceFile.exists()) { return false; } if (isCanReplace) { if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } } else { if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath())); } } return true; } catch (Exception e) { MyBoxLog.error(e + "\n" + "Source:" + sourceFile + "\n" + "Target:" + targetFile); return false; } } public static boolean copyFile(File sourceFile, File targetFile, FileSynchronizeAttributes attr) { if (attr == null) { attr = new FileSynchronizeAttributes(); } return copyFile(sourceFile, targetFile, attr.isCanReplace(), attr.isCopyAttrinutes()); } public static FileSynchronizeAttributes copyWholeDirectory(FxTask task, File sourcePath, File targetPath) { FileSynchronizeAttributes attr = new FileSynchronizeAttributes(); copyWholeDirectory(task, sourcePath, targetPath, attr); return attr; } public static boolean copyWholeDirectory(FxTask task, File sourcePath, File targetPath, FileSynchronizeAttributes attr) { return copyWholeDirectory(task, sourcePath, targetPath, attr, true); } public static boolean copyWholeDirectory(FxTask task, File sourcePath, File targetPath, FileSynchronizeAttributes attr, boolean clearTarget) { try { if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) { return false; } if (FileTools.isEqualOrSubPath(targetPath.getAbsolutePath(), sourcePath.getAbsolutePath())) { MyBoxLog.error(message("TreeTargetComments")); return false; } if (attr == null) { attr = new FileSynchronizeAttributes(); } if (targetPath.exists()) { if (clearTarget && !FileDeleteTools.deleteDir(task, targetPath)) { return false; } } else { targetPath.mkdirs(); } File[] files = sourcePath.listFiles(); if (files == null) { return false; } for (File file : files) { if (task != null && !task.isWorking()) { return false; } File targetFile = new File(targetPath + File.separator + file.getName()); if (file.isFile()) { if (copyFile(file, targetFile, attr)) { attr.setCopiedFilesNumber(attr.getCopiedFilesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } else if (file.isDirectory()) { if (copyWholeDirectory(task, file, targetFile, attr, clearTarget)) { attr.setCopiedDirectoriesNumber(attr.getCopiedDirectoriesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.Arrays; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import org.apache.commons.io.FileUtils; /** * @Author mara * @CreateDate 2018-6-2 11:01:45 * @Description */ public class FileTools { public static long createTime(final String filename) { try { FileTime t = Files.readAttributes(Paths.get(filename), BasicFileAttributes.class).creationTime(); return t.toMillis(); } catch (Exception e) { return -1; } } public static long createTime(File file) { if (file == null || !file.exists()) { return -1; } return createTime(file.getAbsolutePath()); } public static String showFileSize(long size) { if (size < 1024) { return size + " B"; } else { double kb = size * 1.0d / 1024; if (kb < 1024) { return DoubleTools.scale3(kb) + " KB"; } else { double mb = kb / 1024; if (mb < 1024) { return DoubleTools.scale3(mb) + " MB"; } else { double gb = mb / 1024; return DoubleTools.scale3(gb) + " GB"; } } } } public static String fileInformation(File file) { if (file == null) { return null; } StringBuilder s = new StringBuilder(); s.append(message("FileName")) .append(": ").append(file.getAbsolutePath()).append("\n"); s.append(message("FileSize")) .append(": ").append(FileTools.showFileSize(file.length())).append("\n"); s.append(message("FileModifyTime")) .append(": ").append(DateTools.datetimeToString(file.lastModified())); return s.toString(); } public static boolean isSupportedImage(File file) { if (file == null || !file.isFile()) { return false; } String suffix = FileNameTools.ext(file.getName()).toLowerCase(); return FileExtensions.SupportedImages.contains(suffix); } public static boolean rename(File sourceFile, File targetFile) { try { if (sourceFile == null || !sourceFile.exists() || !sourceFile.isFile() || targetFile == null || targetFile.exists() || sourceFile.equals(targetFile)) { return false; } FileUtils.moveFile(sourceFile, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e, sourceFile + " " + targetFile); return false; } } public static boolean override(File sourceFile, File targetFile) { return override(sourceFile, targetFile, false); } public static boolean override(File sourceFile, File targetFile, boolean noEmpty) { try { if (sourceFile == null || !sourceFile.exists() || !sourceFile.isFile() || targetFile == null || sourceFile.equals(targetFile)) { return false; } if (noEmpty && sourceFile.length() == 0) { return false; } synchronized (targetFile) { if (!FileDeleteTools.delete(targetFile)) { return false; } System.gc(); FileUtils.moveFile(sourceFile, targetFile); } // targetFile.getParentFile().mkdirs(); // Files.move(sourceFile.toPath(), targetFile.toPath(), // StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); return true; } catch (Exception e) { MyBoxLog.error(e, sourceFile + " " + targetFile); return false; } } // Return files number and total length public static long[] countDirectorySize(File dir, boolean countSubdir) { long[] size = new long[2]; try { if (dir == null) { return size; } if (dir.isFile()) { size[0] = 1; size[1] = dir.length(); } else if (dir.isDirectory()) { File[] files = dir.listFiles(); size[0] = 0; size[1] = 0; if (files != null) { for (File file : files) { if (file.isFile()) { size[0]++; size[1] += file.length(); } else if (file.isDirectory()) { if (countSubdir) { long[] fsize = countDirectorySize(file, countSubdir); size[0] += fsize[0]; size[1] += fsize[1]; } } } } } } catch (Exception e) { MyBoxLog.debug(e); } return size; } public static boolean same(FxTask task, File file1, File file2) { return Arrays.equals(MessageDigestTools.SHA1(task, file1), MessageDigestTools.SHA1(task, file2)); } public static int bufSize(File file, int memPart) { Runtime r = Runtime.getRuntime(); long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); long min = Math.min(file.length(), availableMem / memPart); return min > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) min; } public static boolean hasData(File file) { return file != null && file.exists() && file.isFile() && file.length() > 0; } public static boolean isEqualOrSubPath(String path1, String path2) { if (path1 == null || path1.isBlank() || path2 == null || path2.isBlank()) { return false; } String name1 = path1.endsWith(File.separator) ? path1 : (path1 + File.separator); String name2 = path1.endsWith(File.separator) ? path2 : (path2 + File.separator); return name1.equals(name2) || name1.startsWith(name2); } public static File removeBOM(FxTask task, File file) { if (!hasData(file)) { return file; } String bom = null; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { byte[] header = new byte[4]; int readLen; if ((readLen = inputStream.read(header, 0, 4)) > 0) { header = ByteTools.subBytes(header, 0, readLen); bom = TextTools.checkCharsetByBom(header); if (bom == null) { return file; } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } File tmpFile = FileTmpTools.getTempFile(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { int bomSize = TextTools.bomSize(bom); inputStream.skip(bomSize); int readLen; byte[] buf = new byte[bufSize(file, 16)]; while ((readLen = inputStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, readLen); } outputStream.flush(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } return tmpFile; } public static File javaIOTmpPath() { return new File(System.getProperty("java.io.tmpdir")); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/BarcodeTools.java
released/MyBox/src/main/java/mara/mybox/tools/BarcodeTools.java
package mara.mybox.tools; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.pdf417.encoder.Compaction; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.AppVariables; import org.krysalis.barcode4j.ChecksumMode; import org.krysalis.barcode4j.HumanReadablePlacement; import org.krysalis.barcode4j.impl.AbstractBarcodeBean; import org.krysalis.barcode4j.impl.codabar.CodabarBean; import org.krysalis.barcode4j.impl.code128.Code128Bean; import org.krysalis.barcode4j.impl.code39.Code39Bean; import org.krysalis.barcode4j.impl.datamatrix.DataMatrixBean; import org.krysalis.barcode4j.impl.fourstate.RoyalMailCBCBean; import org.krysalis.barcode4j.impl.int2of5.Interleaved2Of5Bean; import org.krysalis.barcode4j.impl.pdf417.PDF417Bean; import org.krysalis.barcode4j.impl.postnet.POSTNETBean; import org.krysalis.barcode4j.impl.upcean.EAN13Bean; import org.krysalis.barcode4j.impl.upcean.EAN8Bean; import org.krysalis.barcode4j.impl.upcean.UPCABean; import org.krysalis.barcode4j.impl.upcean.UPCEBean; import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; import thridparty.QRCodeWriter; /** * @Author Mara * @CreateDate 2019-9-24 * @Description * @License Apache License Version 2.0 */ public class BarcodeTools { public enum BarcodeType { QR_Code, PDF_417, DataMatrix, Code39, Code128, Codabar, Interleaved2Of5, ITF_14, POSTNET, EAN13, EAN8, EAN_128, UPCA, UPCE, Royal_Mail_Customer_Barcode, USPS_Intelligent_Mail } public static double defaultModuleWidth(BarcodeType type) { switch (type) { case PDF_417: return new PDF417Bean().getModuleWidth(); case Code39: return new Code39Bean().getModuleWidth(); case Code128: return new Code128Bean().getModuleWidth(); case Codabar: return new CodabarBean().getModuleWidth(); case Interleaved2Of5: return new Interleaved2Of5Bean().getModuleWidth(); case POSTNET: return new POSTNETBean().getModuleWidth(); case EAN13: return new EAN13Bean().getModuleWidth(); case EAN8: return new EAN8Bean().getModuleWidth(); case UPCA: return new UPCABean().getModuleWidth(); case UPCE: return new UPCEBean().getModuleWidth(); case Royal_Mail_Customer_Barcode: return new RoyalMailCBCBean().getModuleWidth(); case DataMatrix: return new DataMatrixBean().getModuleWidth(); } return 0.20f; } public static double defaultBarRatio(BarcodeType type) { switch (type) { case Code39: return new Code39Bean().getWideFactor(); case Codabar: return new CodabarBean().getWideFactor(); case Interleaved2Of5: return new Interleaved2Of5Bean().getWideFactor(); } return 2.0; } public static BufferedImage QR(FxTask task, String code, ErrorCorrectionLevel qrErrorCorrectionLevel, int qrWidth, int qrHeight, int qrMargin, File picFile) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, qrErrorCorrectionLevel); hints.put(EncodeHintType.MARGIN, qrMargin); QRCodeWriter writer = new QRCodeWriter(); BitMatrix bitMatrix = writer.encode(code, BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints); BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix); if (picFile != null) { BufferedImage pic = ImageFileReaders.readImage(task, picFile); if (pic != null) { double ratio = 2; switch (qrErrorCorrectionLevel) { case L: ratio = 0.16; break; case M: ratio = 0.20; break; case Q: ratio = 0.25; break; case H: ratio = 0.30; break; } // https://www.cnblogs.com/tuyile006/p/3416008.html // ratio = Math.min(2 / 7d, ratio); int width = (int) ((qrImage.getWidth() - writer.getLeftPadding() * 2) * ratio); int height = (int) ((qrImage.getHeight() - writer.getTopPadding() * 2) * ratio); return BarcodeTools.centerPicture(qrImage, pic, width, height); } } return qrImage; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage centerPicture(BufferedImage source, BufferedImage picture, int w, int h) { try { if (w <= 0 || h <= 0 || picture == null || picture.getWidth() == 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int ah = h, aw = w; if (w * 1.0f / h > picture.getWidth() * 1.0f / picture.getHeight()) { ah = picture.getHeight() * w / picture.getWidth(); } else { aw = picture.getWidth() * h / picture.getHeight(); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.drawImage(source, 0, 0, width, height, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g.drawImage(picture, (width - aw) / 2, (height - ah) / 2, aw, ah, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage PDF417(String code, int pdf417ErrorCorrectionLevel, Compaction pdf417Compact, int pdf417Width, int pdf417Height, int pdf417Margin) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, pdf417ErrorCorrectionLevel); hints.put(EncodeHintType.MARGIN, pdf417Margin); if (pdf417Compact == null) { hints.put(EncodeHintType.PDF417_COMPACT, false); } else { hints.put(EncodeHintType.PDF417_COMPACT, true); hints.put(EncodeHintType.PDF417_COMPACTION, pdf417Compact); } BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.PDF_417, pdf417Width, pdf417Height, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage DataMatrix(String code, int dmWidth, int dmHeigh) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.DATA_MATRIX, dmWidth, dmHeigh, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage createBarcode( BarcodeType type, String code, double height, double narrowWidth, double barRatio, double quietWidth, HumanReadablePlacement textPostion, String fontName, int fontSize, int dpi, boolean antiAlias, int orientation, boolean checksum, boolean startstop) { try { AbstractBarcodeBean bean = null; switch (type) { case Code39: Code39Bean code39 = new Code39Bean(); code39.setWideFactor(barRatio); code39.setDisplayChecksum(checksum); code39.setDisplayStartStop(startstop); code39.setExtendedCharSetEnabled(true); code39.setChecksumMode(ChecksumMode.CP_ADD); bean = code39; break; case Code128: Code128Bean code128 = new Code128Bean(); bean = code128; break; case Codabar: CodabarBean codabar = new CodabarBean(); codabar.setWideFactor(barRatio); bean = codabar; break; } if (bean == null) { return null; } bean.setFontName(code); bean.setFontSize(fontSize); bean.setModuleWidth(narrowWidth); bean.setHeight(height); bean.setQuietZone(quietWidth); bean.setMsgPosition(textPostion); BitmapCanvasProvider canvas = new BitmapCanvasProvider( dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation); bean.generateBarcode(canvas, code); canvas.finish(); return canvas.getBufferedImage(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage createCode39( BarcodeType type, String code, double height, double narrowWidth, double barRatio, double quietWidth, HumanReadablePlacement textPostion, String fontName, int fontSize, int dpi, boolean antiAlias, int orientation, boolean checksum, boolean startstop) { try { Code39Bean code39 = new Code39Bean(); code39.setWideFactor(barRatio); code39.setDisplayChecksum(checksum); code39.setDisplayStartStop(startstop); code39.setExtendedCharSetEnabled(true); code39.setChecksumMode(ChecksumMode.CP_ADD); code39.setFontName(code); code39.setFontSize(fontSize); code39.setModuleWidth(narrowWidth); code39.setHeight(height); code39.setQuietZone(quietWidth); code39.setMsgPosition(textPostion); BitmapCanvasProvider canvas = new BitmapCanvasProvider( dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation); code39.generateBarcode(canvas, code); canvas.finish(); return canvas.getBufferedImage(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FloatTools.java
released/MyBox/src/main/java/mara/mybox/tools/FloatTools.java
package mara.mybox.tools; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import static mara.mybox.tools.DoubleTools.numberFormat; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2019-5-28 15:31:28 * @License Apache License Version 2.0 */ public class FloatTools { public static boolean invalidFloat(Float value) { return value == null || Float.isNaN(value) || Float.isInfinite(value) || value == AppValues.InvalidFloat; } public static String percentage(float data, float total) { try { String format = "#,###.##"; DecimalFormat df = new DecimalFormat(format); return df.format(scale(data * 100 / total, 2)); } catch (Exception e) { return data + ""; } } public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Float.parseFloat(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Float.parseFloat(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } return compare(f1, f2, desc); } // invalid values are counted as smaller public static int compare(float f1, float f2, boolean desc) { if (Float.isNaN(f1)) { if (Float.isNaN(f2)) { return 0; } else { return desc ? 1 : -1; } } else { if (Float.isNaN(f2)) { return desc ? -1 : 1; } else { float diff = f1 - f2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } public static float scale(float v, int scale) { try { if (numberFormat == null) { numberFormat(); } numberFormat.setMaximumFractionDigits(scale); return Float.parseFloat(numberFormat.format(v)); } catch (Exception e) { return v; } } public static int toInt(float v) { try { return (int) scale(v, 0); } catch (Exception e) { return (int) v; } } public static float roundFloat2(float fvalue) { return scale(fvalue, 2); } public static float roundFloat5(float fvalue) { return scale(fvalue, 5); } public static double[] toDouble(float[] f) { if (f == null) { return null; } double[] d = new double[f.length]; for (int i = 0; i < f.length; ++i) { d[i] = f[i]; } return d; } public static double[][] toDouble(float[][] f) { if (f == null) { return null; } double[][] d = new double[f.length][f[0].length]; for (int i = 0; i < f.length; ++i) { for (int j = 0; j < f[i].length; ++j) { d[i][j] = f[i][j]; } } return d; } public static float random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); float f = r.nextFloat(max); return sign == 1 ? f : -f; } public static String format(float v, String format, int scale) { if (invalidFloat(v)) { return null; } return NumberTools.format(v, format, scale); } public static float[] sortArray(float[] numbers) { List<Float> list = new ArrayList<>(); for (float i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Float>() { @Override public int compare(Float p1, Float p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); float[] sorted = new float[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/OCRTools.java
released/MyBox/src/main/java/mara/mybox/tools/OCRTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.AppVariables.MyboxDataPath; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-21 * @License Apache License Version 2.0 */ public class OCRTools { // https://github.com/nguyenq/tess4j/blob/master/src/test/java/net/sourceforge/tess4j/Tesseract1Test.java#L177 public static final double MINIMUM_DESKEW_THRESHOLD = 0.05d; public static final String TessDataPath = "TessDataPath"; // Generate each time because user may change the interface language. public static Map<String, String> codeName() { // if (CodeName != null) { // return CodeName; // } Map<String, String> named = new HashMap<>(); named.put("chi_sim", Languages.message("SimplifiedChinese")); named.put("chi_sim_vert", Languages.message("SimplifiedChineseVert")); named.put("chi_tra", Languages.message("TraditionalChinese")); named.put("chi_tra_vert", Languages.message("TraditionalChineseVert")); named.put("eng", Languages.message("English")); named.put("equ", Languages.message("MathEquation")); named.put("osd", Languages.message("OrientationScript")); return named; } public static Map<String, String> nameCode() { // if (NameCode != null) { // return NameCode; // } Map<String, String> codes = codeName(); Map<String, String> names = new HashMap<>(); for (String code : codes.keySet()) { names.put(codes.get(code), code); } return names; } public static List<String> codes() { // if (Codes != null) { // return Codes; // } List<String> Codes = new ArrayList<>(); Codes.add("chi_sim"); Codes.add("chi_sim_vert"); Codes.add("chi_tra"); Codes.add("chi_tra_vert"); Codes.add("eng"); Codes.add("equ"); Codes.add("osd"); return Codes; } public static List<String> names() { // if (Names != null) { // return Names; // } List<String> Names = new ArrayList<>(); Map<String, String> codes = codeName(); for (String code : codes()) { Names.add(codes.get(code)); } return Names; } // Make sure supported language files are under defined data path public static boolean initDataFiles() { try { String pathname = UserConfig.getString(TessDataPath, null); if (pathname == null) { pathname = MyboxDataPath + File.separator + "tessdata"; } File path = new File(pathname); if (!path.exists() || !path.isDirectory()) { path = new File(MyboxDataPath + File.separator + "tessdata"); path.mkdirs(); } File chi_sim = new File(path.getAbsolutePath() + File.separator + "chi_sim.traineddata"); if (!chi_sim.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim.traineddata"); FileCopyTools.copyFile(tmp, chi_sim); } File chi_sim_vert = new File(path.getAbsolutePath() + File.separator + "chi_sim_vert.traineddata"); if (!chi_sim_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_sim_vert); } File chi_tra = new File(path.getAbsolutePath() + File.separator + "chi_tra.traineddata"); if (!chi_tra.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra.traineddata"); FileCopyTools.copyFile(tmp, chi_tra); } File chi_tra_vert = new File(path.getAbsolutePath() + File.separator + "chi_tra_vert.traineddata"); if (!chi_tra_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_tra_vert); } File equ = new File(path.getAbsolutePath() + File.separator + "equ.traineddata"); if (!equ.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/equ.traineddata"); FileCopyTools.copyFile(tmp, equ); } File eng = new File(path.getAbsolutePath() + File.separator + "eng.traineddata"); if (!eng.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/eng.traineddata"); FileCopyTools.copyFile(tmp, eng); } File osd = new File(path.getAbsolutePath() + File.separator + "osd.traineddata"); if (!osd.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/tessdata/osd.traineddata"); FileCopyTools.copyFile(tmp, osd); } UserConfig.setString(TessDataPath, path.getAbsolutePath()); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static List<String> namesList(boolean copyFiles) { List<String> data = new ArrayList<>(); try { if (copyFiles) { initDataFiles(); } String dataPath = UserConfig.getString(TessDataPath, null); if (dataPath == null) { return data; } data.addAll(names()); List<String> codes = codes(); File[] files = new File(dataPath).listFiles(); if (files != null) { for (File f : files) { String name = f.getName(); if (!f.isFile() || !name.endsWith(".traineddata")) { continue; } String code = name.substring(0, name.length() - ".traineddata".length()); if (codes.contains(code)) { continue; } data.add(code); } } } catch (Exception e) { MyBoxLog.debug(e); } return data; } public static String name(String code) { Map<String, String> codes = codeName(); return codes.get(code); } public static String code(String name) { Map<String, String> names = nameCode(); return names.get(name); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/GeographyCodeTools.java
released/MyBox/src/main/java/mara/mybox/tools/GeographyCodeTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import mara.mybox.data.GeographyCode; import mara.mybox.data.GeographyCode.AddressLevel; import mara.mybox.data.GeographyCode.CoordinateSystem; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import thridparty.CoordinateConverter; /** * @Author Mara * @CreateDate 2020-8-11 * @License Apache License Version 2.0 */ public class GeographyCodeTools { /* Coordinate System */ public static String coordinateSystemMessageNames() { String s = ""; for (CoordinateSystem v : CoordinateSystem.values()) { if (!s.isBlank()) { s += "\n"; } s += message(v.name()); } return s; } public static CoordinateSystem coordinateSystemByName(String name) { try { return CoordinateSystem.valueOf(name); } catch (Exception e) { return GeographyCode.defaultCoordinateSystem; } } public static CoordinateSystem coordinateSystemByValue(short value) { try { return CoordinateSystem.values()[value]; } catch (Exception e) { return GeographyCode.defaultCoordinateSystem; } } public static short coordinateSystemValue(CoordinateSystem cs) { try { return (short) cs.ordinal(); } catch (Exception e) { return 0; } } public static String coordinateSystemName(short value) { try { return coordinateSystemByValue(value).name(); } catch (Exception e) { return null; } } public static String coordinateSystemMessageName(short value) { try { return message(coordinateSystemName(value)); } catch (Exception e) { return null; } } /* Address Level */ public static String addressLevelMessageNames() { String s = ""; for (AddressLevel v : AddressLevel.values()) { if (!s.isBlank()) { s += "\n"; } s += message(v.name()); } return s; } public static AddressLevel addressLevelByName(String name) { try { return AddressLevel.valueOf(name); } catch (Exception e) { return GeographyCode.defaultAddressLevel; } } public static AddressLevel addressLevelByValue(short value) { try { return AddressLevel.values()[value]; } catch (Exception e) { return GeographyCode.defaultAddressLevel; } } public static short addressLevelValue(AddressLevel level) { try { return (short) level.ordinal(); } catch (Exception e) { return 0; } } public static String addressLevelName(short value) { try { return addressLevelByValue(value).name(); } catch (Exception e) { return null; } } public static String addressLevelMessageName(short value) { try { return message(addressLevelName(value)); } catch (Exception e) { return null; } } /* map */ public static String gaodeMap(int zoom) { try { File map = FxFileTools.getInternalFile("/js/GaoDeMap.html", "js", "GaoDeMap.html", false); String html = TextFileTools.readTexts(null, map); html = html.replace(AppValues.GaoDeMapJavascriptKey, UserConfig.getString("GaoDeMapWebKey", AppValues.GaoDeMapJavascriptKey)) .replace("MyBoxMapZoom", zoom + ""); return html; } catch (Exception e) { MyBoxLog.error(e.toString()); return ""; } } public static File tiandituFile(boolean geodetic, int zoom) { try { File map = FxFileTools.getInternalFile("/js/tianditu.html", "js", "tianditu.html", false); String html = TextFileTools.readTexts(null, map); html = html.replace(AppValues.TianDiTuWebKey, UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey)) .replace("MyBoxMapZoom", zoom + ""); if (geodetic) { html = html.replace("'EPSG:900913", "EPSG:4326"); } TextFileTools.writeFile(map, html); return map; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } /* Query codes by web service */ public static GeographyCode geoCode(CoordinateSystem coordinateSystem, String address) { try { if (coordinateSystem == null) { return null; } if (coordinateSystem == CoordinateSystem.GCJ_02) { // GaoDe Map only supports info codes of China String urlString = "https://restapi.amap.com/v3/geocode/geo?address=" + URLEncoder.encode(address, "UTF-8") + "&output=xml&key=" + UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setChineseName(address); geographyCode.setCoordinateSystem(coordinateSystem); return gaodeCode(urlString, geographyCode); } else if (coordinateSystem == CoordinateSystem.CGCS2000) { // http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"泰山"}&tk=0ddeb917def62b4691500526cc30a9b1 String urlString = "http://api.tianditu.gov.cn/geocoder?ds=" + URLEncoder.encode("{\"keyWord\":\"" + address + "\"}", "UTF-8") + "&tk=" + UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey); URL url = UrlTools.url(urlString); if (url == null) { return null; } File jsonFile = FileTmpTools.getTempFile(".json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } } String data = TextFileTools.readTexts(null, jsonFile); double longitude = -200; double latitude = -200; String flag = "\"lon\":"; int pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { longitude = Double.parseDouble(subData.substring(0, pos)); } catch (Exception e) { } } } flag = "\"lat\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { latitude = Double.parseDouble(subData.substring(0, pos)); } catch (Exception e) { } } } if (validCoordinate(longitude, latitude)) { return GeographyCodeTools.geoCode(coordinateSystem, longitude, latitude); } } return null; } catch (Exception e) { return null; } } public static GeographyCode geoCode(CoordinateSystem coordinateSystem, double longitude, double latitude) { try { if (coordinateSystem == null) { return null; } if (coordinateSystem == CoordinateSystem.GCJ_02) { String urlString = "https://restapi.amap.com/v3/geocode/regeo?location=" + longitude + "," + latitude + "&output=xml&key=" + UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setLongitude(longitude); geographyCode.setLatitude(latitude); geographyCode.setCoordinateSystem(coordinateSystem); return gaodeCode(urlString, geographyCode); } else if (coordinateSystem == CoordinateSystem.CGCS2000) { String urlString = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + longitude + ",'lat':" + latitude + ",'ver':1}&type=geocode&tk=" + UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setLongitude(longitude); geographyCode.setLatitude(latitude); geographyCode.setCoordinateSystem(coordinateSystem); return tiandituCode(urlString, geographyCode); } return null; } catch (Exception e) { return null; } } //{"result":{"formatted_address":"泰安市泰山区升平街39号(泰山区区政府大院内)泰山区统计局", // "location":{"lon":117.12899999995,"lat":36.19280999998}, // "addressComponent":{"address":"泰山区升平街39号(泰山区区政府大院内)","city":"泰安市", // "county_code":"156370902","nation":"中国","poi_position":"西北","county":"泰山区","city_code":"156370900", // "address_position":"西北","poi":"泰山区统计局","province_code":"156370000","province":"山东省","road":"运粮街", //"road_distance":65,"poi_distance":10,"address_distance":10}},"msg":"ok","status":"0"} public static GeographyCode tiandituCode(String urlString, GeographyCode geographyCode) { try { URL url = UrlTools.url(urlString); if (url == null) { return null; } File jsonFile = FileTmpTools.getTempFile(".json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } } String data = TextFileTools.readTexts(null, jsonFile); // MyBoxLog.debug(data); String flag = "\"formatted_address\":\""; int pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"lon\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { double longitude = Double.parseDouble(subData.substring(0, pos)); geographyCode.setLongitude(longitude); } catch (Exception e) { } } } flag = "\"lat\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "}"; pos = subData.indexOf(flag); if (pos >= 0) { try { double latitude = Double.parseDouble(subData.substring(0, pos)); geographyCode.setLatitude(latitude); } catch (Exception e) { } } } flag = "\"address\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"city\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCity(subData.substring(0, pos)); } } flag = "\"county_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode3(subData.substring(0, pos)); } } flag = "\"nation\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCountry(subData.substring(0, pos)); } } flag = "\"county\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCounty(subData.substring(0, pos)); } } flag = "\"city_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode2(subData.substring(0, pos)); } } flag = "\"poi\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"province_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode1(subData.substring(0, pos)); } } flag = "\"province\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setProvince(subData.substring(0, pos)); } } flag = "\"road\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setVillage(subData.substring(0, pos)); } } // if (!validCoordinate(geographyCode)) { // return null; // } return geographyCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } // {"status":"1","info":"OK","infocode":"10000","count":"1","geocodes": // [{"formatted_address":"山东省泰安市泰山区泰山","country":"中国","province":"山东省","citycode":"0538", //"city":"泰安市","county":"泰山区","township":[], //"village":{"name":[],"type":[]}, //"building":{"name":[],"type":[]}, //"adcode":"370902","town":[],"number":[],"location":"117.157242,36.164988","levelCode":"兴趣点"}]} public static GeographyCode gaodeCode(String urlString, GeographyCode geographyCode) { try { URL url = UrlTools.url(urlString); if (url == null) { return null; } File xmlFile = HtmlReadTools.download(null, url.toString()); // MyBoxLog.debug(FileTools.readTexts(xmlFile)); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile); NodeList nodes = doc.getElementsByTagName("formatted_address"); if (nodes != null && nodes.getLength() > 0) { String name = nodes.item(0).getTextContent(); setName(geographyCode, name); } nodes = doc.getElementsByTagName("country"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCountry(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("province"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setProvince(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("citycode"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode2(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("city"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCity(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("district"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCounty(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("township"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setTown(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("neighborhood"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setVillage(nodes.item(0).getFirstChild().getTextContent()); } nodes = doc.getElementsByTagName("building"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setBuilding(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("adcode"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode1(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("streetNumber"); if (nodes != null && nodes.getLength() > 0) { nodes = nodes.item(0).getChildNodes(); if (nodes != null) { Map<String, String> values = new HashMap<>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); values.put(node.getNodeName(), node.getTextContent()); } String s = ""; String v = values.get("street"); if (v != null) { s += v; } v = values.get("number"); if (v != null) { s += v; } v = values.get("location"); if (v != null) { s += v; } v = values.get("direction"); if (v != null) { s += v; } v = values.get("distance"); if (v != null) { s += v; } if (geographyCode.getBuilding() == null) { geographyCode.setBuilding(s); } else { setName(geographyCode, s); } } } else { nodes = doc.getElementsByTagName("street"); if (nodes != null && nodes.getLength() > 0) { String s = nodes.item(0).getTextContent(); if (geographyCode.getBuilding() == null) { geographyCode.setBuilding(s); } else { setName(geographyCode, s); } } nodes = doc.getElementsByTagName("number"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode5(nodes.item(0).getTextContent()); } if (!validCoordinate(geographyCode)) { nodes = doc.getElementsByTagName("location"); if (nodes != null && nodes.getLength() > 0) { String[] values = nodes.item(0).getFirstChild().getTextContent().split(","); geographyCode.setLongitude(Double.parseDouble(values[0].trim())); geographyCode.setLatitude(Double.parseDouble(values[1].trim())); } else { geographyCode.setLongitude(-200); geographyCode.setLatitude(-200); } } if (geographyCode.getChineseName() == null) { geographyCode.setChineseName(geographyCode.getLongitude() + "," + geographyCode.getLatitude()); } nodes = doc.getElementsByTagName("level"); if (nodes != null && nodes.getLength() > 0) { String v = nodes.item(0).getTextContent(); if (message("zh", "Country").equals(v)) { geographyCode.setLevel(AddressLevel.Country); } else if (message("zh", "Province").equals(v)) { geographyCode.setLevel(AddressLevel.Province); } else if (message("zh", "City").equals(v)) { geographyCode.setLevel(AddressLevel.City); } else if (message("zh", "County").equals(v)) { geographyCode.setLevel(AddressLevel.County); } else if (message("zh", "Town").equals(v)) { geographyCode.setLevel(AddressLevel.Town); } else if (message("zh", "Neighborhood").equals(v)) { geographyCode.setLevel(AddressLevel.Village); } else if (message("zh", "PointOfInterest").equals(v)) { geographyCode.setLevel(AddressLevel.PointOfInterest); } else if (message("zh", "Street").equals(v)) { geographyCode.setLevel(AddressLevel.Village); } else if (message("zh", "Building").equals(v)) { geographyCode.setLevel(AddressLevel.Building); } else { geographyCode.setLevel(AddressLevel.PointOfInterest); } } } // if (!validCoordinate(geographyCode)) { // return null; // } return geographyCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean setName(GeographyCode geographyCode, String name) { if (geographyCode.getChineseName() == null) { geographyCode.setChineseName(name); return true; } else if (!geographyCode.getChineseName().equals(name)) { if (geographyCode.getAlias1() == null) { geographyCode.setAlias1(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias1().equals(name)) { if (geographyCode.getAlias2() == null) { geographyCode.setAlias2(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias2().equals(name)) { if (geographyCode.getAlias3() == null) { geographyCode.setAlias3(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias3().equals(name)) { if (geographyCode.getAlias4() == null) { geographyCode.setAlias4(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias4().equals(name)) { geographyCode.setAlias5(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } } } } } return false; } public static String gaodeConvertService(CoordinateSystem cs) { if (cs == null) { cs = GeographyCode.defaultCoordinateSystem; } switch (cs) { case CGCS2000: return "gps"; case GCJ_02: return "autonavi"; case WGS_84: return "gps"; case BD_09: return "baidu"; case Mapbar: return "mapbar"; default: return "autonavi"; } } /* Convert */ public static GeographyCode fromNode(DataNode node) { if (node == null) { return null; } GeographyCode code = new GeographyCode(); code.setTitle(node.getTitle()); code.setLevel(addressLevelByValue(node.getShortValue("level"))); code.setCoordinateSystem(coordinateSystemByValue(node.getShortValue("coordinate_system"))); double d = node.getDoubleValue("longitude"); code.setLongitude((DoubleTools.invalidDouble(d) || d > 180 || d < -180) ? -200 : d); d = node.getDoubleValue("latitude"); code.setLatitude((DoubleTools.invalidDouble(d) || d > 90 || d < -90) ? -200 : d); code.setAltitude(node.getDoubleValue("altitude")); code.setPrecision(node.getDoubleValue("precision")); code.setChineseName(node.getStringValue("chinese_name")); code.setEnglishName(node.getStringValue("english_name")); code.setContinent(node.getStringValue("continent")); code.setCountry(node.getStringValue("country")); code.setProvince(node.getStringValue("province")); code.setCity(node.getStringValue("city")); code.setCounty(node.getStringValue("county")); code.setTown(node.getStringValue("town")); code.setVillage(node.getStringValue("village")); code.setBuilding(node.getStringValue("building")); code.setPoi(node.getStringValue("poi")); code.setAlias1(node.getStringValue("alias1")); code.setAlias2(node.getStringValue("alias2")); code.setAlias3(node.getStringValue("alias3")); code.setAlias4(node.getStringValue("alias4")); code.setAlias5(node.getStringValue("alias5")); code.setCode1(node.getStringValue("code1")); code.setCode2(node.getStringValue("code2")); code.setCode3(node.getStringValue("code3")); code.setCode4(node.getStringValue("code4")); code.setCode5(node.getStringValue("code5")); code.setDescription(node.getStringValue("description")); d = node.getDoubleValue("area"); code.setArea(DoubleTools.invalidDouble(d) || d <= 0 ? -1 : d); long p = node.getLongValue("population"); code.setPopulation(LongTools.invalidLong(p) || p <= 0 ? -1 : p); return code; } public static DataNode toNode(GeographyCode code) { if (code == null) { return null; } DataNode node = new DataNode(); node.setTitle(code.getTitle()); node.setValue("level", addressLevelValue(code.getLevel())); node.setValue("coordinate_system", coordinateSystemValue(code.getCoordinateSystem())); node.setValue("longitude", code.getLongitude()); node.setValue("latitude", code.getLatitude()); node.setValue("precision", code.getPrecision()); node.setValue("chinese_name", code.getChineseName()); node.setValue("english_name", code.getEnglishName()); node.setValue("continent", code.getContinent()); node.setValue("country", code.getCountry()); node.setValue("province", code.getProvince()); node.setValue("city", code.getCity()); node.setValue("county", code.getCounty()); node.setValue("town", code.getTown()); node.setValue("village", code.getVillage()); node.setValue("building", code.getBuilding()); node.setValue("poi", code.getPoi()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("description", code.getDescription()); node.setValue("area", code.getArea()); node.setValue("population", code.getPopulation()); return node; } public static GeographyCode toCGCS2000(GeographyCode code, boolean setCS) { GeographyCode converted = toWGS84(code); if (converted != null && setCS) { converted.setCoordinateSystem(CoordinateSystem.CGCS2000); } return converted; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/LongTools.java
released/MyBox/src/main/java/mara/mybox/tools/LongTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-10-4 * @License Apache License Version 2.0 */ public class LongTools { public static boolean invalidLong(Long value) { return value == null || value == AppValues.InvalidLong; } public static int compare(String s1, String s2, boolean desc) { double d1, d2; try { d1 = Long.parseLong(s1.replaceAll(",", "")); } catch (Exception e) { d1 = Double.NaN; } try { d2 = Long.parseLong(s2.replaceAll(",", "")); } catch (Exception e) { d2 = Double.NaN; } return DoubleTools.compare(d1, d2, desc); } public static long random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); long l = r.nextLong(max); return sign == 1 ? l : -l; } public static String format(long v, String format, int scale) { if (invalidLong(v)) { return null; } return NumberTools.format(v, format, scale); } public static long[] sortArray(long[] numbers) { List<Long> list = new ArrayList<>(); for (long i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Long>() { @Override public int compare(Long p1, Long p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); long[] sorted = new long[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/HtmlWriteTools.java
released/MyBox/src/main/java/mara/mybox/tools/HtmlWriteTools.java
package mara.mybox.tools; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.util.data.MutableDataHolder; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import mara.mybox.controller.HtmlEditorController; import mara.mybox.data.FindReplaceString; import mara.mybox.data.Link; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.style.HtmlStyles; import static mara.mybox.value.AppValues.Indent; import mara.mybox.value.Languages; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class HtmlWriteTools { /* edit html */ public static File writeHtml(String html) { try { File htmFile = FileTmpTools.getTempFile(".html"); Charset charset = HtmlReadTools.charset(html); TextFileTools.writeFile(htmFile, html, charset); return htmFile; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void editHtml(String html) { try { File htmFile = writeHtml(html); HtmlEditorController.openFile(htmFile); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void editHtml(String title, String body) { editHtml(html(title, body)); } /* build html */ public static String emptyHmtl(String title) { String body = title == null ? "<BODY>\n\n\n</BODY>\n" : "<BODY>\n<h2>" + title + "</h2>\n</BODY>\n"; return html(title, "utf-8", null, body); } public static String htmlPrefix(String title, String charset, String styleValue) { StringBuilder s = new StringBuilder(); s.append("<HTML>\n").append(Indent).append("<HEAD>\n"); if (charset == null || charset.isBlank()) { charset = "utf-8"; } s.append(Indent).append(Indent) .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=") .append(charset).append("\" />\n"); if (title != null && !title.isBlank()) { s.append(Indent).append(Indent).append("<TITLE>") .append(title).append("</TITLE>\n"); } if (styleValue != null && !styleValue.isBlank()) { s.append(Indent).append(Indent).append("<style type=\"text/css\">\n"); s.append(Indent).append(Indent).append(Indent).append(styleValue).append("\n"); s.append(Indent).append(Indent).append("</style>\n"); } s.append(Indent).append("</HEAD>\n"); return s.toString(); } public static String htmlPrefix() { return htmlPrefix(null, "utf-8", HtmlStyles.DefaultStyle); } public static String html(String title, String body) { return html(title, "utf-8", HtmlStyles.DefaultStyle, body); } public static String html(String title, String style, String body) { return html(title, "utf-8", style, body); } public static String html(String title, String charset, String styleValue, String body) { StringBuilder s = new StringBuilder(); s.append(htmlPrefix(title, charset, styleValue)); s.append(body); s.append("</HTML>\n"); return s.toString(); } public static String html(String body) { return html(null, "utf-8", HtmlStyles.DefaultStyle, body); } public static String table(String body) { return html(null, "utf-8", HtmlStyles.TableStyle, body); } public static String style(String html, String styleValue) { try { Document doc = Jsoup.parse(html); if (doc == null) { return null; } Charset charset = doc.charset(); if (charset == null) { charset = Charset.forName("UTF-8"); } return html(doc.title(), charset.name(), styleValue, HtmlReadTools.body(html, true)); } catch (Exception e) { return null; } } public static String addStyle(String html, String style) { try { if (html == null || style == null) { return "InvalidData"; } Document doc = Jsoup.parse(html); if (doc == null) { return null; } doc.head().appendChild(new Element("style").text(style)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* convert html */ public static String escapeHtml(String string) { if (string == null) { return null; } return string.replace("&", "&amp;") .replace("\"", "&quot;") .replace("'", "&#39;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\\x20", "&nbsp;") .replace("©", "&copy;") .replace("®", "&reg;") .replace("™", "&trade;"); } public static String stringToHtml(String string) { if (string == null) { return null; } return escapeHtml(string) .replaceAll("\r\n|\n|\r", "<BR>\n"); } public static String textToHtml(String text) { if (text == null) { return null; } String body = stringToHtml(text); return html(null, "<BODY>\n<DIV>\n" + body + "\n</DIV>\n</BODY>"); } public static String codeToHtml(String text) { if (text == null) { return null; } return "<PRE><CODE>" + escapeHtml(text) + "</CODE></PRE>"; } public static String htmlToText(String html) { try { if (html == null || html.isBlank()) { return html; } else { return Jsoup.parse(html).wholeText(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(String md, Parser htmlParser, HtmlRenderer htmlRender) { try { if (htmlParser == null || htmlRender == null || md == null || md.isBlank()) { return null; } com.vladsch.flexmark.util.ast.Node document = htmlParser.parse(md); String html = htmlRender.render(document); return html; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(String md) { try { if (md == null || md.isBlank()) { return null; } MutableDataHolder htmlOptions = MarkdownTools.htmlOptions(); Parser htmlParser = Parser.builder(htmlOptions).build(); HtmlRenderer htmlRender = HtmlRenderer.builder(htmlOptions).build(); return md2html(md, htmlParser, htmlRender); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String setCharset(FxTask task, String html, Charset charset) { try { if (html == null) { return "InvalidData"; } Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (setCharset(task, doc, charset)) { return doc.outerHtml(); } else { return null; } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean setCharset(FxTask task, Document doc, Charset charset) { try { if (doc == null) { return false; } if (charset == null) { charset = Charset.forName("utf-8"); } Elements children = doc.head().children(); for (Element e : children) { if (task != null && !task.isWorking()) { return false; } if (!e.tagName().equalsIgnoreCase("meta")) { continue; } if (e.hasAttr("charset")) { e.remove(); } if ("Content-Type".equalsIgnoreCase(e.attr("http-equiv")) && e.hasAttr("content")) { e.remove(); } } Element meta1 = new Element("meta") .attr("http-equiv", "Content-Type") .attr("content", "text/html; charset=" + charset.name()); Element meta2 = new Element("meta") .attr("charset", charset.name()); doc.head().appendChild(meta1).appendChild(meta2); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String setEquiv(FxTask task, File htmlFile, Charset charset, String key, String value) { try { if (htmlFile == null || key == null || value == null) { return "InvalidData"; } String html = TextFileTools.readTexts(task, htmlFile, charset); Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (!"Content-Type".equalsIgnoreCase(key)) { if (setCharset(task, doc, charset)) { return doc.outerHtml(); } else { return "Canceled"; } } Elements children = doc.head().children(); for (Element e : children) { if (task != null && !task.isWorking()) { return null; } if (!e.tagName().equalsIgnoreCase("meta") || !e.hasAttr("http-equiv")) { continue; } if (key.equalsIgnoreCase(e.attr("http-equiv")) && e.hasAttr("content")) { e.remove(); } } Element meta1 = new Element("meta") .attr("http-equiv", key) .attr("content", value); doc.head().appendChild(meta1); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String ignoreHead(FxTask task, String html) { try { Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } doc.head().empty(); Charset charset = doc.charset(); if (charset == null) { charset = Charset.forName("utf-8"); } if (setCharset(task, doc, charset)) { return html; } else { return "Canceled"; } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toUTF8(FxTask task, File htmlFile) { return setCharset(task, TextFileTools.readTexts(task, htmlFile), Charset.forName("utf-8")); } public static String setStyle(FxTask task, File htmlFile, Charset charset, String css, boolean ignoreOriginal) { try { if (htmlFile == null || css == null) { return "InvalidData"; } String html = TextFileTools.readTexts(task, htmlFile, charset); Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (charset == null) { charset = TextFileTools.charset(htmlFile); } if (ignoreOriginal) { doc.head().empty(); } if (!setCharset(task, doc, charset)) { return "Canceled"; } doc.head().appendChild(new Element("style").text(css)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } // files should have been sorted public static boolean generateFrameset(List<File> files, File targetFile) { try { if (files == null || files.isEmpty()) { return false; } String namePrefix = FileNameTools.prefix(targetFile.getName()); File navFile = new File(targetFile.getParent() + File.separator + namePrefix + "_nav.html"); StringBuilder nav = new StringBuilder(); File first = null; for (File file : files) { String filepath = file.getAbsolutePath(); String name = file.getName(); if (filepath.equals(targetFile.getAbsolutePath()) || filepath.equals(navFile.getAbsolutePath())) { FileDeleteTools.delete(file); } else { if (first == null) { first = file; } if (file.getParent().equals(targetFile.getParent())) { nav.append("<a href=\"./").append(name).append("\" target=main>").append(name).append("</a><br>\n"); } else { nav.append("<a href=\"").append(file.toURI()).append("\" target=main>").append(filepath).append("</a><br>\n"); } } } if (first == null) { return false; } String body = nav.toString(); TextFileTools.writeFile(navFile, html(Languages.message("PathIndex"), body)); String frameset = " <FRAMESET border=2 cols=400,*>\n" + "<FRAME name=nav src=\"" + namePrefix + "_nav.html\" />\n"; if (first.getParent().equals(targetFile.getParent())) { frameset += "<FRAME name=main src=\"" + first.getName() + "\" />\n"; } else { frameset += "<FRAME name=main src=\"" + first.toURI() + "\" />\n"; } frameset += "</FRAMESET>"; File frameFile = new File(targetFile.getParent() + File.separator + namePrefix + ".html"); TextFileTools.writeFile(frameFile, html(null, frameset)); return frameFile.exists(); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } // files should have been sorted public static void makePathList(File path, List<File> files, Map<File, Link> completedLinks) { if (files == null || files.isEmpty()) { return; } try { String listPrefix = "0000_" + Languages.message("PathIndex") + "_list"; StringBuilder csv = new StringBuilder(); String s = Languages.message("Address") + "," + Languages.message("File") + "," + Languages.message("Title") + "," + Languages.message("Name") + "," + Languages.message("Index") + "," + Languages.message("Time") + "\n"; csv.append(s); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(Languages.message("File"), Languages.message("Address"), Languages.message("Title"), Languages.message("Name"), Languages.message("Index"), Languages.message("Time"))); StringTable table = new StringTable(names, Languages.message("DownloadHistory")); for (File file : files) { String name = file.getName(); if (name.startsWith(listPrefix)) { FileDeleteTools.delete(file); } else { Link link = completedLinks.get(file); if (link == null) { s = file.getAbsolutePath() + ",,,," + DateTools.datetimeToString(FileTools.createTime(file)); csv.append(s); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(file.getAbsolutePath(), "", "", "", "", DateTools.datetimeToString(FileTools.createTime(file)))); table.add(row); } else { s = link.getUrl() + "," + file.getAbsolutePath() + "," + (link.getTitle() != null ? link.getTitle() : "") + "," + (link.getName() != null ? link.getName() : "") + "," + (link.getIndex() > 0 ? link.getIndex() : "") + "," + (link.getDlTime() != null ? DateTools.datetimeToString(link.getDlTime()) : "") + "\n"; csv.append(s); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(file.getAbsolutePath(), link.getUrl().toString(), link.getTitle() != null ? link.getTitle() : "", link.getName() != null ? link.getName() : "", link.getIndex() > 0 ? link.getIndex() + "" : "", link.getDlTime() != null ? DateTools.datetimeToString(link.getDlTime()) : "")); table.add(row); } } } String filename = path.getAbsolutePath() + File.separator + listPrefix + ".csv"; TextFileTools.writeFile(new File(filename), csv.toString()); filename = path.getAbsolutePath() + File.separator + listPrefix + ".html"; TextFileTools.writeFile(new File(filename), table.html()); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static int replace(FxTask currentTask, org.w3c.dom.Document doc, String findString, boolean reg, boolean caseInsensitive, String color, String bgColor, String font) { if (doc == null) { return 0; } NodeList nodeList = doc.getElementsByTagName("body"); if (nodeList == null || nodeList.getLength() < 1) { return 0; } FindReplaceString finder = FindReplaceString.create().setOperation(FindReplaceString.Operation.FindNext) .setFindString(findString).setIsRegex(reg).setCaseInsensitive(caseInsensitive).setMultiline(true); String replaceSuffix = " style=\"color:" + color + "; background: " + bgColor + "; font-size:" + font + ";\">" + findString + "</span>"; return replace(currentTask, finder, nodeList.item(0), 0, replaceSuffix); } public static int replace(FxTask currentTask, FindReplaceString finder, Node node, int index, String replaceSuffix) { if (node == null || replaceSuffix == null || finder == null) { return index; } String texts = node.getTextContent(); int newIndex = index; if (texts != null && !texts.isBlank()) { StringBuilder s = new StringBuilder(); while (true) { if (currentTask != null && !currentTask.isWorking()) { return -1; } finder.setInputString(texts).setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return -1; } if (finder.getStringRange() == null) { break; } String replaceString = "<span id=\"MyBoxSearchLocation" + (++newIndex) + "\" " + replaceSuffix; if (finder.getLastStart() > 0) { s.append(texts.substring(0, finder.getLastStart())); } s.append(replaceString); texts = texts.substring(finder.getLastEnd()); } s.append(texts); node.setTextContent(s.toString()); } Node child = node.getFirstChild(); while (child != null) { if (currentTask != null && !currentTask.isWorking()) { return -1; } replace(currentTask, finder, child, newIndex, replaceSuffix); child = child.getNextSibling(); } return newIndex; } public static boolean relinkPage(FxTask task, File httpFile, Map<File, Link> completedLinks, Map<String, File> completedAddresses) { try { if (httpFile == null || !httpFile.exists() || completedAddresses == null) { return false; } Link baseLink = completedLinks.get(httpFile); if (baseLink == null) { return false; } String html = TextFileTools.readTexts(task, httpFile); List<Link> links = HtmlReadTools.links(baseLink.getUrl(), html); String replaced = ""; String unchecked = html; int pos; for (Link link : links) { if (task != null && !task.isWorking()) { return false; } try { String originalAddress = link.getAddressOriginal(); pos = unchecked.indexOf("\"" + originalAddress + "\""); if (pos < 0) { pos = unchecked.indexOf("'" + originalAddress + "'"); } if (pos < 0) { continue; } replaced += unchecked.substring(0, pos); unchecked = unchecked.substring(pos + originalAddress.length() + 2); File linkFile = completedAddresses.get(link.getAddress()); if (linkFile == null || !linkFile.exists()) { replaced += "\"" + originalAddress + "\""; continue; } if (linkFile.getParent().startsWith(httpFile.getParent())) { replaced += "\"" + linkFile.getName() + "\""; } else { replaced += "\"" + linkFile.getAbsolutePath() + "\""; } } catch (Exception e) { // MyBoxLog.debug(e); } } replaced += unchecked; File tmpFile = FileTmpTools.getTempFile(); TextFileTools.writeFile(tmpFile, replaced, TextFileTools.charset(httpFile)); return FileTools.override(tmpFile, httpFile); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void makePathFrameset(File path) { try { if (path == null || !path.isDirectory()) { return; } File[] pathFiles = path.listFiles(); if (pathFiles == null || pathFiles.length == 0) { return; } List<File> files = new ArrayList<>(); for (File file : pathFiles) { if (file.isFile()) { files.add(file); } } if (!files.isEmpty()) { Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f1, f2); } }); File frameFile = new File(path.getAbsolutePath() + File.separator + "0000_" + Languages.message("PathIndex") + ".html"); generateFrameset(files, frameFile); } for (File file : pathFiles) { if (file.isDirectory()) { makePathFrameset(file); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FloatMatrixTools.java
released/MyBox/src/main/java/mara/mybox/tools/FloatMatrixTools.java
package mara.mybox.tools; import java.util.Random; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-5-18 10:37:15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class FloatMatrixTools { // columnNumber is 0-based public static float[] columnValues(float[][] m, int columnNumber) { if (m == null || m.length == 0 || m[0].length <= columnNumber) { return null; } float[] column = new float[m.length]; for (int i = 0; i < m.length; ++i) { column[i] = m[i][columnNumber]; } return column; } public static float[][] columnVector(float x, float y, float z) { float[][] rv = new float[3][1]; rv[0][0] = x; rv[1][0] = y; rv[2][0] = z; return rv; } public static float[][] columnVector(float[] v) { float[][] rv = new float[v.length][1]; for (int i = 0; i < v.length; ++i) { rv[i][0] = v[i]; } return rv; } public static float[] matrix2Array(FxTask task, float[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; float[] a = new float[w * h]; for (int j = 0; j < h; ++j) { if (task != null && !task.isWorking()) { return null; } System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static float[][] array2Matrix(float[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } float[][] m = new float[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static float[][] clone(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static Number[][] clone(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static String print(float[][] matrix, int prefix, int scale) { try { if (matrix == null) { return ""; } String s = "", p = "", t = " "; for (int b = 0; b < prefix; b++) { p += " "; } int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { s += p; for (int j = 0; j < column; ++j) { float d = FloatTools.scale(matrix[i][j], scale); s += d + t; } s += "\n"; } return s; } catch (Exception e) { return null; } } public static boolean same(float[][] matrixA, float[][] matrixB, int scale) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return false; } int rows = matrixA.length; int columns = matrixA[0].length; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { if (scale < 0) { if (matrixA[i][j] != matrixB[i][j]) { return false; } } else { float a = FloatTools.scale(matrixA[i][j], scale); float b = FloatTools.scale(matrixB[i][j], scale); if (a != b) { return false; } } } } return true; } catch (Exception e) { return false; } } public static int[][] identityInt(int n) { try { if (n < 1) { return null; } int[][] result = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static float[][] identityDouble(int n) { try { if (n < 1) { return null; } float[][] result = new float[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static float[][] randomMatrix(int n) { return randomMatrix(n, n); } public static float[][] randomMatrix(int m, int n) { try { if (n < 1) { return null; } float[][] result = new float[m][n]; Random r = new Random(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { result[i][j] = r.nextFloat(); } } return result; } catch (Exception e) { return null; } } public static float[][] vertivalMerge(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA[0].length != matrixB[0].length) { return null; } int rowsA = matrixA.length, rowsB = matrixB.length; int columns = matrixA[0].length; float[][] result = new float[rowsA + rowsB][columns]; for (int i = 0; i < rowsA; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columns); } for (int i = 0; i < rowsB; ++i) { System.arraycopy(matrixB[i], 0, result[i + rowsA], 0, columns); } return result; } catch (Exception e) { return null; } } public static float[][] horizontalMerge(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length) { return null; } int rows = matrixA.length; int columnsA = matrixA[0].length, columnsB = matrixB[0].length; int columns = columnsA + columnsB; float[][] result = new float[rows][columns]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columnsA); System.arraycopy(matrixB[i], 0, result[i], columnsA, columnsB); } return result; } catch (Exception e) { return null; } } public static float[][] add(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } float[][] result = new float[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { float[] rowA = matrixA[i]; float[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] + rowB[j]; } } return result; } catch (Exception e) { return null; } } public static float[][] subtract(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } float[][] result = new float[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { float[] rowA = matrixA[i]; float[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] - rowB[j]; } } return result; } catch (Exception e) { return null; } } public static float[][] multiply(float[][] matrixA, float[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (columnA != rowB) { return null; } float[][] result = new float[rowA][columnB]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnB; ++j) { result[i][j] = 0; for (int k = 0; k < columnA; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[] multiply(float[][] matrix, float[] columnVector) { if (matrix == null || columnVector == null) { return null; } float[] outputs = new float[matrix.length]; for (int i = 0; i < matrix.length; ++i) { float[] row = matrix[i]; outputs[i] = 0f; for (int j = 0; j < Math.min(row.length, columnVector.length); ++j) { outputs[i] += row[j] * columnVector[j]; } } return outputs; } public static float[][] transpose(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[columnA][rowA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[j][i] = matrix[i][j]; } } return result; } catch (Exception e) { return null; } } public static Number[][] transpose(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[columnA][rowA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[j][i] = matrix[i][j]; } } return result; } catch (Exception e) { return null; } } public static float[][] normalize(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; float sum = 0; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { sum += matrix[i][j]; } } if (sum == 0) { return null; } for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / sum; } } return result; } catch (Exception e) { return null; } } public static float[][] integer(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = Math.round(matrix[i][j]); } } return result; } catch (Exception e) { return null; } } public static float[][] scale(float[][] matrix, int scale) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = FloatTools.scale(matrix[i][j], scale); } } return result; } catch (Exception e) { return null; } } public static float[][] multiply(float[][] matrix, float p) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] * p; } } return result; } catch (Exception e) { return null; } } public static float[][] divide(float[][] matrix, float p) { try { if (matrix == null || p == 0) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / p; } } return result; } catch (Exception e) { return null; } } public static float[][] power(float[][] matrix, int n) { try { if (matrix == null || n < 0) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float[][] tmp = clone(matrix); float[][] result = identityDouble(row); while (n > 0) { if (n % 2 > 0) { result = multiply(result, tmp); } tmp = multiply(tmp, tmp); n = n / 2; } return result; } catch (Exception e) { return null; } } public static float[][] inverseByAdjoint(float[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float det = determinantByComplementMinor(matrix); if (det == 0) { return null; } float[][] inverse = new float[row][column]; float[][] adjoint = adjoint(matrix); for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { inverse[i][j] = adjoint[i][j] / det; } } return inverse; } catch (Exception e) { return null; } } public static float[][] inverse(float[][] matrix) { return inverseByElimination(matrix); } public static float[][] inverseByElimination(float[][] matrix) { try { if (matrix == null) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { return null; } float[][] augmented = new float[rows][columns * 2]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrix[i], 0, augmented[i], 0, columns); augmented[i][i + columns] = 1; } augmented = reducedRowEchelonForm(augmented); float[][] inverse = new float[rows][columns]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { inverse[i][j] = augmented[i][j + columns]; } } return inverse; } catch (Exception e) { return null; } } // rowIndex, columnIndex are 0-based. public static float[][] complementMinor(float[][] matrix, int rowIndex, int columnIndex) { try { if (matrix == null || rowIndex < 0 || columnIndex < 0) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rowIndex >= rows || columnIndex >= columns) { return null; } float[][] minor = new float[rows - 1][columns - 1]; int minorRow = 0, minorColumn; for (int i = 0; i < rows; ++i) { if (i == rowIndex) { continue; } minorColumn = 0; for (int j = 0; j < columns; ++j) { if (j == columnIndex) { continue; } minor[minorRow][minorColumn++] = matrix[i][j]; } minorRow++; } return minor; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] adjoint(float[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float[][] adjoint = new float[row][column]; if (row == 1) { adjoint[0][0] = matrix[0][0]; return adjoint; } for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { adjoint[j][i] = (float) Math.pow(-1, i + j) * determinantByComplementMinor(complementMinor(matrix, i, j)); } } return adjoint; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float determinant(float[][] matrix) throws Exception { return determinantByElimination(matrix); } public static float determinantByComplementMinor(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int row = matrix.length, column = matrix[0].length; if (row != column) { throw new Exception("InvalidValue"); } if (row == 1) { return matrix[0][0]; } if (row == 2) { return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]; } float v = 0; for (int j = 0; j < column; ++j) { float[][] minor = complementMinor(matrix, 0, j); v += matrix[0][j] * Math.pow(-1, j) * determinantByComplementMinor(minor); } return v; } catch (Exception e) { // MyBoxLog.debug(e); throw e; } } public static float determinantByElimination(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { throw new Exception("InvalidValue"); } float[][] ref = rowEchelonForm(matrix); if (ref[rows - 1][columns - 1] == 0) { return 0; } float det = 1; for (int i = 0; i < rows; ++i) { det *= ref[i][i]; } return det; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static float[][] hadamardProduct(float[][] matrixA, float[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (rowA != rowB || columnA != columnB) { return null; } float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrixA[i][j] * matrixB[i][j]; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] kroneckerProduct(float[][] matrixA, float[][] matrixB) { try { int rowsA = matrixA.length, columnsA = matrixA[0].length; int rowsB = matrixB.length, columnsB = matrixB[0].length; float[][] result = new float[rowsA * rowsB][columnsA * columnsB]; for (int i = 0; i < rowsA; ++i) { for (int j = 0; j < columnsA; ++j) { for (int m = 0; m < rowsB; m++) { for (int n = 0; n < columnsB; n++) { result[i * rowsB + m][j * columnsB + n] = matrixA[i][j] * matrixB[m][n]; } } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] rowEchelonForm(float[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; float[][] result = clone(matrix); for (int i = 0; i < Math.min(rows, columns); ++i) { if (result[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (result[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { float temp = result[row][j]; result[row][j] = result[i][j]; result[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (result[i][i] == 0) { continue; } float ratio = result[k][i] / result[i][i]; for (int j = i; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] reducedRowEchelonForm(float[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; float[][] result = rowEchelonForm(matrix); for (int i = Math.min(rows - 1, columns - 1); i >= 0; --i) { float dd = result[i][i]; if (dd == 0) { continue; } for (int k = i - 1; k >= 0; k--) { float ratio = result[k][i] / dd; for (int j = k; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } for (int j = i; j < columns; ++j) { result[i][j] = result[i][j] / dd; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float rank(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; float[][] d = clone(matrix); int i = 0; for (i = 0; i < Math.min(rows, columns); ++i) { if (d[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (d[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { float temp = d[row][j]; d[row][j] = d[i][j]; d[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (d[i][i] == 0) { continue; } float ratio = d[k][i] / d[i][i]; for (int j = i; j < columns; ++j) { d[k][j] -= ratio * d[i][j]; } } } return i; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static float[][] swapRow(float matrix[][], int a, int b) { try { for (int j = 0; j < matrix[0].length; ++j) { float temp = matrix[a][j]; matrix[a][j] = matrix[b][j]; matrix[b][j] = temp; } } catch (Exception e) { } return matrix; } public static float[][] swapColumn(float matrix[][], int columnA, int columnB) { try { for (float[] matrix1 : matrix) { float temp = matrix1[columnA]; matrix1[columnA] = matrix1[columnB]; matrix1[columnB] = temp; } } catch (Exception e) { } return matrix; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/AESTools.java
released/MyBox/src/main/java/mara/mybox/tools/AESTools.java
package mara.mybox.tools; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import mara.mybox.dev.MyBoxLog; /** * Reference: https://www.cnblogs.com/zhupig3028/p/16259271.html * * @Author Mara * @CreateDate 2023-3-29 * @License Apache License Version 2.0 */ // Refer To public class AESTools { private final static String ENCODING = "utf-8"; private final static String ALGORITHM = "AES"; private final static String PATTERN = "AES/ECB/pkcs5padding"; public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String DefaultKey = "8SaT6V9w5xpUr7qs"; public static String encrypt(String plainText) { return encrypt(plainText, DefaultKey); } public static String decrypt(String plainText) { return decrypt(plainText, DefaultKey); } public static String generateAESKey() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 16; i++) { sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); } return sb.toString(); } public static String generate3DESKey() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 24; i++) { sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); } return sb.toString(); } public static Map<String, String> genKeyPair() { try { HashMap<String, String> stringStringHashMap = new HashMap<>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded()); String privateKeyString = Base64.getEncoder().encodeToString((privateKey.getEncoded())); stringStringHashMap.put("0", publicKeyString); stringStringHashMap.put("1", privateKeyString); return stringStringHashMap; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String encrypt(String plainText, String key) { try { if (plainText == null || key == null || key.length() != 16) { return null; } SecretKey secretKey = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM); Cipher cipher = Cipher.getInstance(PATTERN); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptData = cipher.doFinal(plainText.getBytes(ENCODING)); return Base64.getEncoder().encodeToString(encryptData); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String decrypt(String plainText, String key) { try { if (plainText == null || key == null) { return null; } SecretKey secretKey = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM); Cipher cipher = Cipher.getInstance(PATTERN); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] encryptData = cipher.doFinal(Base64.getDecoder().decode(plainText)); return new String(encryptData, ENCODING); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/HtmlReadTools.java
released/MyBox/src/main/java/mara/mybox/tools/HtmlReadTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import javafx.concurrent.Task; import javax.net.ssl.HttpsURLConnection; import mara.mybox.controller.BaseController; import mara.mybox.controller.HtmlTableController; import mara.mybox.data.Link; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.DownloadTask; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class HtmlReadTools { public final static String httpUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"; /* read html */ public static File download(FxTask task, String urlAddress) { return download(task, urlAddress, UserConfig.getInt("WebConnectTimeout", 10000), UserConfig.getInt("WebReadTimeout", 10000)); } public static File download(FxTask task, String urlAddress, int connectTimeout, int readTimeout) { try { if (urlAddress == null) { return null; } URL url = UrlTools.url(urlAddress); if (url == null) { return null; } File tmpFile = FileTmpTools.getTempFile(); String protocal = url.getProtocol(); if ("file".equalsIgnoreCase(protocal)) { FileCopyTools.copyFile(new File(url.getFile()), tmpFile); } else if ("https".equalsIgnoreCase(protocal)) { HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); if (connectTimeout > 0) { connection.setConnectTimeout(connectTimeout); } if (readTimeout > 0) { connection.setReadTimeout(readTimeout); } // connection.setRequestProperty("User-Agent", httpUserAgent); connection.connect(); if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) { try (final BufferedInputStream inStream = new BufferedInputStream(new GZIPInputStream(connection.getInputStream())); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } else { try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } } else if ("http".equalsIgnoreCase(protocal)) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // connection.setRequestProperty("User-Agent", httpUserAgent); connection.setConnectTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); connection.setReadTimeout(UserConfig.getInt("WebReadTimeout", 10000)); connection.setUseCaches(false); connection.connect(); if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) { try (final BufferedInputStream inStream = new BufferedInputStream(new GZIPInputStream(connection.getInputStream())); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } else { try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } } if (tmpFile == null || !tmpFile.exists()) { return null; } if (tmpFile.length() == 0) { FileDeleteTools.delete(tmpFile); return null; } return tmpFile; } catch (Exception e) { // MyBoxLog.console(e.toString() + " " + urlAddress); return null; } } public static String url2html(FxTask task, String urlAddress) { try { if (urlAddress == null) { return null; } URL url = UrlTools.url(urlAddress); if (url == null) { return null; } String protocal = url.getProtocol(); if ("file".equalsIgnoreCase(protocal)) { return TextFileTools.readTexts(task, new File(url.getFile())); } else if ("https".equalsIgnoreCase(protocal) || "http".equalsIgnoreCase(protocal)) { File file = download(task, url.toString()); if (file != null) { return TextFileTools.readTexts(task, file); } } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + urlAddress); } return null; } public static Document url2doc(FxTask task, String urlAddress) { try { String html = url2html(task, urlAddress); if (html != null) { return Jsoup.parse(html); } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + urlAddress); } return null; } public static Document file2doc(FxTask task, File file) { try { if (file == null || !file.exists()) { return null; } String html = TextFileTools.readTexts(task, file); if (html != null) { return Jsoup.parse(html); } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + file); } return null; } public static String baseURI(FxTask task, String urlAddress) { try { Document doc = url2doc(task, urlAddress); if (doc == null) { return null; } return doc.baseUri(); } catch (Exception e) { MyBoxLog.debug(e.toString() + " " + urlAddress); return null; } } public static File url2image(FxTask task, String address, String name) { try { if (address == null) { return null; } String suffix = null; if (name != null && !name.isBlank()) { suffix = FileNameTools.ext(name); } String addrSuffix = FileNameTools.ext(address); if (addrSuffix != null && !addrSuffix.isBlank()) { if (suffix == null || suffix.isBlank() || !addrSuffix.equalsIgnoreCase(suffix)) { suffix = addrSuffix; } } if (suffix == null || (suffix.length() != 3 && !"jpeg".equalsIgnoreCase(suffix) && !"tiff".equalsIgnoreCase(suffix))) { suffix = "jpg"; } File tmpFile = download(task, address); if (tmpFile == null) { return null; } File imageFile = new File(tmpFile.getAbsoluteFile() + "." + suffix); if (FileTools.override(tmpFile, imageFile)) { return imageFile; } else { return null; } } catch (Exception e) { MyBoxLog.debug(e, address); return null; } } public static void requestHead(BaseController controller, String link) { if (controller == null || link == null) { return; } Task infoTask = new DownloadTask() { @Override protected boolean initValues() { readHead = true; address = link; return super.initValues(); } @Override protected void whenSucceeded() { if (head == null) { controller.popError(message("InvalidData")); return; } String table = requestHeadTable(url, head); HtmlTableController.open(table); } @Override protected void whenFailed() { if (error != null) { controller.popError(error); } else { controller.popFailed(); } } }; controller.start(infoTask); } public static Map<String, String> requestHead(URL url) { try { if (!url.getProtocol().startsWith("http")) { return null; } HttpURLConnection connection = NetworkTools.httpConnection(url); Map<String, String> head = HtmlReadTools.requestHead(connection); connection.disconnect(); return head; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static Map<String, String> requestHead(HttpURLConnection connection) { try { if (connection == null) { return null; } Map<String, String> head = new HashMap(); connection.setRequestMethod("HEAD"); head.put("ResponseCode", connection.getResponseCode() + ""); head.put("ResponseMessage", connection.getResponseMessage()); head.put("RequestMethod", connection.getRequestMethod()); head.put("ContentEncoding", connection.getContentEncoding()); head.put("ContentType", connection.getContentType()); head.put("ContentLength", connection.getContentLength() + ""); head.put("Expiration", DateTools.datetimeToString(connection.getExpiration())); head.put("LastModified", DateTools.datetimeToString(connection.getLastModified())); for (String key : connection.getHeaderFields().keySet()) { head.put("HeaderField_" + key, connection.getHeaderFields().get(key).toString()); } for (String key : connection.getRequestProperties().keySet()) { head.put("RequestProperty_" + key, connection.getRequestProperties().get(key).toString()); } return head; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String requestHeadTable(URL url) { return requestHeadTable(url, HtmlReadTools.requestHead(url)); } public static String requestHeadTable(URL url, Map<String, String> head) { try { if (url == null || head == null) { return null; } StringBuilder s = new StringBuilder(); s.append("<h1 class=\"center\">").append(url.toString()).append("</h1>\n"); s.append("<hr>\n"); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Name"), message("Value"))); StringTable table = new StringTable(names); for (String name : head.keySet()) { if (name.startsWith("HeaderField_") || name.startsWith("RequestProperty_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name, head.get(name))); table.add(row); } s.append(StringTable.tableDiv(table)); s.append("<h2 class=\"center\">").append("Header Fields").append("</h2>\n"); int hlen = "HeaderField_".length(); for (Object key : head.keySet()) { String name = (String) key; if (!name.startsWith("HeaderField_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name.substring(hlen), (String) head.get(key))); table.add(row); } s.append(StringTable.tableDiv(table)); s.append("<h2 class=\"center\">").append("Request Property").append("</h2>\n"); int rlen = "RequestProperty_".length(); for (String name : head.keySet()) { if (!name.startsWith("RequestProperty_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name.substring(rlen), head.get(name))); table.add(row); } s.append(StringTable.tableDiv(table)); return s.toString(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* parse html */ public static String title(String html) { Document doc = Jsoup.parse(html); if (doc == null) { return null; } return doc.title(); } public static String head(String html) { Document doc = Jsoup.parse(html); if (doc == null || doc.head() == null) { return null; } return doc.head().outerHtml(); } public static Charset charset(String html) { try { Document doc = Jsoup.parse(html); Charset charset = null; if (doc != null) { charset = doc.charset(); } return charset == null ? Charset.forName("UTF-8") : charset; } catch (Exception e) { return null; } } // public static String body(String html) { // return body(html, false); // } public static String body(String html, boolean withTag) { try { Element body = Jsoup.parse(html).body(); return withTag ? body.outerHtml() : body.html(); } catch (Exception e) { return null; } } public static String toc(String html, int indentSize) { try { if (html == null) { return null; } Document doc = Jsoup.parse(html); if (doc == null) { return null; } org.jsoup.nodes.Element body = doc.body(); if (body == null) { return null; } String indent = ""; for (int i = 0; i < indentSize; i++) { indent += " "; } StringBuilder s = new StringBuilder(); toc(body, indent, s); return s.toString(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void toc(Element element, String indent, StringBuilder s) { try { if (element == null || s == null || indent == null) { return; } String tag = element.tagName(); String content = element.text(); if (tag != null && content != null && !content.isBlank()) { content += "\n"; if (tag.equalsIgnoreCase("h1")) { s.append(content); } else if (tag.equalsIgnoreCase("h2")) { s.append(indent).append(content); } else if (tag.equalsIgnoreCase("h3")) { s.append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h4")) { s.append(indent).append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h5")) { s.append(indent).append(indent).append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h6")) { s.append(indent).append(indent).append(indent).append(indent).append(indent).append(content); } } Elements children = element.children(); if (children == null || children.isEmpty()) { return; } for (org.jsoup.nodes.Element child : children) { toc(child, indent, s); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static List<Link> links(URL baseURL, String html) { if (html == null) { return null; } Document doc = Jsoup.parse(html); Elements elements = doc.getElementsByTag("a"); List<Link> links = new ArrayList<>(); for (org.jsoup.nodes.Element element : elements) { String linkAddress = element.attr("href"); try { URL url = UrlTools.fullUrl(baseURL, linkAddress); Link link = Link.create().setUrl(url).setAddress(url.toString()).setAddressOriginal(linkAddress) .setName(element.text()).setTitle(element.attr("title")).setIndex(links.size()); links.add(link); } catch (Exception e) { // MyBoxLog.console(linkAddress); } } return links; } public static List<Link> links(FxTask task, Link addressLink, File path, Link.FilenameType nameType) { try { if (addressLink == null || path == null) { return null; } List<Link> validLinks = new ArrayList<>(); URL url = addressLink.getUrl(); Link coverLink = Link.create().setUrl(url).setAddress(url.toString()).setName("0000_" + path.getName()).setTitle(path.getName()); coverLink.setIndex(0).setFile(new File(coverLink.filename(path, nameType)).getAbsolutePath()); validLinks.add(coverLink); String html = addressLink.getHtml(); if (html == null) { html = TextFileTools.readTexts(task, new File(addressLink.getFile())); } List<Link> links = HtmlReadTools.links(url, html); for (Link link : links) { if (task != null && !task.isWorking()) { return null; } if (link.getAddress() == null) { continue; } String filename = link.filename(path, nameType); if (filename == null) { continue; } link.setFile(new File(filename).getAbsolutePath()); link.setIndex(validLinks.size()); validLinks.add(link); } return validLinks; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static List<StringTable> Tables(String html, String name) { try { if (html == null || html.isBlank()) { return null; } List<StringTable> tables = new ArrayList<>(); Document doc = Jsoup.parse(html); Elements tablesList = doc.getElementsByTag("table"); String titlePrefix = name != null ? name + "_t_" : "t_"; int count = 0; if (tablesList != null) { for (org.jsoup.nodes.Element table : tablesList) { StringTable stringTable = new StringTable(); stringTable.setTitle(titlePrefix + (++count)); List<List<String>> data = new ArrayList<>(); List<String> names = null; Elements trList = table.getElementsByTag("tr"); if (trList != null) { for (org.jsoup.nodes.Element tr : trList) { if (names == null) { Elements thList = tr.getElementsByTag("th"); if (thList != null) { names = new ArrayList<>(); for (org.jsoup.nodes.Element th : thList) { names.add(th.text()); } if (!names.isEmpty()) { stringTable.setNames(names); } } } Elements tdList = tr.getElementsByTag("td"); if (tdList != null) { List<String> row = new ArrayList<>(); for (org.jsoup.nodes.Element td : tdList) { row.add(td.text()); } if (!row.isEmpty()) { data.add(row); } } } } stringTable.setData(data); tables.add(stringTable); } } return tables; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static String removeNode(String html, String id) { try { if (html == null || id == null || id.isBlank()) { return html; } Document doc = Jsoup.parse(html); org.jsoup.nodes.Element element = doc.getElementById(id); if (element != null) { element.remove(); return doc.outerHtml(); } else { return html; } } catch (Exception e) { MyBoxLog.debug(e); return html; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileDeleteTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileDeleteTools.java
package mara.mybox.tools; import java.awt.Desktop; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileDeleteTools { public static boolean delete(String fileName) { return delete(null, fileName); } public static boolean delete(FxTask currentTask, String fileName) { if (fileName == null || fileName.isBlank()) { return false; } return delete(currentTask, new File(fileName)); } public static boolean delete(File file) { return delete(null, file); } public static boolean delete(FxTask currentTask, File file) { try { if (file == null || !file.exists()) { return true; } System.gc(); if (file.isDirectory()) { return deleteDir(currentTask, file); } else { return file.delete(); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean deleteDir(File file) { return delete(null, file); } public static boolean deleteDir(FxTask currentTask, File file) { if (file == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (file.exists() && file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking()) || !deleteDir(currentTask, child)) { return false; } } } } return file.delete(); // FileUtils.deleteQuietly(dir); // return true; } public static boolean clearDir(FxTask currentTask, File file) { if (file == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (file.exists() && file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return false; } if (child.isDirectory()) { if (clearDir(currentTask, child)) { child.delete(); } else { return false; } } else { child.delete(); } } } } return true; // try { // FileUtils.cleanDirectory(dir); // return true; // } catch (Exception e) { // MyBoxLog.error(e); // return false; // } } public static boolean deleteDirExcept(FxTask currentTask, File dir, File except) { if (dir.isDirectory()) { File[] children = dir.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return false; } if (child.equals(except)) { continue; } if (!deleteDirExcept(currentTask, child, except)) { return false; } } } } return delete(currentTask, dir); } public static void deleteNestedDir(FxTask currentTask, File sourceDir) { try { if ((currentTask != null && !currentTask.isWorking()) || sourceDir == null || !sourceDir.exists() || !sourceDir.isDirectory()) { return; } System.gc(); File targetTmpDir = FileTmpTools.getTempDirectory(); deleteNestedDir(currentTask, sourceDir, targetTmpDir); deleteDir(currentTask, targetTmpDir); deleteDir(currentTask, sourceDir); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void deleteNestedDir(FxTask currentTask, File sourceDir, File tmpDir) { try { if ((currentTask != null && !currentTask.isWorking()) || sourceDir == null || !sourceDir.exists()) { return; } if (sourceDir.isDirectory()) { File[] files = sourceDir.listFiles(); if (files == null || files.length == 0) { return; } for (File file : files) { if ((currentTask != null && !currentTask.isWorking())) { return; } if (file.isDirectory()) { File[] subfiles = file.listFiles(); if (subfiles != null) { for (File subfile : subfiles) { if ((currentTask != null && !currentTask.isWorking())) { return; } if (subfile.isDirectory()) { String target = tmpDir.getAbsolutePath() + File.separator + subfile.getName(); new File(target).getParentFile().mkdirs(); Files.move(Paths.get(subfile.getAbsolutePath()), Paths.get(target)); } else { delete(currentTask, subfile); } } } file.delete(); } else { delete(currentTask, file); } } if ((currentTask != null && !currentTask.isWorking())) { return; } deleteNestedDir(currentTask, tmpDir, sourceDir); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static int deleteEmptyDir(FxTask currentTask, File dir, boolean trash) { return deleteEmptyDir(currentTask, dir, 0, trash); } public static int deleteEmptyDir(FxTask currentTask, File dir, int count, boolean trash) { if ((currentTask != null && !currentTask.isWorking())) { return count; } if (dir != null && dir.exists() && dir.isDirectory()) { File[] children = dir.listFiles(); if (children == null || children.length == 0) { boolean ok; if (trash) { ok = Desktop.getDesktop().moveToTrash(dir); } else { ok = deleteDir(currentTask, dir); } if (ok) { return ++count; } else { return count; } } for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return count; } if (child.isDirectory()) { count = deleteEmptyDir(currentTask, child, count, trash); } } children = dir.listFiles(); if (children == null || children.length == 0) { boolean ok; if (trash) { ok = Desktop.getDesktop().moveToTrash(dir); } else { ok = deleteDir(currentTask, dir); } if (ok) { return ++count; } else { return count; } } } return count; } public static void clearJavaIOTmpPath(FxTask currentTask) { try { System.gc(); clearDir(currentTask, FileTools.javaIOTmpPath()); } catch (Exception e) { // MyBoxLog.debug(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/XmlTools.java
released/MyBox/src/main/java/mara/mybox/tools/XmlTools.java
package mara.mybox.tools; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.StringReader; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import mara.mybox.controller.BaseController; import mara.mybox.data.XmlTreeNode; import static mara.mybox.data.XmlTreeNode.NodeType.CDATA; import static mara.mybox.data.XmlTreeNode.NodeType.Comment; import static mara.mybox.data.XmlTreeNode.NodeType.ProcessingInstruction; import static mara.mybox.data.XmlTreeNode.NodeType.Text; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Entity; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Notation; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; /** * @Author Mara * @CreateDate 2023-2-12 * @License Apache License Version 2.0 */ public class XmlTools { public static Transformer transformer; public static DocumentBuilder builder; public static boolean ignoreBlankInstrution; public static boolean ignoreBlankComment; public static boolean ignoreBlankText; public static boolean ignoreComment; public static boolean ignoreBlankCDATA; /* encode */ public static String xmlTag(String tag) { return message(tag).replaceAll(" ", "_"); } public static boolean matchXmlTag(String matchTo, String s) { try { if (matchTo == null || s == null) { return false; } return message("en", matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || message("zh", matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || message(matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || matchTo.replaceAll(" ", "_").equalsIgnoreCase(s); } catch (Exception e) { return false; } } public static String cdata(Node node) { if (node == null) { return null; } try { NodeList fNodes = node.getChildNodes(); if (fNodes != null) { for (int f = 0; f < fNodes.getLength(); f++) { Node c = fNodes.item(f); if (c.getNodeType() == Node.CDATA_SECTION_NODE) { return c.getNodeValue(); } } } } catch (Exception ex) { } return node.getTextContent(); } /* parse */ public static Document textToDoc(FxTask task, BaseController controller, String xml) { try { return readSource(task, controller, new InputSource(new StringReader(xml))); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Document fileToDoc(FxTask task, BaseController controller, File file) { try { return readSource(task, controller, new InputSource(new FileReader(file))); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Document readSource(FxTask task, BaseController controller, InputSource inputSource) { try { Document doc = builder(controller).parse(inputSource); if (doc == null) { return null; } Strip(task, controller, doc); return doc; } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Element toElement(FxTask task, BaseController controller, String xml) { try { Document doc = textToDoc(task, controller, xml); if (doc == null || (task != null && !task.isWorking())) { return null; } return doc.getDocumentElement(); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static DocumentBuilder builder(BaseController controller) { try (Connection conn = DerbyBase.getConnection()) { ignoreComment = UserConfig.getBoolean(conn, "XmlIgnoreComments", false); ignoreBlankComment = UserConfig.getBoolean(conn, "XmlIgnoreBlankComment", false); ignoreBlankText = UserConfig.getBoolean(conn, "XmlIgnoreBlankText", false); ignoreBlankCDATA = UserConfig.getBoolean(conn, "XmlIgnoreBlankCDATA", false); ignoreBlankInstrution = UserConfig.getBoolean(conn, "XmlIgnoreBlankInstruction", false); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(UserConfig.getBoolean(conn, "XmlDTDValidation", false)); factory.setNamespaceAware(UserConfig.getBoolean(conn, "XmlSupportNamespaces", false)); factory.setCoalescing(false); factory.setIgnoringElementContentWhitespace(false); factory.setIgnoringComments(ignoreComment); builder = factory.newDocumentBuilder(); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } builder.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) { // PopTools.showError(controller, e.toString()); } @Override public void fatalError(SAXParseException e) { // PopTools.showError(controller, e.toString()); } @Override public void warning(SAXParseException e) { // PopTools.showError(controller, e.toString()); } }); return builder; } public static Node Strip(FxTask task, BaseController controller, Node node) { try { if (node == null || (task != null && !task.isWorking())) { return node; } NodeList nodeList = node.getChildNodes(); if (nodeList == null) { return node; } List<Node> children = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { if (task != null && !task.isWorking()) { return node; } children.add(nodeList.item(i)); } for (Node child : children) { if (task != null && !task.isWorking()) { return node; } XmlTreeNode.NodeType t = type(child); if (ignoreComment && t == XmlTreeNode.NodeType.Comment) { node.removeChild(child); continue; } String value = child.getNodeValue(); if (value == null || value.isBlank()) { switch (t) { case Comment: if (ignoreBlankComment) { node.removeChild(child); } continue; case Text: if (ignoreBlankText) { node.removeChild(child); } continue; case CDATA: if (ignoreBlankCDATA) { node.removeChild(child); } continue; case ProcessingInstruction: if (ignoreBlankInstrution) { node.removeChild(child); continue; } break; } } Strip(task, controller, child); } } catch (Exception e) { PopTools.showError(controller, e.toString()); } return node; } public static String name(Node node) { return node == null ? null : node.getNodeName(); } public static String value(Node node) { if (node == null) { return null; } switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_FRAGMENT_NODE: return node.getNodeValue(); case Node.ELEMENT_NODE: return elementInfo((Element) node); case Node.DOCUMENT_NODE: return docInfo((Document) node); case Node.DOCUMENT_TYPE_NODE: return docTypeInfo((DocumentType) node); case Node.ENTITY_NODE: return entityInfo((Entity) node, ""); case Node.ENTITY_REFERENCE_NODE: return entityReferenceInfo((EntityReference) node); case Node.NOTATION_NODE: return notationInfo((Notation) node, ""); default: return null; } } public static String docInfo(Document document) { if (document == null) { return null; } String info = ""; String v = document.getXmlVersion(); if (v != null && !v.isBlank()) { info += "version=\"" + v + "\"\n"; } v = document.getXmlEncoding(); if (v != null && !v.isBlank()) { info += "encoding=\"" + v + "\"\n"; } v = document.getDocumentURI(); if (v != null && !v.isBlank()) { info += "uri=\"" + v + "\"\n"; } return info; } public static XmlTreeNode.NodeType type(Node node) { if (node == null) { return null; } switch (node.getNodeType()) { case Node.ELEMENT_NODE: return XmlTreeNode.NodeType.Element; case Node.ATTRIBUTE_NODE: return XmlTreeNode.NodeType.Attribute; case Node.TEXT_NODE: return XmlTreeNode.NodeType.Text; case Node.CDATA_SECTION_NODE: return XmlTreeNode.NodeType.CDATA; case Node.ENTITY_REFERENCE_NODE: return XmlTreeNode.NodeType.EntityRefrence; case Node.ENTITY_NODE: return XmlTreeNode.NodeType.Entity; case Node.PROCESSING_INSTRUCTION_NODE: return XmlTreeNode.NodeType.ProcessingInstruction; case Node.COMMENT_NODE: return XmlTreeNode.NodeType.Comment; case Node.DOCUMENT_NODE: return XmlTreeNode.NodeType.Document; case Node.DOCUMENT_TYPE_NODE: return XmlTreeNode.NodeType.DocumentType; case Node.DOCUMENT_FRAGMENT_NODE: return XmlTreeNode.NodeType.DocumentFragment; case Node.NOTATION_NODE: return XmlTreeNode.NodeType.Notation; default: return XmlTreeNode.NodeType.Unknown; } } public static String entityReferenceInfo(EntityReference ref) { if (ref == null) { return null; } String info = "\t" + ref.getNodeName() + "=\"" + ref.getNodeValue() + "\""; return info; } public static String docTypeInfo(DocumentType documentType) { if (documentType == null) { return null; } String info = ""; String v = documentType.getName(); if (v != null && !v.isBlank()) { info += "name=\"" + v + "\"\n"; } v = documentType.getPublicId(); if (v != null && !v.isBlank()) { info += "Public Id=\"" + v + "\"\n"; } v = documentType.getSystemId(); if (v != null && !v.isBlank()) { info += "System Id=\"" + v + "\"\n"; } v = documentType.getInternalSubset(); if (v != null && !v.isBlank()) { info += "Internal subset=\"" + v + "\"\n"; } NamedNodeMap entities = documentType.getEntities(); if (entities != null && entities.getLength() > 0) { info += "Entities: \n"; for (int i = 0; i < entities.getLength(); i++) { info += entityInfo((Entity) entities.item(i), "\t"); } } NamedNodeMap notations = documentType.getNotations(); if (notations != null && notations.getLength() > 0) { info += "Notations: \n"; for (int i = 0; i < notations.getLength(); i++) { info += notationInfo((Notation) notations.item(i), "\t"); } } return info; } public static String notationInfo(Notation notation, String indent) { if (notation == null) { return null; } String info = indent + notation.getNodeName() + "=" + notation.getNodeValue() + "\n"; String v = notation.getPublicId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Public Id=" + v + "\n"; } v = notation.getSystemId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "System Id=" + v + "\n"; } return info; } public static String elementInfo(Element element) { if (element == null) { return null; } String info = ""; NamedNodeMap attributes = element.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); info += attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"\n"; } } return info; } public static String entityInfo(Entity entity, String indent) { if (entity == null) { return null; } String info = indent + entity.getNodeName() + "=" + entity.getNodeValue(); String v = entity.getNotationName(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Notation name=\"" + v + "\"\n"; } v = entity.getXmlVersion(); if (v != null && !v.isBlank()) { info += indent + "\t" + "version=\"" + v + "\"\n"; } v = entity.getXmlEncoding(); if (v != null && !v.isBlank()) { info += indent + "\t" + "encoding=\"" + v + "\"\n"; } v = entity.getPublicId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Public Id=\"" + v + "\"\n"; } v = entity.getSystemId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "System Id=\"" + v + "\"\n"; } return info; } public static Element findName(Document doc, String name, int index) { try { if (doc == null || name == null || name.isBlank() || index < 0) { return null; } NodeList svglist = doc.getElementsByTagName(name); if (svglist == null || svglist.getLength() <= index) { return null; } return (Element) svglist.item(index); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* tree */ public static int index(Node node) { if (node == null) { return -1; } Node parent = node.getParentNode(); if (parent == null) { return -2; } NodeList nodeList = parent.getChildNodes(); if (nodeList == null) { return -3; } for (int i = 0; i < nodeList.getLength(); i++) { if (node.equals(nodeList.item(i))) { return i; } } return -4; } public static String hierarchyNumber(Node node) { if (node == null) { return ""; } String h = ""; Node parent = node.getParentNode(); Node cnode = node; while (parent != null) { int index = index(cnode); if (index < 0) { return ""; } h = "." + (index + 1) + h; cnode = parent; parent = parent.getParentNode(); } if (h.startsWith(".")) { h = h.substring(1, h.length()); } return h; } public static Node find(Node doc, String hierarchyNumber) { try { if (doc == null || hierarchyNumber == null || hierarchyNumber.isBlank()) { return null; } String[] numbers = hierarchyNumber.split("\\.", -1); if (numbers == null || numbers.length == 0) { return null; } int index; Node current = doc; for (String n : numbers) { index = Integer.parseInt(n); NodeList nodeList = current.getChildNodes(); if (nodeList == null || index < 1 || index > nodeList.getLength()) { return null; } current = nodeList.item(index - 1); } return current; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static void remove(Node doc, Node targetNode) { try { if (doc == null || targetNode == null) { return; } Node child = find(doc, hierarchyNumber(targetNode)); if (child == null) { return; } Node parent = child.getParentNode(); if (parent == null) { return; } parent.removeChild(child); } catch (Exception e) { MyBoxLog.error(e); } } public static void remove(Node targetNode) { try { if (targetNode == null) { return; } Node parent = targetNode.getParentNode(); if (parent == null) { return; } parent.removeChild(targetNode); } catch (Exception e) { MyBoxLog.error(e); } } /* transform */ public static String transform(Node node) { if (node == null) { return null; } return transform(node, UserConfig.getBoolean("XmlTransformerIndent", true)); } public static String transform(Node node, boolean indent) { if (node == null) { return null; } String encoding = node instanceof Document ? ((Document) node).getXmlEncoding() : node.getOwnerDocument().getXmlEncoding(); return transform(node, encoding, indent); } public static String transform(Node node, String encoding, boolean indent) { if (node == null) { return null; } if (encoding == null) { encoding = "utf-8"; } try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { if (XmlTools.transformer == null) { XmlTools.transformer = TransformerFactory.newInstance().newTransformer(); } XmlTools.transformer.setOutputProperty(OutputKeys.METHOD, "xml"); XmlTools.transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); XmlTools.transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, node instanceof Document ? "no" : "yes"); XmlTools.transformer.setOutputProperty(OutputKeys.ENCODING, encoding); XmlTools.transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); StreamResult streamResult = new StreamResult(); streamResult.setOutputStream(os); XmlTools.transformer.transform(new DOMSource(node), streamResult); os.flush(); os.close(); String s = os.toString(encoding); if (indent) { s = s.replaceAll("><", ">\n<"); } return s; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/PdfTools.java
released/MyBox/src/main/java/mara/mybox/tools/PdfTools.java
package mara.mybox.tools; import com.vladsch.flexmark.ext.toc.TocExtension; import com.vladsch.flexmark.pdf.converter.PdfConverterExtension; import com.vladsch.flexmark.profile.pegdown.Extensions; import com.vladsch.flexmark.profile.pegdown.PegdownOptionsAdapter; import com.vladsch.flexmark.util.data.DataHolder; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageBinary; import mara.mybox.controller.ControlPdfWriteOptions; import mara.mybox.data.WeiboSnapParameters; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDPageTree; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.font.Standard14Fonts; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; import org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory; import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageXYZDestination; /** * @Author Mara * @CreateDate 2018-6-17 9:13:00 * @License Apache License Version 2.0 */ public class PdfTools { public static int PDF_dpi = 72; // pixels per inch public static int DefaultMargin = 20; public static enum PdfImageFormat { Original, Tiff, Jpeg } public static float pixels2mm(float pixels) { return FloatTools.roundFloat2(pixels * 25.4f / 72f); } public static float pixels2inch(float pixels) { return FloatTools.roundFloat2(pixels / 72f); } public static int mm2pixels(float mm) { return Math.round(mm * 72f / 25.4f); } public static int inch2pixels(float inch) { return Math.round(inch * 72f); } public static boolean isPDF(String filename) { String suffix = FileNameTools.ext(filename); if (suffix == null) { return false; } return "PDF".equals(suffix.toUpperCase()); } public static PDDocument createPDF(File file) { return createPDF(file, UserConfig.getString("AuthorKey", System.getProperty("user.name"))); } public static PDDocument createPDF(File file, String author) { PDDocument targetDoc = null; try { PDDocument document = new PDDocument(); setAttributes(document, author, -1); document.save(file); targetDoc = document; } catch (Exception e) { MyBoxLog.error(e.toString()); } return targetDoc; } public static boolean createPdfFile(File file, String author) { try { PDDocument targetDoc = createPDF(file, author); if (targetDoc != null) { targetDoc.close(); } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static PDImageXObject imageObject(FxTask task, PDDocument document, String format, BufferedImage bufferedImage) { try { PDImageXObject imageObject; bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, format); if (bufferedImage == null || (task != null && !task.isWorking())) { return null; } switch (format) { case "tif": case "tiff": imageObject = CCITTFactory.createFromImage(document, bufferedImage); break; case "jpg": case "jpeg": imageObject = JPEGFactory.createFromImage(document, bufferedImage, 1f); break; default: imageObject = LosslessFactory.createFromImage(document, bufferedImage); break; } return imageObject; } catch (Exception e) { return null; } } public static boolean writePage(FxTask task, PDDocument document, String sourceFormat, BufferedImage bufferedImage, int pageNumber, int total, ControlPdfWriteOptions options) { try { PDFont font = PdfTools.getFont(document, options.getTtfFile()); return writePage(task, document, font, options.getFontSize(), sourceFormat, bufferedImage, pageNumber, total, options.getImageFormat(), options.getThreshold(), options.getJpegQuality(), options.isIsImageSize(), options.isShowPageNumber(), options.getPageWidth(), options.getPageHeight(), options.getMarginSize(), options.getHeader(), options.getFooter(), options.isDithering()); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean writePage(FxTask task, PDDocument document, PDFont font, int fontSize, String sourceFormat, BufferedImage bufferedImage, int pageNumber, int total, PdfImageFormat targetFormat, int threshold, int jpegQuality, boolean isImageSize, boolean showPageNumber, int pageWidth, int pageHeight, int marginSize, String header, String footer, boolean dithering) { try { PDImageXObject imageObject; switch (targetFormat) { case Tiff: ImageBinary imageBinary = new ImageBinary(); imageBinary.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold) .setImage(bufferedImage) .setIntPara1(threshold) .setIsDithering(dithering) .setTask(task); bufferedImage = imageBinary.start(); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } bufferedImage = ImageBinary.byteBinary(task, bufferedImage); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = CCITTFactory.createFromImage(document, bufferedImage); break; case Jpeg: bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, "jpg"); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = JPEGFactory.createFromImage(document, bufferedImage, jpegQuality / 100f); break; default: if (sourceFormat != null) { bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, sourceFormat); } if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = LosslessFactory.createFromImage(document, bufferedImage); break; } PDRectangle pageSize; if (isImageSize) { pageSize = new PDRectangle(imageObject.getWidth() + marginSize * 2, imageObject.getHeight() + marginSize * 2); } else { pageSize = new PDRectangle(pageWidth, pageHeight); } PDPage page = new PDPage(pageSize); document.addPage(page); try (PDPageContentStream content = new PDPageContentStream(document, page)) { float w, h; if (isImageSize) { w = imageObject.getWidth(); h = imageObject.getHeight(); } else { if (imageObject.getWidth() > imageObject.getHeight()) { w = page.getTrimBox().getWidth() - marginSize * 2; h = imageObject.getHeight() * w / imageObject.getWidth(); } else { h = page.getTrimBox().getHeight() - marginSize * 2; w = imageObject.getWidth() * h / imageObject.getHeight(); } } content.drawImage(imageObject, marginSize, page.getTrimBox().getHeight() - marginSize - h, w, h); if (showPageNumber) { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(w + marginSize - 80, 5); content.showText(pageNumber + " / " + total); content.endText(); } if (header != null && !header.trim().isEmpty()) { try { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(marginSize, page.getTrimBox().getHeight() - marginSize + 2); content.showText(header.trim()); content.endText(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } if (footer != null && !footer.trim().isEmpty()) { try { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(marginSize, marginSize + 2); content.showText(footer.trim()); content.endText(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } PDExtendedGraphicsState gs = new PDExtendedGraphicsState(); gs.setNonStrokingAlphaConstant(0.2f); gs.setAlphaSourceFlag(true); gs.setBlendMode(BlendMode.NORMAL); } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static List<BlendMode> pdfBlendModes() { try { List<BlendMode> modes = new ArrayList<>(); modes.add(BlendMode.NORMAL); // modes.add(BlendMode.COMPATIBLE); modes.add(BlendMode.MULTIPLY); modes.add(BlendMode.SCREEN); modes.add(BlendMode.OVERLAY); modes.add(BlendMode.DARKEN); modes.add(BlendMode.LIGHTEN); modes.add(BlendMode.COLOR_DODGE); modes.add(BlendMode.COLOR_BURN); modes.add(BlendMode.HARD_LIGHT); modes.add(BlendMode.SOFT_LIGHT); modes.add(BlendMode.DIFFERENCE); modes.add(BlendMode.EXCLUSION); modes.add(BlendMode.HUE); modes.add(BlendMode.SATURATION); modes.add(BlendMode.LUMINOSITY); modes.add(BlendMode.COLOR); return modes; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } // BlendMode m = BlendMode.getInstance(COSName.A); // Field xbar = m.getClass().getDeclaredField("BLEND_MODE_NAMES"); // xbar.setAccessible(true); // Map<BlendMode, COSName> maps = (Map<BlendMode, COSName>) xbar.get(reader); // return maps.keySet(); } public static boolean imageInPdf(FxTask task, PDDocument document, BufferedImage bufferedImage, WeiboSnapParameters p, int showPageNumber, int totalPage, PDFont font) { return writePage(task, document, font, p.getFontSize(), "png", bufferedImage, showPageNumber, totalPage, p.getFormat(), p.getThreshold(), p.getJpegQuality(), p.isIsImageSize(), p.isAddPageNumber(), p.getPageWidth(), p.getPageHeight(), p.getMarginSize(), p.getTitle(), null, p.isDithering()); } public static boolean images2Pdf(FxTask task, List<Image> images, File targetFile, WeiboSnapParameters p) { try { if (images == null || images.isEmpty()) { return false; } int count = 0, total = images.size(); try (PDDocument document = new PDDocument()) { PDFont font = getFont(document, p.getFontFile()); BufferedImage bufferedImage; for (Image image : images) { if (task != null && !task.isWorking()) { return false; } if (null == p.getFormat()) { bufferedImage = SwingFXUtils.fromFXImage(image, null); } else { switch (p.getFormat()) { case Tiff: bufferedImage = SwingFXUtils.fromFXImage(image, null); break; case Jpeg: bufferedImage = FxImageTools.checkAlpha(task, image, "jpg"); break; default: bufferedImage = SwingFXUtils.fromFXImage(image, null); break; } } imageInPdf(task, document, bufferedImage, p, ++count, total, font); } setAttributes(document, p.getAuthor(), p.getPdfScale()); document.save(targetFile); document.close(); return true; } } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean imagesFiles2Pdf(FxTask task, List<String> files, File targetFile, WeiboSnapParameters p, boolean deleteFiles) { try { if (files == null || files.isEmpty()) { return false; } int count = 0, total = files.size(); try (PDDocument document = new PDDocument()) { PDFont font = getFont(document, p.getFontFile()); BufferedImage bufferedImage; File file; for (String filename : files) { if (task != null && !task.isWorking()) { return false; } file = new File(filename); bufferedImage = ImageFileReaders.readImage(task, file); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageInPdf(task, document, bufferedImage, p, ++count, total, font); if (task != null && !task.isWorking()) { return false; } if (deleteFiles) { FileDeleteTools.delete(file); } } setAttributes(document, p.getAuthor(), p.getPdfScale()); document.save(targetFile); document.close(); return true; } } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void setPageSize(PDPage page, PDRectangle pageSize) { page.setTrimBox(pageSize); page.setCropBox(pageSize); page.setArtBox(pageSize); page.setBleedBox(new PDRectangle(pageSize.getWidth() + mm2pixels(5), pageSize.getHeight() + mm2pixels(5))); page.setMediaBox(page.getBleedBox()); // pageSize.setLowerLeftX(20); // pageSize.setLowerLeftY(20); // pageSize.setUpperRightX(page.getTrimBox().getWidth() - 20); // pageSize.setUpperRightY(page.getTrimBox().getHeight() - 20); } public static PDFont HELVETICA() { return new PDType1Font(Standard14Fonts.getMappedFontName(Standard14Fonts.FontName.HELVETICA.getName())); } public static PDFont getFont(PDDocument document, String fontFile) { PDFont font = HELVETICA(); try { if (fontFile != null) { font = PDType0Font.load(document, new File(TTFTools.ttf(fontFile))); } } catch (Exception e) { } return font; } public static PDFont defaultFont(PDDocument document) { PDFont font = HELVETICA(); try { List<String> ttfList = TTFTools.ttfList(); if (ttfList != null && !ttfList.isEmpty()) { font = getFont(document, ttfList.get(0)); } } catch (Exception e) { } return font; } public static float fontWidth(PDFont font, String text, int fontSize) { try { if (font == null || text == null || fontSize <= 0) { return -1; } return fontSize * font.getStringWidth(text) / 1000; } catch (Exception e) { return -2; } } public static float fontHeight(PDFont font, int fontSize) { try { if (font == null || fontSize <= 0) { return -1; } return fontSize * font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000; } catch (Exception e) { return -2; } } public static List<PDImageXObject> getImageListFromPDF(FxTask task, PDDocument document, Integer startPage) throws Exception { List<PDImageXObject> imageList = new ArrayList<>(); if (null != document) { PDPageTree pages = document.getPages(); startPage = startPage == null ? 0 : startPage; int len = pages.getCount(); if (startPage < len) { for (int i = startPage; i < len; ++i) { if (task != null && !task.isWorking()) { return null; } PDPage page = pages.get(i); Iterable<COSName> objectNames = page.getResources().getXObjectNames(); for (COSName imageObjectName : objectNames) { if (task != null && !task.isWorking()) { return null; } if (page.getResources().isImageXObject(imageObjectName)) { imageList.add((PDImageXObject) page.getResources().getXObject(imageObjectName)); } } } } } return imageList; } public static void setAttributes(PDDocument doc, String author, int defaultZoom) { setAttributes(doc, author, "MyBox v" + AppValues.AppVersion, defaultZoom, 1.0f); } public static void setAttributes(PDDocument doc, String author, String producer, int defaultZoom, float version) { try { if (doc == null) { return; } PDDocumentInformation info = new PDDocumentInformation(); info.setCreationDate(Calendar.getInstance()); info.setModificationDate(Calendar.getInstance()); info.setProducer(producer); info.setAuthor(author); doc.setDocumentInformation(info); doc.setVersion(version); if (defaultZoom > 0 && doc.getNumberOfPages() > 0) { PDPage page = doc.getPage(0); PDPageXYZDestination dest = new PDPageXYZDestination(); dest.setPage(page); dest.setZoom(defaultZoom / 100.0f); dest.setTop((int) page.getCropBox().getHeight()); PDActionGoTo action = new PDActionGoTo(); action.setDestination(dest); doc.getDocumentCatalog().setOpenAction(action); } } catch (Exception e) { MyBoxLog.error(e); } } public static String html2pdf(FxTask task, File target, String html, String css, boolean ignoreHead, DataHolder pdfOptions) { try { if (html == null || html.isBlank()) { return null; } if (ignoreHead) { html = HtmlWriteTools.ignoreHead(task, html); if (html == null || (task != null && !task.isWorking())) { return message("Canceled"); } } if (!css.isBlank()) { try { html = PdfConverterExtension.embedCss(html, css); } catch (Exception e) { MyBoxLog.error(e.toString()); } } try { PdfConverterExtension.exportToPdf(target.getAbsolutePath(), html, "", pdfOptions); if (!target.exists()) { return message("Failed"); } else if (target.length() == 0) { FileDeleteTools.delete(target); return message("Failed"); } return message("Successful"); } catch (Exception e) { return e.toString(); } } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } } public static File html2pdf(FxTask task, String html) { try { if (html == null || html.isBlank()) { return null; } File pdfFile = FileTmpTools.generateFile("pdf"); File wqy_microhei = FxFileTools.getInternalFile("/data/wqy-microhei.ttf", "data", "wqy-microhei.ttf"); String css = "@font-face {\n" + " font-family: 'myFont';\n" + " src: url('file:///" + wqy_microhei.getAbsolutePath().replaceAll("\\\\", "/") + "');\n" + " font-weight: normal;\n" + " font-style: normal;\n" + "}\n" + " body { font-family: 'myFont';}"; DataHolder pdfOptions = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL & ~(Extensions.ANCHORLINKS | Extensions.EXTANCHORLINKS_WRAP), TocExtension.create()) .toMutable() .set(TocExtension.LIST_CLASS, PdfConverterExtension.DEFAULT_TOC_LIST_CLASS) .toImmutable(); html2pdf(task, pdfFile, html, css, true, pdfOptions); return pdfFile; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File text2pdf(FxTask task, String text) { try { if (text == null || text.isBlank()) { return null; } return html2pdf(task, HtmlWriteTools.textToHtml(text)); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File md2pdf(FxTask task, String md) { try { if (md == null || md.isBlank()) { return null; } return html2pdf(task, HtmlWriteTools.md2html(md)); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/NumberTools.java
released/MyBox/src/main/java/mara/mybox/tools/NumberTools.java
package mara.mybox.tools; import java.math.RoundingMode; import java.text.DecimalFormat; import javafx.scene.control.IndexRange; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2022-10-4 * @License Apache License Version 2.0 */ public class NumberTools { public static String format(Number data, String format) { return format(data, format, -1); } public static String format(Number data, String inFormat, int scale) { try { if (data == null) { return null; } String format = inFormat; if (format == null || format.isBlank() || Languages.matchIgnoreCase("None", format)) { return noFormat(data, scale); } else if (Languages.matchIgnoreCase("ScientificNotation", format)) { return scientificNotation(data, scale); } else if (Languages.matchIgnoreCase("GroupInThousands", format)) { return format(data, 3, scale); } else if (Languages.matchIgnoreCase("GroupInTenThousands", format)) { return format(data, 4, scale); } else { DecimalFormat df = new DecimalFormat(format); df.setMaximumFractionDigits(scale >= 0 ? scale : 340); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(data); } } catch (Exception e) { return new DecimalFormat().format(data); } } public static String noFormat(Number data, int scale) { return format(data, -1, scale); } public static String scientificNotation(Number data, int scale) { try { if (data == null) { return null; } double d = DoubleTools.scale(data.toString(), InvalidAs.Empty, scale); return d + ""; } catch (Exception e) { return null; } } public static String format(Number data) { return format(data, 3, -1); } public static String format(Number data, int scale) { return format(data, -1, scale); } public static String format(Number data, int groupSize, int scale) { try { if (data == null) { return null; } DecimalFormat df = new DecimalFormat(); if (groupSize >= 0) { df.setGroupingUsed(true); df.setGroupingSize(groupSize); } else { df.setGroupingUsed(false); } df.setMaximumFractionDigits(scale >= 0 ? scale : 340); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(data); } catch (Exception e) { return null; } } // 0-based, exclude to and end public static IndexRange scrollRange(int scrollSize, int total, int from, int to, int currentIndex) { if (total < 1) { return null; } int start = Math.max(from, currentIndex - scrollSize / 2); if (start < 0 || start >= total) { start = 0; } int end = Math.min(to, start + scrollSize); if (end < 0 || end > total) { end = total; } if (start >= end) { return null; } return new IndexRange(start, end); } public static IndexRange scrollRange(int scrollSize, int total, int currentIndex) { return scrollRange(scrollSize, total, 0, total, currentIndex); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/ConfigTools.java
released/MyBox/src/main/java/mara/mybox/tools/ConfigTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-9 7:46:58 * @Description Read data outside database * @License Apache License Version 2.0 */ public class ConfigTools { /* MyBox config */ public static String defaultDataPath() { return defaultDataPathFile().getAbsolutePath(); } public static File defaultDataPathFile() { File defaultPath = new File(System.getProperty("user.home") + File.separator + "mybox"); if (!defaultPath.exists()) { defaultPath.mkdirs(); } else if (!defaultPath.isDirectory()) { FileDeleteTools.delete(defaultPath); defaultPath.mkdirs(); } return defaultPath; } public static File defaultConfigFile() { File defaultPath = defaultDataPathFile(); File configFile = new File(defaultPath.getAbsolutePath() + File.separator + "MyBox_v" + AppValues.AppVersion + (AppValues.Alpha ? "a" : "") + ".ini"); return configFile; } public static Map<String, String> readValues() { return ConfigTools.readValues(AppVariables.MyboxConfigFile); } public static String readValue(String key) { return ConfigTools.readValue(AppVariables.MyboxConfigFile, key); } public static int readInt(String key, int defaultValue) { try { String v = ConfigTools.readValue(key); return Integer.parseInt(v); } catch (Exception e) { return defaultValue; } } public static boolean writeConfigValue(String key, String value) { try { if (!AppVariables.MyboxConfigFile.exists()) { if (!AppVariables.MyboxConfigFile.createNewFile()) { return false; } } return writeValue(AppVariables.MyboxConfigFile, key, value); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } /* General config */ public static Map<String, String> readValues(File file) { Map<String, String> values = new HashMap<>(); try { if (file == null || !file.exists()) { return values; } try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { Properties conf = new Properties(); conf.load(in); for (String key : conf.stringPropertyNames()) { values.put(key, conf.getProperty(key)); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } return values; } public static String readValue(File file, String key) { try { if (!file.exists() || !file.isFile()) { return null; } String value; try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { Properties conf = new Properties(); conf.load(in); value = conf.getProperty(key); } return value; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writeConfigValue(File file, String key, String value) { Properties conf = new Properties(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { conf.load(in); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { if (value == null) { conf.remove(key); } else { conf.setProperty(key, value); } conf.store(out, "Update " + key); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } public static boolean writeValue(File file, String key, String value) { Properties conf = new Properties(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { conf.load(in); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { if (value == null) { conf.remove(key); } else { conf.setProperty(key, value); } conf.store(out, "Update " + key); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } public static boolean writeValues(File file, Map<String, String> values) { if (file == null || values == null) { return false; } Properties conf = new Properties(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { for (String key : values.keySet()) { conf.setProperty(key, values.get(key)); } conf.store(out, "Update "); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/DoubleMatrixTools.java
released/MyBox/src/main/java/mara/mybox/tools/DoubleMatrixTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.List; import java.util.Random; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-5-18 10:37:15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class DoubleMatrixTools { // columnNumber is 0-based public static double[] columnValues(double[][] m, int columnNumber) { if (m == null || m.length == 0 || m[0].length <= columnNumber) { return null; } double[] column = new double[m.length]; for (int i = 0; i < m.length; ++i) { column[i] = m[i][columnNumber]; } return column; } public static double[][] columnVector(double x, double y, double z) { double[][] rv = new double[3][1]; rv[0][0] = x; rv[1][0] = y; rv[2][0] = z; return rv; } public static double[][] columnVector(double[] v) { double[][] rv = new double[v.length][1]; for (int i = 0; i < v.length; ++i) { rv[i][0] = v[i]; } return rv; } public static double[] matrix2Array(double[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; double[] a = new double[w * h]; for (int j = 0; j < h; ++j) { System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static double[][] array2Matrix(double[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } double[][] m = new double[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static double[][] clone(double[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static Number[][] clone(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static String print(double[][] matrix, int prefix, int scale) { try { if (matrix == null) { return ""; } String s = "", p = "", t = " "; for (int b = 0; b < prefix; b++) { p += " "; } int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { s += p; for (int j = 0; j < column; ++j) { double d = DoubleTools.scale(matrix[i][j], scale); s += d + t; } s += "\n"; } return s; } catch (Exception e) { return null; } } public static String html(double[][] matrix, int scale) { try { if (matrix == null) { return ""; } String s = "", t = "&nbsp;&nbsp;"; int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { double d = DoubleTools.scale(matrix[i][j], scale); s += d + t; } s += "<BR>\n"; } return s; } catch (Exception e) { return null; } } public static boolean same(double[][] matrixA, double[][] matrixB, int scale) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return false; } int rows = matrixA.length; int columns = matrixA[0].length; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { if (scale < 0) { if (matrixA[i][j] != matrixB[i][j]) { return false; } } else { double a = DoubleTools.scale(matrixA[i][j], scale); double b = DoubleTools.scale(matrixB[i][j], scale); if (a != b) { return false; } } } } return true; } catch (Exception e) { return false; } } public static int[][] identityInt(int n) { try { if (n < 1) { return null; } int[][] result = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static double[][] identityDouble(int n) { try { if (n < 1) { return null; } double[][] result = new double[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static double[][] randomMatrix(int n) { return randomMatrix(n, n); } public static double[][] randomMatrix(int m, int n) { try { if (n < 1) { return null; } double[][] result = new double[m][n]; Random r = new Random(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { result[i][j] = r.nextDouble(); } } return result; } catch (Exception e) { return null; } } public static double[][] vertivalMerge(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA[0].length != matrixB[0].length) { return null; } int rowsA = matrixA.length, rowsB = matrixB.length; int columns = matrixA[0].length; double[][] result = new double[rowsA + rowsB][columns]; for (int i = 0; i < rowsA; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columns); } for (int i = 0; i < rowsB; ++i) { System.arraycopy(matrixB[i], 0, result[i + rowsA], 0, columns); } return result; } catch (Exception e) { return null; } } public static double[][] horizontalMerge(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length) { return null; } int rows = matrixA.length; int columnsA = matrixA[0].length, columnsB = matrixB[0].length; int columns = columnsA + columnsB; double[][] result = new double[rows][columns]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columnsA); System.arraycopy(matrixB[i], 0, result[i], columnsA, columnsB); } return result; } catch (Exception e) { return null; } } public static double[][] add(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } double[][] result = new double[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { double[] rowA = matrixA[i]; double[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] + rowB[j]; } } return result; } catch (Exception e) { return null; } } public static double[][] subtract(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } double[][] result = new double[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { double[] rowA = matrixA[i]; double[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] - rowB[j]; } } return result; } catch (Exception e) { return null; } } public static double[][] multiply(double[][] matrixA, double[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (columnA != rowB) { return null; } double[][] result = new double[rowA][columnB]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnB; ++j) { result[i][j] = 0; for (int k = 0; k < columnA; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[] multiply(double[][] matrix, double[] columnVector) { if (matrix == null || columnVector == null) { return null; } double[] outputs = new double[matrix.length]; for (int i = 0; i < matrix.length; ++i) { double[] row = matrix[i]; outputs[i] = 0d; for (int j = 0; j < Math.min(row.length, columnVector.length); ++j) { outputs[i] += row[j] * columnVector[j]; } } return outputs; } public static double[][] transpose(double[][] matrix) { try { if (matrix == null) { return null; } int rowsNumber = matrix.length, columnsNumber = matrix[0].length; double[][] result = new double[columnsNumber][rowsNumber]; for (int row = 0; row < rowsNumber; ++row) { for (int col = 0; col < columnsNumber; ++col) { result[col][row] = matrix[row][col]; } } return result; } catch (Exception e) { return null; } } public static double[][] integer(double[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = Math.round(matrix[i][j]); } } return result; } catch (Exception e) { return null; } } public static double[][] scale(double[][] matrix, int scale) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = DoubleTools.scale(matrix[i][j], scale); } } return result; } catch (Exception e) { return null; } } public static double[][] multiply(double[][] matrix, double p) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] * p; } } return result; } catch (Exception e) { return null; } } public static double[][] divide(double[][] matrix, double p) { try { if (matrix == null || p == 0) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / p; } } return result; } catch (Exception e) { return null; } } public static double[][] power(double[][] matrix, int n) { try { if (matrix == null || n < 0) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double[][] tmp = clone(matrix); double[][] result = identityDouble(row); while (n > 0) { if (n % 2 > 0) { result = multiply(result, tmp); } tmp = multiply(tmp, tmp); n = n / 2; } return result; } catch (Exception e) { return null; } } public static double[][] inverseByAdjoint(double[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double det = determinantByComplementMinor(matrix); if (det == 0) { return null; } double[][] inverse = new double[row][column]; double[][] adjoint = adjoint(matrix); for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { inverse[i][j] = adjoint[i][j] / det; } } return inverse; } catch (Exception e) { return null; } } public static double[][] inverse(double[][] matrix) { return inverseByElimination(matrix); } public static double[][] inverseByElimination(double[][] matrix) { try { if (matrix == null) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { return null; } double[][] augmented = new double[rows][columns * 2]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrix[i], 0, augmented[i], 0, columns); augmented[i][i + columns] = 1; } augmented = reducedRowEchelonForm(augmented); double[][] inverse = new double[rows][columns]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { inverse[i][j] = augmented[i][j + columns]; } } return inverse; } catch (Exception e) { return null; } } // rowIndex, columnIndex are 0-based. public static double[][] complementMinor(double[][] matrix, int rowIndex, int columnIndex) { try { if (matrix == null || rowIndex < 0 || columnIndex < 0) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rowIndex >= rows || columnIndex >= columns) { return null; } double[][] minor = new double[rows - 1][columns - 1]; int minorRow = 0, minorColumn; for (int i = 0; i < rows; ++i) { if (i == rowIndex) { continue; } minorColumn = 0; for (int j = 0; j < columns; ++j) { if (j == columnIndex) { continue; } minor[minorRow][minorColumn++] = matrix[i][j]; } minorRow++; } return minor; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] adjoint(double[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double[][] adjoint = new double[row][column]; if (row == 1) { adjoint[0][0] = matrix[0][0]; return adjoint; } for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { adjoint[j][i] = Math.pow(-1, i + j) * determinantByComplementMinor(complementMinor(matrix, i, j)); } } return adjoint; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double determinant(double[][] matrix) throws Exception { return determinantByElimination(matrix); } public static double determinantByComplementMinor(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int row = matrix.length, column = matrix[0].length; if (row != column) { throw new Exception("InvalidValue"); } if (row == 1) { return matrix[0][0]; } if (row == 2) { return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]; } double v = 0; for (int j = 0; j < column; ++j) { double[][] minor = complementMinor(matrix, 0, j); v += matrix[0][j] * Math.pow(-1, j) * determinantByComplementMinor(minor); } return v; } catch (Exception e) { // MyBoxLog.debug(e); throw e; } } public static double determinantByElimination(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { throw new Exception("InvalidValue"); } double[][] ref = rowEchelonForm(matrix); if (ref[rows - 1][columns - 1] == 0) { return 0; } double det = 1; for (int i = 0; i < rows; ++i) { det *= ref[i][i]; } return det; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static double[][] hadamardProduct(double[][] matrixA, double[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (rowA != rowB || columnA != columnB) { return null; } double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrixA[i][j] * matrixB[i][j]; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] kroneckerProduct(double[][] matrixA, double[][] matrixB) { try { int rowsA = matrixA.length, columnsA = matrixA[0].length; int rowsB = matrixB.length, columnsB = matrixB[0].length; double[][] result = new double[rowsA * rowsB][columnsA * columnsB]; for (int i = 0; i < rowsA; ++i) { for (int j = 0; j < columnsA; ++j) { for (int m = 0; m < rowsB; m++) { for (int n = 0; n < columnsB; n++) { result[i * rowsB + m][j * columnsB + n] = matrixA[i][j] * matrixB[m][n]; } } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] rowEchelonForm(double[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; double[][] result = clone(matrix); for (int i = 0; i < Math.min(rows, columns); ++i) { if (result[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (result[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { double temp = result[row][j]; result[row][j] = result[i][j]; result[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (result[i][i] == 0) { continue; } double ratio = result[k][i] / result[i][i]; for (int j = i; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] reducedRowEchelonForm(double[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; double[][] result = rowEchelonForm(matrix); for (int i = Math.min(rows - 1, columns - 1); i >= 0; --i) { double dd = result[i][i]; if (dd == 0) { continue; } for (int k = i - 1; k >= 0; k--) { double ratio = result[k][i] / dd; for (int j = k; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } for (int j = i; j < columns; ++j) { result[i][j] = result[i][j] / dd; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double rank(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; double[][] d = clone(matrix); int i = 0; for (i = 0; i < Math.min(rows, columns); ++i) { if (d[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (d[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { double temp = d[row][j]; d[row][j] = d[i][j]; d[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (d[i][i] == 0) { continue; } double ratio = d[k][i] / d[i][i]; for (int j = i; j < columns; ++j) { d[k][j] -= ratio * d[i][j]; } } } return i; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static double[][] swapRow(double matrix[][], int a, int b) { try { for (int j = 0; j < matrix[0].length; ++j) { double temp = matrix[a][j]; matrix[a][j] = matrix[b][j]; matrix[b][j] = temp; } } catch (Exception e) { } return matrix; } public static double[][] swapColumn(double matrix[][], int columnA, int columnB) { try { for (double[] matrix1 : matrix) { double temp = matrix1[columnA]; matrix1[columnA] = matrix1[columnB]; matrix1[columnB] = temp; } } catch (Exception e) { } return matrix; } public static String dataText(double[][] data, String delimiterName) { if (data == null || data.length == 0 || delimiterName == null) { return null; } StringBuilder s = new StringBuilder(); String delimiter = TextTools.delimiterValue(delimiterName); int rowsNumber = data.length; int colsNumber = data[0].length; for (int i = 0; i < rowsNumber; i++) { for (int j = 0; j < colsNumber; j++) { s.append(data[i][j]); if (j < colsNumber - 1) { s.append(delimiter); } } s.append("\n"); } return s.toString(); } public static String dataHtml(double[][] data, String title) { if (data == null || data.length == 0) { return null; } int rowsNumber = data.length; int colsNumber = data[0].length; StringTable table = new StringTable(null, title == null ? Languages.message("Data") : title); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(data[i][j] + ""); } table.add(row); } return table.html(); } public static double[][] toArray(List<List<String>> data) { try { int rowsNumber = data.size(); int colsNumber = data.get(0).size(); if (rowsNumber <= 0 || colsNumber <= 0) { return null; } double[][] array = new double[rowsNumber][colsNumber]; for (int r = 0; r < rowsNumber; r++) { List<String> row = data.get(r); for (int c = 0; c < row.size(); c++) { double d = 0; try { d = Double.parseDouble(row.get(c)); } catch (Exception e) { } array[r][c] = d; } } return array; } catch (Exception e) { return null; } } public static List<List<String>> toList(double[][] array) { try { int rowsNumber = array.length; int colsNumber = array[0].length; List<List<String>> data = new ArrayList<>(); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(array[i][j] + ""); } data.add(row); } return data; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/TTFTools.java
released/MyBox/src/main/java/mara/mybox/tools/TTFTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class TTFTools { public static List<String> ttfList() { List<String> names = new ArrayList<>(); try { String os = SystemTools.os(); File ttfPath; switch (os) { case "win": ttfPath = new File("C:/Windows/Fonts/"); names.addAll(ttfList(ttfPath)); break; case "linux": ttfPath = new File("/usr/share/fonts/"); names.addAll(ttfList(ttfPath)); ttfPath = new File("/usr/lib/kbd/consolefonts/"); names.addAll(ttfList(ttfPath)); break; case "mac": ttfPath = new File("/Library/Fonts/"); names.addAll(ttfList(ttfPath)); ttfPath = new File("/System/Library/Fonts/"); names.addAll(ttfList(ttfPath)); break; } // http://wenq.org/wqy2/ File wqy_microhei = FxFileTools.getInternalFile("/data/wqy-microhei.ttf", "data", "wqy-microhei.ttf"); String wqy_microhei_name = wqy_microhei.getAbsolutePath() + " " + Languages.message("wqy_microhei"); if (!names.isEmpty() && names.get(0).contains(" ")) { names.add(1, wqy_microhei_name); } else { names.add(0, wqy_microhei_name); } } catch (Exception e) { MyBoxLog.error(e.toString()); } return names; } public static List<String> ttfList(File path) { List<String> names = new ArrayList<>(); try { if (path == null || !path.exists() || !path.isDirectory()) { return names; } File[] fontFiles = path.listFiles(); if (fontFiles == null || fontFiles.length == 0) { return names; } for (File file : fontFiles) { String filename = file.getAbsolutePath(); if (!filename.toLowerCase().endsWith(".ttf")) { continue; } names.add(filename); } String pathname = path.getAbsolutePath() + File.separator; List<String> cnames = new ArrayList<>(); if (names.contains(pathname + "STSONG.TTF")) { cnames.add(pathname + "STSONG.TTF" + " \u534e\u6587\u5b8b\u4f53"); } if (names.contains(pathname + "simfang.ttf")) { cnames.add(pathname + "simfang.ttf" + " \u4eff\u5b8b"); } if (names.contains(pathname + "simkai.ttf")) { cnames.add(pathname + "simkai.ttf" + " \u6977\u4f53"); } if (names.contains(pathname + "STKAITI.TTF")) { cnames.add(pathname + "STKAITI.TTF" + " \u534e\u6587\u6977\u4f53"); } if (names.contains(pathname + "SIMLI.TTF")) { cnames.add(pathname + "SIMLI.TTF" + " \u96b6\u4e66"); } if (names.contains(pathname + "STXINWEI.TTF")) { cnames.add(pathname + "STXINWEI.TTF" + " \u534e\u6587\u65b0\u9b4f"); } if (names.contains(pathname + "SIMYOU.TTF")) { cnames.add(pathname + "SIMYOU.TTF" + " \u5e7c\u5706"); } if (names.contains(pathname + "FZSTK.TTF")) { cnames.add(pathname + "FZSTK.TTF" + " \u65b9\u6b63\u8212\u4f53"); } if (names.contains(pathname + "STXIHEI.TTF")) { cnames.add(pathname + "STXIHEI.TTF" + " \u534e\u6587\u7ec6\u9ed1"); } if (names.contains(pathname + "simhei.ttf")) { cnames.add(pathname + "simhei.ttf" + " \u9ed1\u4f53"); } for (String name : names) { if (name.contains(pathname + "\u534e\u6587")) { cnames.add(name); } } names.addAll(0, cnames); } catch (Exception e) { MyBoxLog.error(e.toString()); } return names; } public static String ttf(String item) { if (item == null) { return null; } int pos = item.indexOf(" "); if (pos > 0) { return item.substring(0, pos); } return item; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/TextFileTools.java
released/MyBox/src/main/java/mara/mybox/tools/TextFileTools.java
package mara.mybox.tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.List; import mara.mybox.data.TextEditInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class TextFileTools { public static String readTexts(FxTask task, File file) { return readTexts(task, file, charset(file)); } public static String readTexts(FxTask task, File file, Charset charset) { if (file == null || charset == null) { return null; } StringBuilder s = new StringBuilder(); File validFile = FileTools.removeBOM(task, file); if (validFile == null || (task != null && !task.isWorking())) { return null; } try (final BufferedReader reader = new BufferedReader(new FileReader(validFile, charset))) { String line = reader.readLine(); if (line != null) { s.append(line); while ((line = reader.readLine()) != null) { if (task != null && !task.isWorking()) { break; } s.append(System.lineSeparator()).append(line); } } } catch (Exception e) { return null; } return s.toString(); } public static File writeFile(File file, String data) { return writeFile(file, data, Charset.forName("utf-8")); } public static File writeFile(File file, String data, Charset charset) { if (file == null || data == null) { return null; } file.getParentFile().mkdirs(); Charset fileCharset = charset != null ? charset : Charset.forName("utf-8"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, fileCharset, false))) { writer.write(data); writer.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } return file; } public static File writeFile(String data) { return writeFile(FileTmpTools.getTempFile(), data); } public static Charset charset(File file) { try { if (file == null || !file.exists()) { return Charset.forName("utf-8"); } TextEditInformation info = new TextEditInformation(file); if (TextTools.checkCharset(info)) { return info.getCharset(); } else { return Charset.forName("utf-8"); } } catch (Exception e) { return Charset.forName("utf-8"); } } public static boolean isUTF8(File file) { Charset charset = charset(file); return charset.equals(Charset.forName("utf-8")); } public static boolean mergeTextFiles(FxTask task, List<File> files, File targetFile) { if (files == null || files.isEmpty() || targetFile == null) { return false; } targetFile.getParentFile().mkdirs(); String line; try (final FileWriter writer = new FileWriter(targetFile, Charset.forName("utf-8"))) { for (File file : files) { File validFile = FileTools.removeBOM(task, file); try (final BufferedReader reader = new BufferedReader(new FileReader(validFile, charset(validFile)))) { while ((line = reader.readLine()) != null) { if (task != null && !task.isWorking()) { return false; } writer.write(line + System.lineSeparator()); } } } writer.flush(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } return true; } public static void writeLine(FxTask task, BufferedWriter writer, List<String> values, String delimiter) { try { if (writer == null || values == null || values.isEmpty() || delimiter == null) { return; } String delimiterValue = TextTools.delimiterValue(delimiter); int end = values.size() - 1; String line = ""; for (int c = 0; c <= end; c++) { if (task != null && !task.isWorking()) { return; } String value = values.get(c); if (value != null) { line += value; } if (c < end) { line += delimiterValue; } } writer.write(line + "\n"); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/DownloadTools.java
released/MyBox/src/main/java/mara/mybox/tools/DownloadTools.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mara.mybox.tools; /** * * @author mara */ public class DownloadTools { }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileTmpTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileTmpTools.java
package mara.mybox.tools; import java.io.File; import mara.mybox.value.AppPaths; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileTmpTools { public static String tmpFilename(String path) { return path + File.separator + DateTools.nowFileString() + "_" + IntTools.random(100); } public static String tmpFilename(String path, String prefix) { if (path == null) { return null; } if (prefix == null) { return FileTmpTools.tmpFilename(path); } return path + File.separator + FileNameTools.filter(prefix) + "_" + DateTools.nowFileString() + "_" + IntTools.random(100); } public static File getTempFile() { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath()); } public static File getTempFile(String suffix) { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath(), suffix); } public static File tmpFile(String prefix, String ext) { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath(), prefix, ext == null || ext.isBlank() ? null : "." + ext); } public static File getPathTempFile(String path) { if (path == null) { return null; } new File(path).mkdirs(); File file = new File(FileTmpTools.tmpFilename(path)); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path)); } return file; } public static File getPathTempFile(String path, String suffix) { if (path == null) { return null; } new File(path).mkdirs(); String s = FileNameTools.filter(suffix); s = s == null || s.isBlank() ? "" : s; File file = new File(FileTmpTools.tmpFilename(path) + s); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path) + s); } return file; } public static File getPathTempFile(String path, String prefix, String suffix) { if (path == null) { return null; } new File(path).mkdirs(); String p = FileNameTools.filter(prefix); String s = FileNameTools.filter(suffix); s = s == null || s.isBlank() ? "" : s; if (p != null && !p.isBlank()) { File tFile = new File(path + File.separator + p + s); while (tFile.exists()) { tFile = new File(tmpFilename(path, p) + s); } return tFile; } return getPathTempFile(path, s); } public static File getTempDirectory() { return getPathTempDirectory(AppVariables.MyBoxTempPath.getAbsolutePath()); } public static File getPathTempDirectory(String path) { if (path == null) { return null; } new File(path).mkdirs(); File file = new File(FileTmpTools.tmpFilename(path) + File.separator); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path) + File.separator); } file.mkdirs(); return file; } public static boolean isTmpFile(File file) { return file != null && file.getAbsolutePath().startsWith( AppVariables.MyBoxTempPath.getAbsolutePath() + File.separator); } public static String generatePath(String type) { String path = AppPaths.getGeneratedPath() + File.separator + (type == null || type.isBlank() ? "x" : FileNameTools.filter(type)); new File(path).mkdirs(); return path; } public static File generateFile(String ext) { return getPathTempFile(generatePath(ext), ext == null || ext.isBlank() ? null : "." + ext); } public static File generateFile(String prefix, String ext) { return getPathTempFile(generatePath(ext), prefix, ext == null || ext.isBlank() ? null : "." + ext); } public static boolean isGenerateFile(File file) { return file != null && file.getAbsolutePath().startsWith( AppPaths.getGeneratedPath() + File.separator); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/CsvTools.java
released/MyBox/src/main/java/mara/mybox/tools/CsvTools.java
package mara.mybox.tools; import java.io.File; import java.io.FileWriter; import java.nio.charset.Charset; import mara.mybox.dev.MyBoxLog; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVFormat.Builder; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.DuplicateHeaderMode; /** * @Author Mara * @CreateDate 2022-5 * @License Apache License Version 2.0 */ public class CsvTools { public static final char CommentsMarker = '#'; public static Builder builder(String delimiter) { String d = TextTools.delimiterValue(delimiter); if (d == null) { return null; } return CSVFormat.Builder.create() .setDelimiter(d) .setIgnoreEmptyLines(true) .setTrim(true) .setNullString("") .setCommentMarker(d.equals(CommentsMarker + "") ? null : CommentsMarker) .setDuplicateHeaderMode(DuplicateHeaderMode.ALLOW_ALL); } public static CSVFormat csvFormat(String delimiter, boolean hasHeader) { Builder builder = builder(delimiter); if (hasHeader) { builder.setHeader().setSkipHeaderRecord(true); } else { builder.setSkipHeaderRecord(false); } return builder.get(); } public static CSVFormat csvFormat(String delimiter) { return csvFormat(delimiter, true); } public static CSVFormat csvFormat() { return csvFormat(",", true); } public static CSVPrinter csvPrinter(File csvFile) { try { return new CSVPrinter(new FileWriter(csvFile, Charset.forName("UTF-8")), csvFormat()); } catch (Exception e) { return null; } } public static CSVPrinter csvPrinter(File csvFile, String delimiter, boolean hasHeader) { try { return new CSVPrinter(new FileWriter(csvFile, Charset.forName("UTF-8")), csvFormat(delimiter, hasHeader)); } catch (Exception e) { MyBoxLog.console(e); return null; } } public static CSVParser csvParser(File csvFile, String delimiter, boolean hasHeader) { try { return CSVParser.parse(csvFile, Charset.forName("UTF-8"), csvFormat(delimiter, hasHeader)); } catch (Exception e) { MyBoxLog.console(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/SvgTools.java
released/MyBox/src/main/java/mara/mybox/tools/SvgTools.java
package mara.mybox.tools; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javafx.scene.paint.Color; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageQuantization; import mara.mybox.image.data.ImageRegionKMeans; import mara.mybox.image.data.PixelsOperation; import mara.mybox.controller.BaseController; import mara.mybox.controller.ControlImageQuantization; import mara.mybox.controller.ControlSvgFromImage; import mara.mybox.controller.ControlSvgFromImage.Algorithm; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.value.Languages.message; import org.apache.batik.anim.dom.SVGDOMImplementation; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.fop.svg.PDFTranscoder; import org.w3c.dom.*; import thridparty.miguelemosreverte.ImageTracer; import static thridparty.miguelemosreverte.ImageTracer.bytetrans; import thridparty.miguelemosreverte.SVGUtils; import thridparty.miguelemosreverte.VectorizingUtils; import static mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm.RegionKMeansClustering; /** * @Author Mara * @CreateDate 2023-2-12 * @License Apache License Version 2.0 */ public class SvgTools { /* to image */ public static File docToImage(FxTask task, BaseController controller, Document doc, float width, float height, Rectangle area) { if (doc == null) { return null; } return textToImage(task, controller, XmlTools.transform(doc), width, height, area); } public static File textToImage(FxTask task, BaseController controller, String svg, float width, float height, Rectangle area) { if (svg == null || svg.isBlank()) { return null; } String handled = handleAlpha(task, controller, svg); // Looks batik does not supper color formats with alpha try (ByteArrayInputStream inputStream = new ByteArrayInputStream(handled.getBytes("utf-8"))) { return toImage(task, controller, inputStream, width, height, area); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static File fileToImage(FxTask task, BaseController controller, File file, float width, float height, Rectangle area) { if (file == null || !file.exists()) { return null; } return textToImage(task, controller, TextFileTools.readTexts(task, file), width, height, area); } public static BufferedImage pathToImage(FxTask task, BaseController controller, String path) { if (path == null || path.isBlank()) { return null; } String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" ><path d=\"" + path + "\"></path></svg>"; File tmpFile = textToImage(task, controller, svg, -1, -1, null); if (tmpFile == null || !tmpFile.exists()) { return null; } if (tmpFile.length() <= 0) { FileDeleteTools.delete(tmpFile); return null; } return ImageFileReaders.readImage(task, tmpFile); } public static File toImage(FxTask task, BaseController controller, InputStream inputStream, float width, float height, Rectangle area) { if (inputStream == null) { return null; } File tmpFile = FileTmpTools.generateFile("png"); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { PNGTranscoder transcoder = new PNGTranscoder(); if (width > 0) { transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width); } if (height > 0) { transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height); } if (area != null) { transcoder.addTranscodingHint(PNGTranscoder.KEY_AOI, area); } TranscoderInput input = new TranscoderInput(inputStream); TranscoderOutput output = new TranscoderOutput(outputStream); transcoder.transcode(input, output); outputStream.flush(); outputStream.close(); } catch (Exception e) { PopTools.showError(controller, e.toString()); } if (tmpFile.exists() && tmpFile.length() > 0) { return tmpFile; } FileDeleteTools.delete(tmpFile); return null; } /* to pdf */ public static File docToPDF(FxTask task, BaseController controller, Document doc, float width, float height, Rectangle area) { if (doc == null) { return null; } return textToPDF(task, controller, XmlTools.transform(doc), width, height, area); } public static File textToPDF(FxTask task, BaseController controller, String svg, float width, float height, Rectangle area) { if (svg == null || svg.isBlank()) { return null; } String handled = handleAlpha(task, controller, svg); // Looks batik does not supper color formats with alpha if (handled == null || (task != null && !task.isWorking())) { return null; } try (ByteArrayInputStream inputStream = new ByteArrayInputStream(handled.getBytes("utf-8"))) { return toPDF(task, controller, inputStream, width, height, area); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static File fileToPDF(FxTask task, BaseController controller, File file, float width, float height, Rectangle area) { if (file == null || !file.exists()) { return null; } return textToPDF(task, controller, TextFileTools.readTexts(task, file), width, height, area); } public static File toPDF(FxTask task, BaseController controller, InputStream inputStream, float width, float height, Rectangle area) { if (inputStream == null) { return null; } File tmpFile = FileTmpTools.generateFile("pdf"); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { PDFTranscoder transcoder = new PDFTranscoder(); if (width > 0) { transcoder.addTranscodingHint(PDFTranscoder.KEY_WIDTH, width); } if (height > 0) { transcoder.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, height); } if (area != null) { transcoder.addTranscodingHint(PDFTranscoder.KEY_AOI, area); } TranscoderInput input = new TranscoderInput(inputStream); TranscoderOutput output = new TranscoderOutput(outputStream); transcoder.transcode(input, output); outputStream.flush(); outputStream.close(); } catch (Exception e) { PopTools.showError(controller, e.toString()); } if (tmpFile.exists() && tmpFile.length() > 0) { return tmpFile; } FileDeleteTools.delete(tmpFile); return null; } /* color */ public static String handleAlpha(FxTask task, BaseController controller, String svg) { if (svg == null || svg.isBlank()) { return svg; } try { Document doc = XmlTools.textToDoc(task, controller, svg); if (doc == null || (task != null && !task.isWorking())) { return svg; } handleAlpha(task, controller, doc); return XmlTools.transform(doc); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static boolean handleAlpha(FxTask task, BaseController controller, Node node) { if (node == null) { return false; } try { if (node instanceof Element) { Element element = (Element) node; try { Color c = Color.web(element.getAttribute("stroke")); String opacity = element.getAttribute("stroke-opacity"); if (c != null) { element.setAttribute("stroke", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("stroke-opacity", c.getOpacity() + ""); } } } catch (Exception e) { } try { Color c = Color.web(element.getAttribute("fill")); String opacity = element.getAttribute("fill-opacity"); if (c != null) { element.setAttribute("fill", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("fill-opacity", c.getOpacity() + ""); } } } catch (Exception e) { } try { Color c = Color.web(element.getAttribute("color")); String opacity = element.getAttribute("opacity"); if (c != null) { element.setAttribute("color", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("opacity", c.getOpacity() + ""); } } } catch (Exception e) { } } NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { if (task != null && !task.isWorking()) { return false; } Node child = children.item(i); handleAlpha(task, controller, child); } } return true; } catch (Exception e) { PopTools.showError(controller, e.toString()); return false; } } /* values */ public static Rectangle viewBox(String value) { Rectangle rect = null; try { String[] v = value.trim().split("\\s+"); if (v != null && v.length >= 4) { rect = new Rectangle(Integer.parseInt(v[0]), Integer.parseInt(v[1]), Integer.parseInt(v[2]), Integer.parseInt(v[3])); } } catch (Exception e) { } return rect; } public static String viewBoxString(Rectangle rect) { if (rect == null) { return null; } return (int) rect.getX() + " " + (int) rect.getY() + " " + (int) rect.getWidth() + " " + (int) rect.getHeight(); } /* generate */ public static String blankSVG(float width, float height) { String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" "; if (width > 0) { svg += " width=\"" + width + "\" "; } if (height > 0) { svg += " height=\"" + height + "\" "; } return svg += " ></svg>"; } public static Document blankDoc(float width, float height) { return XmlTools.textToDoc(null, null, blankSVG(width, height)); } public static Document blankDoc() { return blankDoc(500.0f, 500.0f); } public static Document focus(FxTask task, Document doc, Node node, float bgOpacity) { if (doc == null) { return doc; } Document clonedDoc = (Document) doc.cloneNode(true); if (node == null || !(node instanceof Element) || "svg".equalsIgnoreCase(node.getNodeName())) { return clonedDoc; } String hierarchyNumber = XmlTools.hierarchyNumber(node); if (hierarchyNumber == null) { return clonedDoc; } Node targetNode = XmlTools.find(clonedDoc, hierarchyNumber); Node cnode = targetNode; while (cnode != null) { if (task != null && !task.isWorking()) { return doc; } Node parent = cnode.getParentNode(); if (parent == null) { break; } NodeList nodes = parent.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (task != null && !task.isWorking()) { return doc; } Node child = nodes.item(i); if (child.equals(cnode) || !(child instanceof Element)) { continue; } ((Element) child).setAttribute("opacity", bgOpacity + ""); } cnode = parent; } return clonedDoc; } public static Document removeSize(Document doc) { if (doc == null) { return doc; } Document clonedDoc = (Document) doc.cloneNode(true); Element svgNode = XmlTools.findName(clonedDoc, "svg", 0); svgNode.removeAttribute("width"); svgNode.removeAttribute("height"); svgNode.removeAttribute("viewBox"); return clonedDoc; } public static File toFile(SVGGraphics2D g, File file) { if (g == null || file == null) { return null; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, Charset.forName("utf-8"), false))) { g.stream(writer, true); writer.flush(); return file; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File toFile(SVGGraphics2D g) { if (g == null) { return null; } File tmpFile = FileTmpTools.getTempFile(".svg"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile, Charset.forName("utf-8"), false))) { g.stream(writer, true); writer.flush(); return tmpFile; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toText(FxTask task, SVGGraphics2D g) { String s = TextFileTools.readTexts(task, toFile(g), Charset.forName("utf-8")); return s; // if (s == null) { // return null; // } // return s.replaceAll("><", ">\n<"); } /* SVGGraphics2D */ public static Document document() { return GenericDOMImplementation.getDOMImplementation().createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null); } /* image to svg */ public static String imagefileToSvg(FxTask task, BaseController controller, File imageFile, ControlSvgFromImage optionsController) { try { if (imageFile == null || !imageFile.exists()) { return null; } BufferedImage image = ImageFileReaders.readImage(task, imageFile); if (image == null || (task != null && !task.isWorking())) { return null; } return imageToSvg(task, controller, image, optionsController); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } // https://github.com/miguelemosreverte/imagetracerjava public static String imageToSvg(FxTask task, BaseController controller, BufferedImage inImage, ControlSvgFromImage optionsController) { try { if (optionsController == null || inImage == null) { PopTools.showError(controller, message("InvalidData")); return null; } BufferedImage image = AlphaTools.removeAlpha(task, inImage); switch (optionsController.getQuantization()) { case jankovicsandras: return jankovicsandras(task, controller, image, optionsController); case mybox: return mybox(task, controller, image, optionsController); default: return miguelemosreverte(task, controller, image, optionsController); } } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String miguelemosreverte(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } HashMap<String, Float> options = optionsController.getOptions(); options = ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.IndexedImage ii = miguelemosreverteQuantization(task, controller, image, options); if (ii == null || (task != null && !task.isWorking())) { return null; } return miguelemosreverteSVG(task, controller, ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static ImageTracer.IndexedImage miguelemosreverteQuantization(FxTask task, BaseController controller, BufferedImage image, HashMap<String, Float> options) { try { if (image == null) { PopTools.showError(controller, message("InvalidData")); return null; } if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.ImageData imgd = ImageTracer.loadImageData(image); if (imgd == null || (task != null && !task.isWorking())) { return null; } byte[][] palette = ImageTracer.getPalette(image, options); if (palette == null || (task != null && !task.isWorking())) { return null; } return VectorizingUtils.colorquantization(imgd, palette, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String miguelemosreverteSVG(FxTask task, BaseController controller, ImageTracer.IndexedImage ii, HashMap<String, Float> options) { try { if (ii == null || (task != null && !task.isWorking())) { return null; } // 2. Layer separation and edge detection int[][][] rawlayers = VectorizingUtils.layering(ii); if (rawlayers == null || (task != null && !task.isWorking())) { return null; } // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = VectorizingUtils.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); if (bps == null || (task != null && !task.isWorking())) { return null; } // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = VectorizingUtils.batchinternodes(bps); if (bis == null || (task != null && !task.isWorking())) { return null; } // 5. Batch tracing ii.layers = VectorizingUtils.batchtracelayers(bis, options.get("ltres"), options.get("qtres")); if (ii.layers == null || (task != null && !task.isWorking())) { return null; } return SVGUtils.getsvgstring(ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String jankovicsandras(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } HashMap<String, Float> options = optionsController.getOptions(); options = thridparty.jankovicsandras.ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } thridparty.jankovicsandras.ImageTracer.IndexedImage ii = jankovicsandrasQuantization(task, controller, image, options); if (ii == null || (task != null && !task.isWorking())) { return null; } return jankovicsandrasSVG(task, controller, ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } // https://github.com/jankovicsandras/imagetracerjava public static thridparty.jankovicsandras.ImageTracer.IndexedImage jankovicsandrasQuantization(FxTask task, BaseController controller, BufferedImage image, HashMap<String, Float> options) { try { if (image == null || options == null) { return null; } thridparty.jankovicsandras.ImageTracer.ImageData imgd = thridparty.jankovicsandras.ImageTracer.loadImageData(image); if (imgd == null || (task != null && !task.isWorking())) { return null; } return thridparty.jankovicsandras.ImageTracer.colorquantization(imgd, null, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String jankovicsandrasSVG(FxTask task, BaseController controller, thridparty.jankovicsandras.ImageTracer.IndexedImage ii, HashMap<String, Float> options) { try { if (ii == null || (task != null && !task.isWorking())) { return null; } // 2. Layer separation and edge detection int[][][] rawlayers = thridparty.jankovicsandras.ImageTracer.layering(ii); if (rawlayers == null || (task != null && !task.isWorking())) { return null; } // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = thridparty.jankovicsandras.ImageTracer.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); if (bps == null || (task != null && !task.isWorking())) { return null; } // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = thridparty.jankovicsandras.ImageTracer.batchinternodes(bps); if (bis == null || (task != null && !task.isWorking())) { return null; } // 5. Batch tracing ii.layers = thridparty.jankovicsandras.ImageTracer.batchtracelayers(bis, options.get("ltres"), options.get("qtres")); if (ii.layers == null || (task != null && !task.isWorking())) { return null; } return thridparty.jankovicsandras.ImageTracer.getsvgstring(ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static ImageKMeans myboxQuantization(FxTask task, BaseController controller, BufferedImage image, ControlImageQuantization quantization) { try { ImageKMeans kmeans = ImageKMeans.create(); kmeans.setAlgorithm(RegionKMeansClustering). setQuantizationSize(quantization.getQuanColors()) .setRegionSize(quantization.getRegionSize()) .setWeight1(quantization.getRgbWeight1()) .setWeight2(quantization.getRgbWeight2()) .setWeight3(quantization.getRgbWeight3()) .setRecordCount(false) .setFirstColor(quantization.getFirstColorCheck().isSelected()) .setOperationType(PixelsOperation.OperationType.Quantization) .setImage(image).setScope(null) .setIsDithering(quantization.getQuanDitherCheck().isSelected()) .setTask(task); kmeans.makePalette().start(); return kmeans; } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String mybox(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } ImageKMeans kmeans = myboxQuantization(task, controller, image, optionsController.getQuantizationController()); if (kmeans == null || kmeans.paletteBytes == null || kmeans.getColorIndice() == null || (task != null && !task.isWorking())) { return null; } HashMap<String, Float> options = optionsController.getOptions(); MyBoxLog.console(optionsController.getLayer().name()); if (optionsController.getLayer() == Algorithm.jankovicsandras) { options = thridparty.jankovicsandras.ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } thridparty.jankovicsandras.ImageTracer.IndexedImage ii = new thridparty.jankovicsandras.ImageTracer.IndexedImage( kmeans.getColorIndice(), kmeans.paletteBytes); return jankovicsandrasSVG(task, controller, ii, options); } else { options = ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.IndexedImage ii = new ImageTracer.IndexedImage( kmeans.getColorIndice(), kmeans.paletteBytes); return miguelemosreverteSVG(task, controller, ii, options); } } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static class ImageKMeans extends ImageQuantization { public int[][] colorIndice; public byte[][] paletteBytes; protected ImageRegionKMeans kmeans; protected List<java.awt.Color> paletteColors; public static ImageKMeans create() { return new ImageKMeans(); } public ImageKMeans makePalette() { try { kmeans = imageRegionKMeans(); paletteColors = kmeans.getCenters(); int size = paletteColors.size(); paletteBytes = new byte[size + 1][4]; for (int i = 0; i < size; i++) { if (task != null && !task.isWorking()) { return null; } int value = paletteColors.get(i).getRGB(); paletteBytes[i][3] = bytetrans((byte) (value >>> 24)); paletteBytes[i][0] = bytetrans((byte) (value >>> 16)); paletteBytes[i][1] = bytetrans((byte) (value >>> 8)); paletteBytes[i][2] = bytetrans((byte) (value)); } int transparent = 0; paletteBytes[size][3] = bytetrans((byte) (transparent >>> 24)); paletteBytes[size][0] = bytetrans((byte) (transparent >>> 16)); paletteBytes[size][1] = bytetrans((byte) (transparent >>> 8)); paletteBytes[size][2] = bytetrans((byte) (transparent)); int width = image.getWidth(); int height = image.getHeight(); colorIndice = new int[height + 2][width + 2]; for (int j = 0; j < (height + 2); j++) { if (task != null && !task.isWorking()) { return null; } colorIndice[j][0] = -1; colorIndice[j][width + 1] = -1; } for (int i = 0; i < (width + 2); i++) { if (task != null && !task.isWorking()) { return null; } colorIndice[0][i] = -1; colorIndice[height + 1][i] = -1; } } catch (Exception e) { MyBoxLog.debug(e); } return this; } @Override public java.awt.Color operateColor(java.awt.Color color) { try { java.awt.Color mappedColor = kmeans.map(color); int index = paletteColors.indexOf(mappedColor); colorIndice[currentY + 1][currentX + 1] = index; return mappedColor; } catch (Exception e) { return color; } } /* get/set */ public int[][] getColorIndice() { return colorIndice; } public byte[][] getPaletteBytes() { return paletteBytes; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/MarkdownTools.java
released/MyBox/src/main/java/mara/mybox/tools/MarkdownTools.java
package mara.mybox.tools; import com.vladsch.flexmark.ast.Heading; import com.vladsch.flexmark.ast.Image; import com.vladsch.flexmark.ast.ImageRef; import com.vladsch.flexmark.ext.abbreviation.AbbreviationExtension; import com.vladsch.flexmark.ext.definition.DefinitionExtension; import com.vladsch.flexmark.ext.footnotes.FootnoteExtension; import com.vladsch.flexmark.ext.tables.TablesExtension; import com.vladsch.flexmark.ext.typographic.TypographicExtension; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.parser.ParserEmulationProfile; import com.vladsch.flexmark.util.ast.Block; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.MutableDataHolder; import com.vladsch.flexmark.util.data.MutableDataSet; import com.vladsch.flexmark.util.sequence.BasedSequence; import java.io.File; import java.net.URLDecoder; import java.nio.charset.Charset; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.data.Link; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.UserConfig; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; /** * @Author Mara * @CreateDate 2020-10-21 * @License Apache License Version 2.0 */ public class MarkdownTools { public static String string(BasedSequence string) { if (string == null) { return null; } try { return URLDecoder.decode(string.toStringOrNull(), "UTF-8"); } catch (Exception e) { return null; } } // https://github.com/vsch/flexmark-java/blob/master/flexmark-java-samples/src/com/vladsch/flexmark/java/samples/TitleExtract.java public static void links(Node node, List<Link> links) { if (node == null || links == null) { return; } if (node instanceof com.vladsch.flexmark.ast.Link) { com.vladsch.flexmark.ast.Link mdLink = (com.vladsch.flexmark.ast.Link) node; try { Link link = Link.create() .setAddress(string(mdLink.getUrl())) .setName(string(mdLink.getText())) .setTitle(string(mdLink.getTitle())) .setIndex(links.size()); links.add(link); } catch (Exception e) { } } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { links(child, links); child = child.getNext(); } } } public static void heads(Node node, List<Heading> heads) { if (node == null || heads == null) { return; } if (node instanceof Heading) { Heading head = (Heading) node; heads.add(head); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { heads(child, heads); child = child.getNext(); } } } public static String toc(Node node, int indentSize) { if (node == null) { return null; } List<Heading> heads = new ArrayList<>(); heads(node, heads); String toc = ""; for (Heading head : heads) { for (int i = 0; i < head.getLevel() * indentSize; i++) { toc += " "; } toc += head.getText() + "\n"; } return toc; } public static void images(Node node, List<Image> images) { if (node == null || images == null) { return; } if (node instanceof Image) { Image image = (Image) node; images.add(image); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { images(child, images); child = child.getNext(); } } } public static void imageRefs(Node node, List<ImageRef> imageRefs) { if (node == null || imageRefs == null) { return; } if (node instanceof ImageRef) { ImageRef imageRef = (ImageRef) node; imageRefs.add(imageRef); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { imageRefs(child, imageRefs); child = child.getNext(); } } } public static MutableDataHolder htmlOptions(String emulation, int indentSize, boolean trim, boolean discard, boolean append) { try { MutableDataHolder htmlOptions = new MutableDataSet(); htmlOptions.setFrom(ParserEmulationProfile.valueOf(emulation)); htmlOptions.set(Parser.EXTENSIONS, Arrays.asList( AbbreviationExtension.create(), DefinitionExtension.create(), FootnoteExtension.create(), TypographicExtension.create(), TablesExtension.create() )); htmlOptions.set(HtmlRenderer.INDENT_SIZE, indentSize) // .set(HtmlRenderer.PERCENT_ENCODE_URLS, true) // .set(TablesExtension.COLUMN_SPANS, false) .set(TablesExtension.TRIM_CELL_WHITESPACE, trim) .set(TablesExtension.DISCARD_EXTRA_COLUMNS, discard) .set(TablesExtension.APPEND_MISSING_COLUMNS, append); return htmlOptions; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static MutableDataHolder htmlOptions() { try (Connection conn = DerbyBase.getConnection()) { return htmlOptions(UserConfig.getString(conn, "MarkdownEmulation", "PEGDOWN"), UserConfig.getInt(conn, "MarkdownIndent", 4), UserConfig.getBoolean(conn, "MarkdownTrim", false), UserConfig.getBoolean(conn, "MarkdownDiscard", false), UserConfig.getBoolean(conn, "MarkdownAppend", false)); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(FxTask task, MutableDataHolder htmlOptions, File mdFile, String style) { try { if (mdFile == null || !mdFile.exists()) { return null; } Parser htmlParser = Parser.builder(htmlOptions).build(); HtmlRenderer htmlRender = HtmlRenderer.builder(htmlOptions).build(); Node document = htmlParser.parse(TextFileTools.readTexts(task, mdFile)); String html = htmlRender.render(document); Document doc = Jsoup.parse(html); if (doc == null) { return null; } HtmlWriteTools.setCharset(task, doc, Charset.forName("UTF-8")); if (task != null && !task.isWorking()) { return null; } doc.head().appendChild(new Element("style").text(style)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/NetworkTools.java
released/MyBox/src/main/java/mara/mybox/tools/NetworkTools.java
package mara.mybox.tools; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.util.Enumeration; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-6-9 7:46:58 * @License Apache License Version 2.0 */ public class NetworkTools { public static int findFreePort(int port) { int p; try { Socket socket = new Socket(InetAddress.getLocalHost(), port); socket.close(); p = port; } catch (Exception e) { try { try (ServerSocket serverSocket = new ServerSocket(0)) { p = serverSocket.getLocalPort(); } } catch (Exception ex) { p = -1; } } return p; } public static boolean isPortUsed(int port) { try { Socket socket = new Socket(InetAddress.getLocalHost(), port); socket.close(); return true; } catch (Exception e) { return false; } } // https://www.cnblogs.com/starcrm/p/7071227.html public static InetAddress localHost() { try { InetAddress candidateAddress = null; MyBoxLog.debug("InetAddress.getLocalHost():" + InetAddress.getLocalHost()); for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); MyBoxLog.debug("inetAddr.getHostAddress:" + inetAddr.getHostAddress()); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { return inetAddr; } else if (candidateAddress == null) { candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress; } InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { return InetAddress.getByName("localhost"); } return jdkSuppliedAddress; } catch (Exception e) { return null; } } public static SSLContext sslContext() { try { SSLContext context = SSLContext.getInstance(AppValues.HttpsProtocal); context.init(null, null, null); return context; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SSLSocketFactory sslSocketFactory() { try { return sslContext().getSocketFactory(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SSLSocket sslSocket(String host, int port) { try { return (SSLSocket) sslSocketFactory().createSocket(host, port); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HttpURLConnection httpConnection(URL url) { try { if ("https".equals(url.getProtocol())) { HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sslSocketFactory()); return conn; } else { return (HttpURLConnection) url.openConnection(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String host2ipv4(FxTask task, String host) { try { if (host == null) { return null; } String ip = host2ipv4ByIpaddress(task, host); if (ip != null && !ip.isBlank()) { return ip; } InetAddress a = InetAddress.getByName(host); return a.getHostAddress(); } catch (Exception e) { // MyBoxLog.debug(e); return host; } } // https://fastly.net.ipaddress.com/github.global.ssl.fastly.net public static String host2ipv4ByIpaddress(FxTask task, String host) { try { if (host == null) { return null; } String[] nodes = host.split("\\."); if (nodes.length < 2) { return null; } String domain = nodes[nodes.length - 2] + "." + nodes[nodes.length - 1]; String address = "https://" + domain + ".ipaddress.com/" + (nodes.length == 2 ? "" : host); String data = HtmlReadTools.url2html(task, address); if (data == null) { return null; } String flag = "<tr><th>IP Address</th><td><ul class=\"comma-separated\"><li>"; int start = data.indexOf(flag); if (start < 0) { return null; } data = data.substring(start + flag.length()); int end = data.indexOf("</li>"); if (end < 0) { return null; } return data.substring(0, end); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String ip2host(String ip) { try { if (ip == null) { return null; } InetAddress a = InetAddress.getByName(ip); return a.getHostName(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean isIPv4(String ip) { try { if (ip == null) { return false; } String[] nodes = ip.split("\\."); if (nodes.length != 4) { return false; } for (String node : nodes) { int v = Integer.parseInt(node); if (v < 0 || v > 255) { return false; } } return true; } catch (Exception e) { return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/ByteFileTools.java
released/MyBox/src/main/java/mara/mybox/tools/ByteFileTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class ByteFileTools { // Can not handle file larger than 2g public static byte[] readBytes(File file) { byte[] data = null; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { int bufSize = (int) file.length(); data = new byte[bufSize]; int readLen = inputStream.read(data); if (readLen > 0 && readLen < bufSize) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e); } return data; } public static byte[] readBytes(File file, long offset, int length) { if (file == null || offset < 0 || length <= 0) { return null; } byte[] data; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { data = new byte[length]; inputStream.skip(offset); int readLen = inputStream.read(data); if (readLen > 0 && readLen < length) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e); return null; } return data; } public static File writeFile(File file, byte[] data) { if (file == null || data == null) { return null; } file.getParentFile().mkdirs(); try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { outputStream.write(data); outputStream.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } return file; } public static boolean mergeBytesFiles(File file1, File file2, File targetFile) { try { List<File> files = new ArrayList(); files.add(file1); files.add(file2); return mergeBytesFiles(files, targetFile); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean mergeBytesFiles(List<File> files, File targetFile) { if (files == null || files.isEmpty() || targetFile == null) { return false; } targetFile.getParentFile().mkdirs(); try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int bufLen; for (File file : files) { try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { while ((bufLen = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bufLen); } } } } catch (Exception e) { MyBoxLog.debug(e); return false; } return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/MicrosoftDocumentTools.java
released/MyBox/src/main/java/mara/mybox/tools/MicrosoftDocumentTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.MainExtractorFactory; import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.extractor.ole2.OLE2ScratchpadExtractorFactory; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFPictureShape; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbookFactory; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.ooxml.extractor.POIXMLExtractorFactory; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xslf.usermodel.XSLFSlideShowFactory; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory; import org.w3c.dom.Document; /** * @Author Mara * @CreateDate 2020-2-22 * @License Apache License Version 2.0 */ public class MicrosoftDocumentTools { public static String cellString(Cell cell) { if (cell == null) { return null; } switch (cell.getCellType()) { case STRING: return cell.getStringCellValue(); case NUMERIC: return cell.getNumericCellValue() + ""; case BOOLEAN: return cell.getBooleanCellValue() + ""; } return null; } public static void copyRow(Row sourceRow, Row targetRow) { if (sourceRow == null || targetRow == null) { return; } for (int col = sourceRow.getFirstCellNum(); col < sourceRow.getLastCellNum(); col++) { Cell sourceCell = sourceRow.getCell(col); if (sourceCell == null) { continue; } CellType type = sourceCell.getCellType(); if (type == null) { type = CellType.STRING; } Cell targetCell = targetRow.createCell(col, type); copyCell(sourceCell, targetCell, type); } } public static void copyCell(Cell sourceCell, Cell targetCell, CellType type) { if (sourceCell == null || targetCell == null || type == null) { return; } try { switch (type) { case STRING: targetCell.setCellValue(sourceCell.getStringCellValue()); break; case NUMERIC: targetCell.setCellValue(sourceCell.getNumericCellValue()); break; case BLANK: targetCell.setCellValue(""); break; case BOOLEAN: targetCell.setCellValue(sourceCell.getBooleanCellValue()); break; case ERROR: targetCell.setCellErrorValue(sourceCell.getErrorCellValue()); break; case FORMULA: targetCell.setCellFormula(sourceCell.getCellFormula()); break; } } catch (Exception e) { MyBoxLog.debug(e); } } public static void setCell(Cell targetCell, CellType type, String value) { if (value == null || targetCell == null || type == null) { return; } try { if (type == CellType.NUMERIC) { try { long v = Long.parseLong(value); targetCell.setCellValue(v); return; } catch (Exception e) { } try { double v = Double.parseDouble(value); targetCell.setCellValue(v); return; } catch (Exception e) { } } targetCell.setCellValue(value); } catch (Exception e) { MyBoxLog.debug(e); } } public static boolean createXLSX(File file, List<String> columns, List<List<String>> rows) { try { if (file == null || columns == null || rows == null || columns.isEmpty()) { return false; } XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("sheet1"); // sheet.setDefaultColumnWidth(20); XSSFRow titleRow = sheet.createRow(0); XSSFCellStyle horizontalCenter = wb.createCellStyle(); horizontalCenter.setAlignment(HorizontalAlignment.CENTER); for (int i = 0; i < columns.size(); i++) { XSSFCell cell = titleRow.createCell(i); cell.setCellValue(columns.get(i)); cell.setCellStyle(horizontalCenter); } for (int i = 0; i < rows.size(); i++) { XSSFRow row = sheet.createRow(i + 1); List<String> values = rows.get(i); for (int j = 0; j < values.size(); j++) { XSSFCell cell = row.createCell(j); cell.setCellValue(values.get(j)); } } for (int i = 0; i < columns.size(); i++) { sheet.autoSizeColumn(i); } try (OutputStream fileOut = new FileOutputStream(file)) { wb.write(fileOut); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean createXLS(File file, List<String> columns, List<List<String>> rows) { try { if (file == null || columns == null || rows == null || columns.isEmpty()) { return false; } HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); // sheet.setDefaultColumnWidth(40); HSSFRow titleRow = sheet.createRow(0); HSSFCellStyle horizontalCenter = wb.createCellStyle(); horizontalCenter.setAlignment(HorizontalAlignment.CENTER); for (int i = 0; i < columns.size(); i++) { HSSFCell cell = titleRow.createCell(i); cell.setCellValue(columns.get(i)); cell.setCellStyle(horizontalCenter); } for (int i = 1; i <= rows.size(); i++) { HSSFRow row = sheet.createRow(0); List<String> values = rows.get(i); for (int j = 0; j < values.size(); j++) { HSSFCell cell = row.createCell(j); cell.setCellValue(values.get(j)); } } try (OutputStream fileOut = new FileOutputStream(file)) { wb.write(fileOut); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static Document word97ToDoc(File srcFile) { Document doc = null; try (HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile))) { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); WordToHtmlConverter converter = new WordToHtmlConverter(doc); converter.processDocument(wordDocument); doc = converter.getDocument(); } catch (Exception e) { MyBoxLog.console(e); } return doc; } public static String word97Tohtml(File srcFile, Charset charset) { try { Document doc = word97ToDoc(srcFile); if (doc == null) { return null; } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.ENCODING, charset == null ? "UTF-8" : charset.name()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc), new StreamResult(baos)); baos.flush(); baos.close(); return baos.toString(charset); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File word2HtmlFile(File srcFile, Charset charset) { try { String suffix = FileNameTools.ext(srcFile.getName()); String html; if ("doc".equalsIgnoreCase(suffix)) { html = word97Tohtml(srcFile, charset); } else if ("docx".equalsIgnoreCase(suffix)) { String text = extractText(srcFile); if (text == null) { return null; } html = HtmlWriteTools.textToHtml(text); } else { return null; } return HtmlWriteTools.writeHtml(html); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String word2Html(FxTask task, File srcFile, Charset charset) { try { File htmlFile = word2HtmlFile(srcFile, charset); return TextFileTools.readTexts(task, htmlFile, charset); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HSLFPictureShape imageShape(FxTask task, HSLFSlideShow ppt, BufferedImage image, String format) { try { byte[] bytes = ByteTools.imageToBytes(task, image, format); PictureType type; if ("png".equalsIgnoreCase(format)) { type = PictureType.PNG; } else if ("jpg".equalsIgnoreCase(format) || "jpeg".equalsIgnoreCase(format)) { type = PictureType.JPEG; } else if ("bmp".equalsIgnoreCase(format)) { type = PictureType.BMP; } else if ("gif".equalsIgnoreCase(format)) { type = PictureType.GIF; } else if ("tif".equalsIgnoreCase(format) || "tiff".equalsIgnoreCase(format)) { type = PictureType.TIFF; } else { type = PictureType.PNG; } HSLFPictureData pd = ppt.addPicture(bytes, type); return new HSLFPictureShape(pd); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String extractText(File srcFile) { String text = null; try (POITextExtractor extractor = ExtractorFactory.createExtractor(srcFile)) { text = extractor.getText(); } catch (Exception e) { MyBoxLog.error(e); } return text; } // https://github.com/Mararsh/MyBox/issues/1100 public static void registryFactories() { SlideShowFactory.addProvider(new HSLFSlideShowFactory()); SlideShowFactory.addProvider(new XSLFSlideShowFactory()); ExtractorFactory.addProvider(new MainExtractorFactory()); ExtractorFactory.addProvider(new OLE2ScratchpadExtractorFactory()); ExtractorFactory.addProvider(new POIXMLExtractorFactory()); WorkbookFactory.addProvider(new HSSFWorkbookFactory()); WorkbookFactory.addProvider(new XSSFWorkbookFactory()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/ByteTools.java
released/MyBox/src/main/java/mara/mybox/tools/ByteTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterOutputStream; import javafx.scene.control.IndexRange; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.data.FileEditInformation.Line_Break; import mara.mybox.data.FindReplaceString; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @Description * @License Apache License Version 2.0 */ public class ByteTools { public static int Invalid_Byte = AppValues.InvalidShort; // https://stackoverflow.com/questions/4485128/how-do-i-convert-long-to-byte-and-back-in-java public static int bytesToInt(byte[] b) { return ByteBuffer.allocate(Integer.BYTES).put(b).flip().getInt(); } public static long bytesToUInt(byte[] b) { return bytesToLong(mergeBytes(new byte[4], b)); } public static long bytesToLong(byte[] b) { return ByteBuffer.allocate(Long.BYTES).put(b).flip().getLong(); } public static int bytesToUshort(byte[] b) { return bytesToInt(mergeBytes(new byte[2], b)); } // https://stackoverflow.com/questions/6374915/java-convert-int-to-byte-array-of-4-bytes?r=SearchResults public static byte[] intToBytes(int a) { return ByteBuffer.allocate(Integer.BYTES).putInt(a).array(); } public static byte intSmallByte(int a) { byte[] bytes = intToBytes(a); return bytes[3]; } public static byte intBigByte(int a) { byte[] bytes = intToBytes(a); return bytes[0]; } public static byte[] longToBytes(long a) { return ByteBuffer.allocate(Long.BYTES).putLong(a).array(); } public static byte[] uIntToBytes(long a) { return subBytes(longToBytes(a), 4, 4); } public static byte[] uShortToBytes(int a) { return subBytes(intToBytes(a), 2, 2); } public static byte[] shortToBytes(short a) { return ByteBuffer.allocate(Short.BYTES).putShort(a).array(); } public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { hex = "0" + hex; } return hex; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex); } return sb.toString(); } public static String bytesToHexFormat(byte[] bytes) { if (bytes == null) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); } String s = sb.toString(); return s.toUpperCase(); } public static String stringToHexFormat(String text) { return bytesToHexFormatWithCF(text.getBytes()); } public static String bytesToHexFormatWithCF(byte[] bytes) { return bytesToHexFormatWithCF(bytes, bytesToHex("\n".getBytes())); } public static String bytesToHexFormatWithCF(byte[] bytes, String newLineHex) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); } String s = sb.toString(); s = s.replace(newLineHex + " ", newLineHex + "\n"); s = s.toUpperCase(); return s; } public static String bytesToHexFormat(byte[] bytes, int newLineWidth) { StringBuilder sb = new StringBuilder(); int count = 1; for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); if (count % newLineWidth == 0) { sb.append("\n"); } count++; } String s = sb.toString(); s = s.toUpperCase(); return s; } public static byte[] hexToBytes(String inHex) { try { int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1) { hexlen++; result = new byte[(hexlen / 2)]; inHex = "0" + inHex; } else { result = new byte[(hexlen / 2)]; } int j = 0; for (int i = 0; i < hexlen; i += 2) { result[j] = hexToByte(inHex.substring(i, i + 2)); j++; } return result; } catch (Exception e) { return null; } } public static byte hexToByte(String inHex) { try { return (byte) Integer.parseInt(inHex, 16); } catch (Exception e) { return 0; } } public static byte hexToByteAnyway(String inHex) { try { return (byte) Integer.parseInt(inHex, 16); } catch (Exception e) { return Byte.valueOf("63");// "?" } } public static int hexToInt(String inHex) { try { if (inHex.length() == 0 || inHex.length() > 2) { return Invalid_Byte; } String hex = inHex; if (inHex.length() == 1) { hex = "0" + hex; } return Integer.parseInt(hex, 16); } catch (Exception e) { return Invalid_Byte; } } public static String validateByteHex(String inHex) { try { if (inHex.length() == 0 || inHex.length() > 2) { return null; } String hex = inHex; if (inHex.length() == 1) { hex = "0" + hex; } Integer.parseInt(hex, 16); return hex; } catch (Exception e) { return null; } } public static boolean isByteHex(String inHex) { try { if (inHex.length() != 2) { return false; } Integer.parseInt(inHex, 16); return true; } catch (Exception e) { return false; } } public static boolean isBytesHex(String inHex) { try { String hex = inHex.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = hex.length(); if (hexlen % 2 == 1) { return false; } for (int i = 0; i < hexlen; i += 2) { Integer.parseInt(hex.substring(i, i + 2), 16); } return true; } catch (Exception e) { return false; } } public static boolean validateTextHex(String text) { try { String inHex = text.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = inHex.length(); if (hexlen % 2 == 1) { return false; } String b; for (int i = 0; i < hexlen; i += 2) { b = inHex.substring(i, i + 2); Integer.parseInt(b, 16); } return true; } catch (Exception e) { return false; } } public static String formatTextHex(String text) { try { String inHex = text.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = inHex.length(); if (hexlen % 2 == 1) { return null; } StringBuilder sb = new StringBuilder(); String b; for (int i = 0; i < hexlen; i += 2) { b = inHex.substring(i, i + 2); Integer.parseInt(b, 16); sb.append(b).append(" "); } return sb.toString(); } catch (Exception e) { return null; } } public static byte[] hexFormatToBytes(String hexFormat) { try { String hex = hexFormat.replaceAll("\\s+|\n", ""); int hexlen = hex.length(); byte[] result; if (hexlen % 2 == 1) { hexlen++; result = new byte[(hexlen / 2)]; hex = "0" + hex; } else { result = new byte[(hexlen / 2)]; } int j = 0; for (int i = 0; i < hexlen; i += 2) { result[j] = hexToByteAnyway(hex.substring(i, i + 2)); j++; } return result; } catch (Exception e) { return null; } } public static byte[] subBytes(byte[] bytes, int off, int length) { try { byte[] newBytes = new byte[length]; System.arraycopy(bytes, off, newBytes, 0, length); return newBytes; } catch (Exception e) { MyBoxLog.error(e, bytes.length + " " + off + " " + length); return null; } } public static byte[] mergeBytes(byte[] bytes1, byte[] bytes2) { try { byte[] bytes3 = new byte[bytes1.length + bytes2.length]; System.arraycopy(bytes1, 0, bytes3, 0, bytes1.length); System.arraycopy(bytes2, 0, bytes3, bytes1.length, bytes2.length); return bytes3; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static int countNumber(FxTask currentTask, byte[] bytes, byte[] subBytes) { return FindReplaceString.count(currentTask, bytesToHex(bytes), bytesToHex(subBytes)); } public static int countNumber(FxTask currentTask, byte[] bytes, byte c) { return FindReplaceString.count(currentTask, bytesToHex(bytes), byteToHex(c)); } public static int countNumber(FxTask currentTask, byte[] bytes, String hex) { return FindReplaceString.count(currentTask, bytesToHex(bytes), hex); } public static int lineIndex(String lineText, Charset charset, int offset) { int hIndex = 0; byte[] cBytes; for (int i = 0; i < lineText.length(); ++i) { char c = lineText.charAt(i); cBytes = String.valueOf(c).getBytes(charset); int clen = cBytes.length * 3; if (offset <= hIndex + clen) { return i; } hIndex += clen; } return -1; } public static IndexRange textIndex(String hex, Charset charset, IndexRange hexRange) { int hIndex = 0, cindex = 0; int cBegin = 0; int cEnd = 0; int hexBegin = hexRange.getStart(); int hexEnd = hexRange.getEnd(); if (hexBegin == 0 && hexEnd <= 0) { return new IndexRange(0, 0); } boolean gotStart = false, gotEnd = false; String[] lines = hex.split("\n"); StringBuilder text = new StringBuilder(); String lineText; for (String lineHex : lines) { lineText = new String(ByteTools.hexFormatToBytes(lineHex), charset); lineText = StringTools.replaceLineBreak(lineText); if (!gotStart && hexBegin >= hIndex && hexBegin <= (hIndex + lineHex.length())) { cBegin = cindex + lineIndex(lineText, charset, hexBegin - hIndex); gotStart = true; } if (hexEnd >= hIndex && hexEnd <= (hIndex + lineHex.length())) { cEnd = cindex + lineIndex(lineText, charset, hexEnd - hIndex) + 1; gotEnd = true; break; } hIndex += lineHex.length() + 1; cindex += lineText.length() + 1; } if (!gotStart) { cBegin = text.length() - 1; } if (!gotEnd) { cEnd = text.length(); } if (cBegin > cEnd) { cEnd = cBegin; } return new IndexRange(cBegin, cEnd); } public static int indexOf(String hexString, String hexSubString, int initFrom) { if (hexString == null || hexSubString == null || hexString.length() < hexSubString.length()) { return -1; } int from = initFrom, pos = 0; while (pos >= 0) { pos = hexString.indexOf(hexSubString, from); if (pos % 2 == 0) { return pos; } from = pos + 1; } return -1; } public static String formatHex(String hexString, Line_Break lineBreak, int lineBreakWidth, String lineBreakValue) { String text = hexString; if (lineBreak == Line_Break.Width && lineBreakWidth > 0) { int step = 3 * lineBreakWidth; StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i += step) { if (i + step < text.length()) { sb.append(text.substring(i, i + step - 1)).append("\n"); } else { sb.append(text.substring(i, text.length() - 1)); } } text = sb.toString(); } else if (lineBreakValue != null) { if (text.endsWith(lineBreakValue)) { text = text.replaceAll(lineBreakValue, lineBreakValue.trim() + "\n"); text = text.substring(0, text.length() - 1); } else { text = text.replaceAll(lineBreakValue, lineBreakValue.trim() + "\n"); } } return text; } public static long checkBytesValue(String string) { try { String strV = string.trim().toLowerCase(); long unit = 1; if (strV.endsWith("b")) { unit = 1; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("k")) { unit = 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("m")) { unit = 1024 * 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("g")) { unit = 1024 * 1024 * 1024L; strV = strV.substring(0, strV.length() - 1); } double v = Double.parseDouble(strV.trim()); if (v >= 0) { return Math.round(v * unit); } else { return -1; } } catch (Exception e) { return -1; } } public static byte[] deflate(Object object) { return deflate(toBytes(object)); } public static byte[] deflate(byte[] bytes) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (DeflaterOutputStream out = new DeflaterOutputStream(a)) { out.write(bytes); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static byte[] inflate(Object object) { return inflate(toBytes(object)); } public static byte[] inflate(byte[] bytes) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (InflaterOutputStream out = new InflaterOutputStream(a)) { out.write(bytes); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static byte[] toBytes(Object object) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(a)) { out.writeObject(object); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static Object toObject(byte[] bytes) { try { ByteArrayInputStream a = new ByteArrayInputStream(bytes); try (ObjectInputStream in = new ObjectInputStream(a)) { return in.readObject(); } } catch (Exception e) { return null; } } public static byte[] imageToBytes(FxTask task, BufferedImage image, String format) { return BufferedImageTools.bytes(task, image, format); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileSplitTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileSplitTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileSplitTools { public static List<File> splitFileByFilesNumber(FxTask currentTask, File file, String filename, long filesNumber) { try { if (file == null || filesNumber <= 0) { return null; } long bytesNumber = file.length() / filesNumber; List<File> splittedFiles = new ArrayList<>(); try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; int digit = (filesNumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen; int fileIndex = 1; int startIndex = 0; int endIndex = 0; while ((fileIndex < filesNumber) && (bufLen = inputStream.read(buf)) > 0) { if (currentTask == null || !currentTask.isWorking()) { return null; } endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } if (currentTask == null || !currentTask.isWorking()) { return null; } buf = new byte[(int) (file.length() - endIndex)]; bufLen = inputStream.read(buf); if (bufLen > 0) { endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { outputStream.write(buf); } splittedFiles.add(new File(newFilename)); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static List<File> splitFileByStartEndList(FxTask currentTask, File file, String filename, List<Long> startEndList) { try { if (file == null || startEndList == null || startEndList.isEmpty() || startEndList.size() % 2 > 0) { return null; } List<File> splittedFiles = new ArrayList<>(); for (int i = 0; i < startEndList.size(); i += 2) { if (currentTask == null || !currentTask.isWorking()) { return null; } File f = cutFile(file, filename, startEndList.get(i), startEndList.get(i + 1)); if (f != null) { splittedFiles.add(f); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static List<File> splitFileByBytesNumber(FxTask currentTask, File file, String filename, long bytesNumber) { try { if (file == null || bytesNumber <= 0) { return null; } List<File> splittedFiles = new ArrayList<>(); try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; long fnumber = file.length() / bytesNumber; if (file.length() % bytesNumber > 0) { fnumber++; } int digit = (fnumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen; int fileIndex = 1; int startIndex = 0; int endIndex = 0; while ((bufLen = inputStream.read(buf)) > 0) { if (currentTask == null || !currentTask.isWorking()) { return null; } endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } // 1-based start, that is: from (start - 1) to ( end - 1) actually public static File cutFile(File file, String filename, long startIndex, long endIndex) { try { if (file == null || startIndex < 1 || startIndex > endIndex) { return null; } File tempFile = FileTmpTools.getTempFile(); String newFilename = filename + "-cut-b" + startIndex + "-b" + endIndex; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { if (startIndex > 1) { inputStream.skip(startIndex - 1); } int cutLength = (int) (endIndex - startIndex + 1); byte[] buf = new byte[cutLength]; int bufLen; bufLen = inputStream.read(buf); if (bufLen <= 0) { return null; } try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) { if (cutLength > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); newFilename = filename + "-cut-b" + startIndex + "-b" + bufLen; } outputStream.write(buf); } } File actualFile = new File(newFilename); if (FileTools.override(tempFile, actualFile)) { return actualFile; } else { return null; } } catch (Exception e) { MyBoxLog.debug(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/IconTools.java
released/MyBox/src/main/java/mara/mybox/tools/IconTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.value.AppVariables.MyboxDataPath; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class IconTools { public static File readIcon(FxTask task, String address, boolean download) { try { if (address == null) { return null; } URL url = UrlTools.url(address); if (url == null) { return null; } String host = url.getHost(); if (host == null || host.isBlank()) { return null; } File file = FxFileTools.getInternalFile("/icons/" + host + ".png", "icons", host + ".png"); if (file == null || !file.exists()) { file = FxFileTools.getInternalFile("/icons/" + host + ".ico", "icons", host + ".ico"); if ((file == null || !file.exists()) && download) { file = new File(MyboxDataPath + File.separator + "icons" + File.separator + host + ".ico"); file = readIcon(task, address, file); } } return file != null && file.exists() ? file : null; } catch (Exception e) { // MyBoxLog.debug(e); return null; } } // https://www.cnblogs.com/luguo3000/p/3767380.html public static File readIcon(FxTask task, String address, File targetFile) { File actualTarget = readHostIcon(task, address, targetFile); if (actualTarget == null) { actualTarget = readHtmlIcon(task, address, targetFile); } if (actualTarget != null) { BufferedImage image = ImageFileReaders.readImage(task, actualTarget); if (image != null) { String name = actualTarget.getAbsolutePath(); if (name.endsWith(".ico")) { ImageAttributes attributes = new ImageAttributes() .setImageFormat("png").setColorSpaceName("sRGB") .setAlpha(ImageAttributes.Alpha.Keep).setQuality(100); File png = new File(name.substring(0, name.lastIndexOf(".")) + ".png"); ImageConvertTools.convertColorSpace(task, actualTarget, attributes, png); if (png.exists()) { FileDeleteTools.delete(actualTarget); actualTarget = png; } } return actualTarget; } else { FileDeleteTools.delete(actualTarget); } } return null; } public static File readHostIcon(FxTask task, String address, File targetFile) { try { if (address == null || targetFile == null) { return null; } URL url = UrlTools.url(address); if (url == null) { return null; } String iconUrl = "https://" + url.getHost() + "/favicon.ico"; File actualTarget = downloadIcon(task, iconUrl, targetFile); // if (actualTarget == null) { // iconUrl = "http://" + url.getHost() + "/favicon.ico"; // actualTarget = downloadIcon(task, iconUrl, targetFile); // } return actualTarget; } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static File readHtmlIcon(FxTask task, String address, File targetFile) { try { if (address == null) { return null; } String iconUrl = htmlIconAddress(task, address); if (iconUrl == null) { return null; } return downloadIcon(task, iconUrl, targetFile); } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static File downloadIcon(FxTask task, String address, File targetFile) { try { if (address == null || targetFile == null) { return null; } File iconFile = HtmlReadTools.download(task, address, 1000, 1000); if (iconFile == null || !iconFile.exists()) { return null; } String suffix = FileNameTools.ext(address); File actualTarget = targetFile; if (suffix != null && !suffix.isBlank()) { actualTarget = new File(FileNameTools.replaceExt(targetFile.getAbsolutePath(), suffix)); } if (FileTools.override(iconFile, actualTarget, true) && actualTarget.exists()) { return actualTarget; } else { return null; } } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static String htmlIconAddress(FxTask task, String address) { try { if (address == null) { return null; } String html = HtmlReadTools.url2html(task, address); Pattern[] ICON_PATTERNS = new Pattern[]{ Pattern.compile("rel=[\"']shortcut icon[\"'][^\r\n>]+?((?<=href=[\"']).+?(?=[\"']))"), Pattern.compile("((?<=href=[\"']).+?(?=[\"']))[^\r\n<]+?rel=[\"']shortcut icon[\"']")}; for (Pattern iconPattern : ICON_PATTERNS) { Matcher matcher = iconPattern.matcher(html); if (matcher.find()) { String iconUrl = matcher.group(1); if (iconUrl.contains("http")) { return iconUrl; } if (iconUrl.charAt(0) == '/') { URL url = UrlTools.url(address); if (url == null) { return null; } iconUrl = url.getProtocol() + "://" + url.getHost() + iconUrl; } else { iconUrl = address + "/" + iconUrl; } return iconUrl; } } return null; } catch (Exception e) { // MyBoxLog.debug(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileSortTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileSortTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javafx.stage.FileChooser; import mara.mybox.data.FileInformation; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileSortTools { public static enum FileSortMode { ModifyTimeDesc, ModifyTimeAsc, CreateTimeDesc, CreateTimeAsc, SizeDesc, SizeAsc, NameDesc, NameAsc, FormatDesc, FormatAsc } public static FileSortMode sortMode(String mode) { for (FileSortMode v : FileSortMode.values()) { if (Languages.matchIgnoreCase(v.name(), mode)) { return v; } } return null; } public static boolean hasNextFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return false; } int index = files.indexOf(file); return index >= 0 && index < files.size() - 1; } catch (Exception e) { return false; } } public static boolean hasPreviousFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return false; } int index = files.indexOf(file); return index > 0 && index <= files.size() - 1; } catch (Exception e) { return false; } } public static File nextFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return null; } int index = files.indexOf(file); if (index < 0 || index >= files.size() - 1) { return null; } return files.get(index + 1); } catch (Exception e) { return null; } } public static File previousFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return null; } int index = files.indexOf(file); if (index <= 0 || index > files.size() - 1) { return null; } return files.get(index - 1); } catch (Exception e) { return null; } } public static List<File> siblingFiles(File file, int fileType, FileSortMode sortMode) { if (file == null) { return null; } List<File> files = validFiles(file.getParentFile(), fileType); sortFiles(files, sortMode); return files; } public static List<File> validFiles(File path, int fileType) { try { if (path == null || !path.isDirectory()) { return null; } File[] pathFiles = path.listFiles(); if (pathFiles == null || pathFiles.length == 0) { return null; } List<FileChooser.ExtensionFilter> filter = VisitHistoryTools.getExtensionFilter(fileType); List<File> files = new ArrayList<>(); for (File file : pathFiles) { if (file.isFile() && FileFilters.accept(filter, file)) { files.add(file); } } return files; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static void sortFiles(List<File> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } try { switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.lastModified() - f1.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.lastModified() - f2.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case NameDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f2, f1); } }); break; case NameAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f1, f2); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t2 - t1; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t1 - t2; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.length() - f1.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.length() - f2.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case FormatDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.ext(f2.getName()).compareTo(FileNameTools.ext(f1.getName())); } }); break; case FormatAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.ext(f1.getName()).compareTo(FileNameTools.ext(f2.getName())); } }); break; } } catch (Exception e) { MyBoxLog.debug(e); } } public static void sortFileInformations(List<FileInformation> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().lastModified() - f1.getFile().lastModified()); } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().lastModified() - f2.getFile().lastModified()); } }); break; case NameDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.compareName(f2.getFile(), f1.getFile()); } }); break; case NameAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.compareName(f1.getFile(), f2.getFile()); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t2 - t1); } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t1 - t2); } }); break; case SizeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().length() - f1.getFile().length()); } }); break; case SizeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().length() - f2.getFile().length()); } }); break; case FormatDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.ext(f2.getFile().getName()).compareTo(FileNameTools.ext(f1.getFile().getName())); } }); break; case FormatAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.ext(f1.getFile().getName()).compareTo(FileNameTools.ext(f2.getFile().getName())); } }); break; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/CertificateTools.java
released/MyBox/src/main/java/mara/mybox/tools/CertificateTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class CertificateTools { public static String keystore() { String jvm_cacerts = System.getProperty("java.home") + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts"; try { File file = myboxCacerts(); if (!file.exists()) { file.getParentFile().mkdirs(); FileCopyTools.copyFile(new File(jvm_cacerts), file); } if (file.exists()) { return file.getAbsolutePath(); } else { return jvm_cacerts; } } catch (Exception e) { return jvm_cacerts; } } public static String keystorePassword() { return "changeit"; } public static void resetKeystore() { FileDeleteTools.delete(myboxCacerts()); keystore(); } public static File myboxCacerts() { return new File(AppVariables.MyboxDataPath + File.separator + "security" + File.separator + "cacerts_mybox"); } public static void SSLServerSocketInfo() { try { SSLServerSocket sslServerSocket; SSLServerSocketFactory ssl = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); sslServerSocket = (SSLServerSocket) ssl.createServerSocket(); String[] cipherSuites = sslServerSocket.getSupportedCipherSuites(); for (String suite : cipherSuites) { MyBoxLog.debug(suite); } String[] protocols = sslServerSocket.getSupportedProtocols(); for (String protocol : protocols) { MyBoxLog.debug(protocol); } } catch (Exception e) { } } public static boolean isHostCertificateInstalled(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); return true; } catch (Exception e) { return false; } } catch (Exception e) { return false; } } public static String installCertificates(String keyStoreFile, String passwd, Certificate[] certs, String[] names) { try { if (keyStoreFile == null || certs == null || names == null || certs.length != names.length) { return Languages.message("InvalidData"); } char[] passphrase = passwd.toCharArray(); File cacerts = new File(keyStoreFile); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(cacerts))) { keyStore.load(in, passphrase); } catch (Exception e) { return e.toString(); } File tmpFile = FileTmpTools.getTempFile(); try (final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile))) { for (int i = 0; i < certs.length; i++) { String alias = names[i].replaceAll(" ", "-"); keyStore.setCertificateEntry(alias, certs[i]); } keyStore.store(out, passphrase); } catch (Exception e) { return e.toString(); } FileTools.override(tmpFile, cacerts); return null; } catch (Exception e) { return e.toString(); } } public static String installCertificates(Certificate[] certs, String[] names) { return installCertificates(CertificateTools.keystore(), CertificateTools.keystorePassword(), certs, names); } public static Certificate[] getCertificatesByFile(File certFile) { try (final FileInputStream inStream = new FileInputStream(certFile)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> data = cf.generateCertificates(inStream); if (data == null || data.isEmpty()) { return null; } Certificate[] certs = new Certificate[data.size()]; int index = 0; for (Certificate cert : data) { certs[index++] = cert; } return certs; } catch (Exception e) { return null; } } public static String installCertificateByFile(String keyStoreFile, String passwd, File certFile, String alias, boolean wholeChain) { try { if (wholeChain) { Certificate[] certs = getCertificatesByFile(certFile); if (certs == null || certs.length == 0) { return Languages.message("InvalidData"); } String[] names = new String[certs.length]; names[0] = alias; for (int i = 1; i < certs.length; i++) { names[i] = alias + "-chain-" + i; } return installCertificates(keyStoreFile, passwd, certs, names); } else { Certificate cert = getCertificateByFile(certFile); if (cert == null) { return Languages.message("InvalidData"); } return installCertificate(keyStoreFile, passwd, cert, alias); } } catch (Exception e) { return e.toString(); } } public static String installCertificateByFile(File certFile, String alias, boolean wholeChain) { return installCertificateByFile(CertificateTools.keystore(), CertificateTools.keystorePassword(), certFile, alias, wholeChain); } public static String installHostsCertificates(List<String> hosts, boolean wholeChain) { if (hosts == null || hosts.isEmpty()) { return Languages.message("InvalidData"); } try { List<Certificate> certsList = new ArrayList<>(); List<String> namesList = new ArrayList<>(); for (String host : hosts) { if (wholeChain) { Certificate[] hostCerts = getCertificatesByHost(host); if (hostCerts == null) { continue; } for (int i = 0; i < hostCerts.length; i++) { certsList.add(hostCerts[i]); namesList.add(host + (i == 0 ? "" : " chain " + i)); } } else { Certificate hostCert = getCertificateByHost(host); if (hostCert == null) { continue; } certsList.add(hostCert); namesList.add(host); } } if (certsList.isEmpty()) { return Languages.message("InvalidData"); } String keyStoreFile = CertificateTools.keystore(); String passwd = CertificateTools.keystorePassword(); Certificate[] certs = new Certificate[certsList.size()]; String[] names = new String[certsList.size()]; for (int i = 0; i < namesList.size(); i++) { certs[i] = certsList.get(i); names[i] = namesList.get(i); } return installCertificates(keyStoreFile, passwd, certs, names); } catch (Exception e) { return e.toString(); } } // https://github.com/escline/InstallCert/blob/master/InstallCert.java public static String installCertificateByHost(String keyStoreFile, String passwd, String host, String alias, boolean wholeChain) { try { if (wholeChain) { Certificate[] certs = getCertificatesByHost(host); if (certs == null || certs.length == 0) { return Languages.message("InvalidData"); } String[] names = new String[certs.length]; names[0] = alias; for (int i = 1; i < certs.length; i++) { names[i] = alias + "-chain-" + i; } return installCertificates(keyStoreFile, passwd, certs, names); } else { Certificate cert = getCertificateByHost(host); if (cert == null) { return Languages.message("InvalidData"); } return installCertificate(keyStoreFile, passwd, cert, alias); } } catch (Exception e) { return e.toString(); } } public static String installCertificateByHost(String host, String alias, boolean wholeChain) { try { return installCertificateByHost(CertificateTools.keystore(), CertificateTools.keystorePassword(), host, alias, wholeChain); } catch (Exception e) { MyBoxLog.console(e.toString()); return e.toString(); } } public static String installCertificateByHost(String host, boolean wholeChain) { try { return installCertificateByHost(host, host, wholeChain); } catch (Exception e) { MyBoxLog.console(e.toString()); return e.toString(); } } public static String uninstallCertificate(String keyStoreFile, String passwd, List<String> aliases) throws Exception { try { char[] passphrase = passwd.toCharArray(); File cacerts = new File(keyStoreFile); KeyStore keyStore; try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(cacerts))) { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(in, passphrase); } catch (Exception e) { return e.toString(); } File tmpFile = FileTmpTools.getTempFile(); try (final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile))) { for (String alias : aliases) { keyStore.deleteEntry(alias); } keyStore.store(out, passphrase); } catch (Exception e) { return e.toString(); } FileTools.override(tmpFile, cacerts); return null; } catch (Exception e) { return e.toString(); } } public static Certificate getCertificateByHost(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); } catch (Exception e) { } return socket.getSession().getPeerCertificates()[0]; } catch (Exception e) { return null; } } public static Certificate[] getCertificatesByHost(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); } catch (Exception e) { } return socket.getSession().getPeerCertificates(); } catch (Exception e) { return null; } } public static Certificate getCertificateByFile(File certFile) { try (final FileInputStream inStream = new FileInputStream(certFile)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return cf.generateCertificate(inStream); } catch (Exception e) { return null; } } public static String installCertificate(String keyStoreFile, String passwd, Certificate cert, String name) { if (cert == null || name == null) { return Languages.message("InvalidData"); } Certificate[] certs = {cert}; String[] names = {name}; return installCertificates(keyStoreFile, passwd, certs, names); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/JsonTools.java
released/MyBox/src/main/java/mara/mybox/tools/JsonTools.java
package mara.mybox.tools; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javafx.scene.control.IndexRange; import mara.mybox.data.FindReplaceString; import static mara.mybox.data.FindReplaceString.create; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-3-26 * @License Apache License Version 2.0 */ public class JsonTools { public static LinkedHashMap<String, String> jsonValues(FxTask currentTask, String data, List<String> keys) { try { LinkedHashMap<String, String> values = new LinkedHashMap<>(); String subdata = data; FindReplaceString endFind = create() .setOperation(FindReplaceString.Operation.FindNext) .setFindString("[\\},]").setAnchor(0) .setIsRegex(true).setCaseInsensitive(true).setMultiline(true); for (String key : keys) { if (currentTask != null && !currentTask.isWorking()) { return null; } Map<String, Object> value = jsonValue(currentTask, subdata, key, endFind); if (currentTask != null && !currentTask.isWorking()) { return null; } if (value == null) { continue; } values.put(key, (String) value.get("value")); int start = (int) value.get("end") + 1; if (start >= subdata.length() - 1) { break; } subdata = subdata.substring(start); } return values; } catch (Exception e) { return null; } } public static Map<String, Object> jsonValue(FxTask currentTask, String json, String key, FindReplaceString endFind) { try { String flag = "\"" + key + "\":"; int startPos = json.indexOf(flag); if (startPos < 0) { return null; } String data = json.substring(startPos + flag.length()); endFind.setInputString(data).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } IndexRange end = endFind.getStringRange(); if (end == null) { return null; } int endPos = end.getStart(); Map<String, Object> map = new HashMap<>(); String value = data.substring(0, endPos); if (value.startsWith("\"")) { value = value.substring(1); } if (value.endsWith("\"")) { value = value.substring(0, value.length() - 1); } map.put("value", value); map.put("start", startPos); map.put("end", endPos); return map; } catch (Exception e) { return null; } } public static String encode(String value) { try { return new ObjectMapper().writeValueAsString(value); } catch (Exception e) { return value; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/ShortTools.java
released/MyBox/src/main/java/mara/mybox/tools/ShortTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-10-4 * @License Apache License Version 2.0 */ public class ShortTools { public static boolean invalidShort(Short value) { return value == null || value == AppValues.InvalidShort; } // invalid values are always in the end public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Short.parseShort(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Short.parseShort(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } if (Float.isNaN(f1)) { if (Float.isNaN(f2)) { return 0; } else { return 1; } } else { if (Float.isNaN(f2)) { return -1; } else { float diff = f1 - f2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } public static short random(short max) { Random r = new Random(); return (short) r.nextInt(max); } public static String format(short v, String format, int scale) { if (invalidShort(v)) { return null; } return NumberTools.format(v, format, scale); } public static short[] sortArray(short[] numbers) { List<Short> list = new ArrayList<>(); for (short i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Short>() { @Override public int compare(Short p1, Short p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); short[] sorted = new short[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/StringTools.java
released/MyBox/src/main/java/mara/mybox/tools/StringTools.java
package mara.mybox.tools; import java.math.BigDecimal; import java.nio.charset.Charset; import java.text.Collator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @License Apache License Version 2.0 */ public class StringTools { public static String start(String string, int maxLen) { if (string == null) { return string; } return string.length() > maxLen ? string.substring(0, maxLen) + "..." : string; } public static String end(String string, int maxLen) { if (string == null) { return string; } int len = string.length(); return len > maxLen ? "..." + string.substring(len - maxLen, len) : string; } public static String abbreviate(String string, int maxLen) { if (string == null) { return string; } return start(replaceLineBreak(string, " ").strip(), maxLen); } // https://github.com/Mararsh/MyBox/issues/1266 // Error popped when menu name includes "_". Not sure whether this is a bug of javafx public static String menuSuffix(String name) { if (name == null) { return null; } return end(name.replaceAll("_|\r\n|\r|\n", " ").strip(), AppVariables.menuMaxLen); } public static String menuPrefix(String name) { if (name == null) { return null; } return start(name.replaceAll("_|\r\n|\r|\n", " ").strip(), AppVariables.menuMaxLen); } public static String replaceLineBreak(String string) { return replaceLineBreak(string, " "); } public static String replaceHtmlLineBreak(String string) { return replaceLineBreak(string, "</BR>"); } public static String replaceLineBreak(String string, String replaceAs) { if (string == null) { return string; } if (replaceAs == null) { replaceAs = ""; } return string.replaceAll("\r\n|\n|\r", replaceAs); } public static String trimBlanks(String string) { if (string == null) { return string; } return string.replaceAll("\\s+", " ").trim(); } public static String[] separatedBySpace(String string) { String[] ss = new String[2]; String s = string.trim(); int pos1 = s.indexOf(' '); if (pos1 < 0) { ss[0] = s; ss[1] = ""; return ss; } ss[0] = s.substring(0, pos1); ss[1] = s.substring(pos1).trim(); return ss; } public static String[] splitBySpace(String string) { if (string == null) { return null; } return string.trim().split("\\s+"); } public static String[] splitByComma(String string) { String[] splitted = string.split(","); return splitted; } public static String fillLeftZero(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v = "0" + v; } return v; } public static String fillRightZero(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v += "0"; } return v; } public static String fillRightBlank(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v += " "; } return v; } public static String fillLeftBlank(Number value, int digit) { String v = new BigDecimal(value + "").toString() + ""; for (int i = v.length(); i < digit; ++i) { v = " " + v; } return v; } public static String fillRightBlank(String value, int digit) { String v = value; for (int i = v.length(); i < digit; ++i) { v += " "; } return v; } public static int numberPrefix(String string) { if (string == null) { return AppValues.InvalidInteger; } try { String s = string.trim(); int sign = 1; if (s.startsWith("-")) { if (s.length() == 1) { return AppValues.InvalidInteger; } sign = -1; s = s.substring(1); } String prefix = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isNumber(c)) { prefix += c; } else { break; } } if (prefix.isBlank()) { return AppValues.InvalidInteger; } return Integer.parseInt(prefix) * sign; } catch (Exception e) { return AppValues.InvalidInteger; } } public static boolean isNumber(char c) { return c >= '0' && c <= '9'; } public static int compareWithNumber(String string1, String string2) { try { if (string1 == null) { return string2 == null ? 0 : -1; } if (string2 == null) { return 1; } int len = Math.min(string1.length(), string2.length()); String number1 = "", number2 = ""; boolean numberEnd1 = false, numberEnd2 = false; for (int i = 0; i < len; i++) { char c1 = string1.charAt(i); char c2 = string2.charAt(i); if (c1 == c2) { continue; } if (isNumber(c1)) { if (!numberEnd1) { number1 += c1; } } else { numberEnd1 = true; } if (isNumber(c2)) { if (!numberEnd2) { number2 += c2; } } else { numberEnd2 = true; } if (numberEnd1 && numberEnd2) { break; } } if (!number1.isBlank() && !number2.isBlank()) { return compareNumber(number1, number2); } return compare(string1, string2); } catch (Exception e) { MyBoxLog.debug(e); return 1; } } public static int compareNumber(String number1, String number2) { if (number1 == null) { return number2 == null ? 0 : -1; } if (number2 == null) { return 1; } int len1 = number1.length(); int len2 = number2.length(); if (len1 > len2) { return 1; } else if (len1 < len2) { return -1; } for (int i = 0; i < len1; i++) { char c1 = number1.charAt(i); char c2 = number2.charAt(i); if (c1 > c2) { return 1; } else if (c1 < c2) { return -1; } } return 0; } public static int compare(String s1, String s2) { if (s1 == null) { return s2 == null ? 0 : -1; } if (s2 == null) { return 1; } Collator compare = Collator.getInstance(Locale.getDefault()); return compare.compare(s1, s2); } public static void sort(List<String> strings, Locale locale) { if (strings == null || strings.isEmpty()) { return; } Collections.sort(strings, new Comparator<String>() { private final Collator compare = Collator.getInstance(locale); @Override public int compare(String f1, String f2) { return compare.compare(f1, f2); } }); } public static void sort(List<String> strings) { sort(strings, Locale.getDefault()); } public static void sortDesc(List<String> strings, Locale locale) { if (strings == null || strings.isEmpty()) { return; } Collections.sort(strings, new Comparator<String>() { private final Collator compare = Collator.getInstance(Locale.getDefault()); @Override public int compare(String f1, String f2) { return compare.compare(f2, f1); } }); } public static void sortDesc(List<String> strings) { sortDesc(strings, Locale.getDefault()); } public static String format(long data) { try { DecimalFormat df = new DecimalFormat("#,###"); return df.format(data); } catch (Exception e) { return message("Invalid"); } } public static String format(double data) { return format(Math.round(data)); } public static String leftAlgin(String name, String value, int nameLength) { return String.format("%-" + nameLength + "s:" + value, name); } public static boolean match(String string, String find, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | Pattern.MULTILINE; Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.matches(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean match(String string, String find, boolean isRegex, boolean dotAll, boolean multiline, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (isRegex ? 0x00 : Pattern.LITERAL) | (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | (dotAll ? Pattern.DOTALL : 0x00) | (multiline ? Pattern.MULTILINE : 0x00); Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.matches(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean include(String string, String find, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | Pattern.MULTILINE; Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.find(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } // https://blog.csdn.net/zx1749623383/article/details/79540748 public static String decodeUnicode(String unicode) { if (unicode == null || "".equals(unicode)) { return null; } StringBuilder sb = new StringBuilder(); int i, pos = 0; while ((i = unicode.indexOf("\\u", pos)) > 0) { sb.append(unicode.substring(pos, i)); if (i + 5 < unicode.length()) { pos = i + 6; sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16)); } else { break; } } return sb.toString(); } public static String encodeUnicode(String string) { if (string == null || "".equals(string)) { return null; } StringBuilder unicode = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); unicode.append("\\u").append(Integer.toHexString(c)); } return unicode.toString(); } public static String convertCharset(String source, String sourceCharset, String targetCharset) { try { if (sourceCharset.equals(targetCharset)) { return source; } return new String(source.getBytes(sourceCharset), targetCharset); } catch (Exception e) { return source; } } public static String convertCharset(String source, Charset sourceCharset, Charset targetCharset) { try { if (sourceCharset.equals(targetCharset)) { return source; } return new String(source.getBytes(sourceCharset), targetCharset); } catch (Exception e) { return source; } } public static String discardBlankLines(String text) { if (text == null) { return null; } String[] lines = text.split("\n"); StringBuilder s = new StringBuilder(); for (String line : lines) { if (line.isBlank()) { continue; } s.append(line).append("\n"); } return s.toString(); } public static String[][] transpose(String[][] matrix) { try { if (matrix == null) { return null; } int rowsNumber = matrix.length, columnsNumber = matrix[0].length; String[][] result = new String[columnsNumber][rowsNumber]; for (int row = 0; row < rowsNumber; ++row) { for (int col = 0; col < columnsNumber; ++col) { result[col][row] = matrix[row][col]; } } return result; } catch (Exception e) { return null; } } public static String[] matrix2Array(String[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; String[] a = new String[w * h]; for (int j = 0; j < h; ++j) { System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static String[][] array2Matrix(String[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } String[][] m = new String[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static String[][] toString(double[][] dMatrix) { try { if (dMatrix == null) { return null; } int rsize = dMatrix.length, csize = dMatrix[0].length; String[][] sMatrix = new String[rsize][csize]; for (int i = 0; i < rsize; i++) { for (int j = 0; j < csize; j++) { sMatrix[i][j] = dMatrix[i][j] + ""; } } return sMatrix; } catch (Exception e) { return null; } } public static List<String> toList(String value, String separater) { try { if (value == null || value.isBlank()) { return null; } String[] a = value.split(separater, 0); if (a == null || a.length == 0) { return null; } List<String> values = new ArrayList<>(); values.addAll(Arrays.asList(a)); if (values.isEmpty()) { return null; } else { return values; } } catch (Exception e) { return null; } } public static String toString(List<String> values, String separater) { try { if (values == null || values.isEmpty()) { return null; } String s = null; for (String v : values) { if (v != null && !v.isBlank()) { if (s == null) { s = v; } else { s += separater + v; } } } if (s == null || s.isBlank()) { return null; } else { return s; } } catch (Exception e) { return null; } } public static boolean isTrue(String string) { if (string == null || string.isBlank()) { return false; } return "1".equals(string) || Languages.matchIgnoreCase("true", string) || Languages.matchIgnoreCase("yes", string); } public static boolean isFalse(String string) { if (string == null || string.isBlank()) { return false; } return "0".equals(string) || Languages.matchIgnoreCase("false", string) || Languages.matchIgnoreCase("no", string); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FileNameTools.java
released/MyBox/src/main/java/mara/mybox/tools/FileNameTools.java
package mara.mybox.tools; import java.io.File; import java.text.Collator; import java.util.Locale; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileNameTools { public static String filter(String name) { if (name == null || name.isBlank()) { return name; } Pattern pattern = Pattern.compile(AppValues.FileNameSpecialChars); return pattern.matcher(name).replaceAll("_"); } public static String name(String filename) { return name(filename, File.separator); } public static String name(String filename, String separator) { if (filename == null) { return null; } String fname = filename; int pos = fname.lastIndexOf(separator); if (pos >= 0) { fname = (pos < fname.length() - 1) ? fname.substring(pos + 1) : ""; } return fname; } public static String append(String filename, String append) { if (filename == null) { return null; } if (append == null || append.isEmpty()) { return filename; } String path; String name; int pos = filename.lastIndexOf(File.separator); if (pos >= 0) { path = filename.substring(0, pos + 1); name = pos < filename.length() - 1 ? filename.substring(pos + 1) : ""; } else { path = ""; name = filename; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos) + append + name.substring(pos); } else { return path + name + append; } } // not include path, only filename's prefix public static String prefix(String filename) { if (filename == null) { return null; } String name = name(filename); int pos = name.lastIndexOf('.'); if (pos >= 0) { name = name.substring(0, pos); } return name; } public static String ext(String filename) { return ext(filename, File.separator); } // not include "." public static String ext(String filename, String separator) { if (filename == null || filename.endsWith(separator)) { return null; } String name = name(filename, separator); int pos = name.lastIndexOf('.'); return (pos >= 0 && pos < name.length() - 1) ? name.substring(pos + 1) : ""; } public static String replaceExt(String file, String newSuffix) { if (file == null || newSuffix == null) { return null; } String path; String name; int pos = file.lastIndexOf(File.separator); if (pos >= 0) { path = file.substring(0, pos + 1); name = pos < file.length() - 1 ? file.substring(pos + 1) : ""; } else { path = ""; name = file; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos + 1) + newSuffix; } else { return path + name + "." + newSuffix; } } // include "." public static String suffix(String filename) { if (filename == null || filename.endsWith(File.separator)) { return null; } String name = name(filename); int pos = name.lastIndexOf('.'); return (pos >= 0 && pos < name.length() - 1) ? name.substring(pos) : ""; } public static int compareName(File f1, File f2) { try { if (f1 == null) { return f2 == null ? 0 : -1; } if (f2 == null) { return 1; } if (f1.isFile() && f2.isFile() && f1.getParent().equals(f2.getParent())) { return StringTools.compareWithNumber(f1.getName(), f2.getName()); } else { Collator compare = Collator.getInstance(Locale.getDefault()); return compare.compare(f1.getAbsolutePath(), f2.getAbsolutePath()); } } catch (Exception e) { MyBoxLog.debug(e); return 1; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/FFmpegTools.java
released/MyBox/src/main/java/mara/mybox/tools/FFmpegTools.java
package mara.mybox.tools; /** * @Author Mara * @CreateDate 2018-7-12 * @Description * @License Apache License Version 2.0 */ public class FFmpegTools { // public static FFprobeResult FFprobleFrames(File FFprobleExcuatble, File mediaFile, // String streams, String intervals) throws Exception { // FFprobe probe = FFprobe.atPath(FFprobleExcuatble.toPath().getParent()) // .setShowFrames(true) // .setInput(Paths.get(mediaFile.getAbsolutePath())); // if (streams != null && !streams.trim().isEmpty()) { // probe.setSelectStreams(streams.trim()); // } // if (intervals != null && !intervals.trim().isEmpty()) { // probe.setReadIntervals(intervals.trim()); // } // return probe.execute(); // } // // public static FFprobeResult FFproblePackets(File FFprobleExcuatble, File mediaFile, // String streams, String intervals) throws Exception { // FFprobe probe = FFprobe.atPath(FFprobleExcuatble.toPath().getParent()) // .setShowPackets(true) // .setInput(Paths.get(mediaFile.getAbsolutePath())); // if (streams != null && !streams.trim().isEmpty()) { // probe.setSelectStreams(streams.trim()); // } // if (intervals != null && !intervals.trim().isEmpty()) { // probe.setReadIntervals(intervals.trim()); // } // return probe.execute(); // } // // public static void convert(File FFmpegExcuatble, File sourceFile, File targetFile) { // // The most reliable way to get video duration // // ffprobe for some formats can't detect duration // final AtomicLong duration = new AtomicLong(); // final FFmpegResult nullResult = FFmpeg.atPath(FFmpegExcuatble.toPath()) // .addInput(UrlInput.fromPath(sourceFile.toPath())) // .addOutput(new NullOutput()) // .setOverwriteOutput(true) // .setProgressListener(new ProgressListener() { // @Override // public void onProgress(FFmpegProgress progress) { // duration.set(progress.getTimeMillis()); // } // }) // .execute(); // // ProgressListener listener = new ProgressListener() { // private final long lastReportTs = System.currentTimeMillis(); // // @Override // public void onProgress(FFmpegProgress progress) { // long now = System.currentTimeMillis(); // if (lastReportTs + 1000 < now) { // long percent = 100 * progress.getTimeMillis() / duration.get(); // MyBoxLog.debug("Progress: " + percent + "%"); // } // } // }; // // FFmpegResult result = FFmpeg.atPath(FFmpegExcuatble.toPath()) // .addInput(UrlInput.fromPath(sourceFile.toPath())) // .addOutput(UrlOutput.toPath(targetFile.toPath())) // .setProgressListener(listener) // .setOverwriteOutput(true) // .execute(); // } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/TextTools.java
released/MyBox/src/main/java/mara/mybox/tools/TextTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javafx.scene.control.IndexRange; import mara.mybox.data.FileEditInformation; import mara.mybox.data.FileEditInformation.Line_Break; import mara.mybox.data.TextEditInformation; import static mara.mybox.data2d.DataFileText.CommentsMarker; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; import thridparty.EncodingDetect; /** * @Author Mara * @CreateDate 2018-12-10 13:06:33 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class TextTools { public final static String BlankName = "Blank"; public final static String Blank4Name = "Blank4"; public final static String Blank8Name = "Blank8"; public final static String BlanksName = "Blanks"; public final static String TabName = "Tab"; public static List<Charset> getCharsets() { List<Charset> sets = new ArrayList<>(); sets.addAll(Arrays.asList(Charset.forName("UTF-8"), Charset.forName("GBK"), Charset.forName("GB2312"), Charset.forName("GB18030"), Charset.forName("BIG5"), Charset.forName("ASCII"), Charset.forName("ISO-8859-1"), Charset.forName("UTF-16"), Charset.forName("UTF-16BE"), Charset.forName("UTF-16LE"), Charset.forName("UTF-32"), Charset.forName("UTF-32BE"), Charset.forName("UTF-32LE") )); if (sets.contains(Charset.defaultCharset())) { sets.remove(Charset.defaultCharset()); } sets.add(0, Charset.defaultCharset()); Map<String, Charset> all = Charset.availableCharsets(); for (Charset set : all.values()) { if (Charset.isSupported(set.name()) && !sets.contains(set)) { sets.add(set); } } return sets; } public static List<String> getCharsetNames() { try { List<Charset> sets = getCharsets(); List<String> setNames = new ArrayList<>(); for (Charset set : sets) { setNames.add(set.name()); } return setNames; } catch (Exception e) { return null; } } public static String checkCharsetByBom(byte[] bytes) { if (bytes.length < 2) { return null; } if ((bytes[0] == (byte) 0xFE) && (bytes[1] == (byte) 0xFF)) { return "UTF-16BE"; } if ((bytes[0] == (byte) 0xFF) && (bytes[1] == (byte) 0xFE)) { return "UTF-16LE"; } if (bytes.length < 3) { return null; } if ((bytes[0] == (byte) 0xEF) && (bytes[1] == (byte) 0xBB) && (bytes[2] == (byte) 0xBF)) { return "UTF-8"; } if (bytes.length < 4) { return null; } if ((bytes[0] == (byte) 0x00) && (bytes[1] == (byte) 0x00) && (bytes[2] == (byte) 0xFE) && (bytes[3] == (byte) 0xFF)) { return "UTF-32BE"; } if ((bytes[0] == (byte) 0xFF) && (bytes[1] == (byte) 0xFE) && (bytes[2] == (byte) 0x00) && (bytes[3] == (byte) 0x00)) { return "UTF-32LE"; } return null; } public static boolean checkCharset(FileEditInformation info) { try { if (info == null || info.getFile() == null) { return false; } String setName; info.setWithBom(false); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(info.getFile()))) { byte[] header = new byte[4]; int bufLen; if ((bufLen = inputStream.read(header, 0, 4)) > 0) { header = ByteTools.subBytes(header, 0, bufLen); setName = checkCharsetByBom(header); if (setName != null) { info.setCharset(Charset.forName(setName)); info.setWithBom(true); return true; } } } setName = EncodingDetect.detect(info.getFile()); info.setCharset(Charset.forName(setName)); return true; } catch (Exception e) { // MyBoxLog.debug(e); return false; } } public static int bomSize(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return 2; case "UTF-16LE": return 2; case "UTF-8": return 3; case "UTF-32": case "UTF-32BE": return 4; case "UTF-32LE": return 4; } return 0; } public static String bomHex(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return "FE FF"; case "UTF-16LE": return "FF FE"; case "UTF-8": return "EF BB BF"; case "UTF-32": case "UTF-32BE": return "00 00 FE FF"; case "UTF-32LE": return "FF FE 00 00"; } return null; } public static byte[] bomBytes(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return new byte[]{(byte) 0xFE, (byte) 0xFF}; case "UTF-16LE": return new byte[]{(byte) 0xFF, (byte) 0xFE}; case "UTF-8": return new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; case "UTF-32": case "UTF-32BE": return new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}; case "UTF-32LE": return new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; } return null; } public static String readText(FxTask task, File file) { return readText(task, new TextEditInformation(file)); } public static String readText(FxTask task, FileEditInformation info) { try { if (info == null || info.getFile() == null) { return null; } StringBuilder text = new StringBuilder(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(info.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, info.getCharset())) { if (info.isWithBom()) { inputStream.skip(bomSize(info.getCharset().name())); } char[] buf = new char[512]; int len; while ((len = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return text.toString(); } text.append(buf, 0, len); } } return text.toString(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean writeText(FileEditInformation info, String text) { try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(info.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, info.getCharset())) { if (info.isWithBom()) { byte[] bytes = bomBytes(info.getCharset().name()); outputStream.write(bytes); } writer.write(text); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean convertCharset(FxTask task, FileEditInformation source, FileEditInformation target) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return false; } try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, source.getCharset()); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (source.isWithBom()) { inputStream.skip(bomSize(source.getCharset().name())); } if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } char[] buf = new char[512]; int count; while ((count = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return false; } String text = new String(buf, 0, count); writer.write(text); } } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean convertLineBreak(FxTask task, FileEditInformation source, FileEditInformation target) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return false; } String sourceLineBreak = TextTools.lineBreakValue(source.getLineBreak()); String taregtLineBreak = TextTools.lineBreakValue(target.getLineBreak()); if (sourceLineBreak == null || taregtLineBreak == null) { return false; } if (source.getLineBreak() == target.getLineBreak()) { return FileCopyTools.copyFile(source.getFile(), target.getFile(), true, true); } try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, source.getCharset()); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { char[] buf = new char[4096]; int count; while ((count = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return false; } String text = new String(buf, 0, count); text = text.replaceAll(sourceLineBreak, taregtLineBreak); writer.write(text); } } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static long checkCharsNumber(String string) { try { String strV = string.trim().toLowerCase(); long unit = 1; if (strV.endsWith("k")) { unit = 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("m")) { unit = 1024 * 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("g")) { unit = 1024 * 1024 * 1024L; strV = strV.substring(0, strV.length() - 1); } double v = Double.parseDouble(strV.trim()); if (v >= 0) { return Math.round(v * unit); } else { return -1; } } catch (Exception e) { return -1; } } public static List<File> convert(FxTask task, FileEditInformation source, FileEditInformation target, int maxLines) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return null; } String sourceLineBreak = TextTools.lineBreakValue(source.getLineBreak()); String taregtLineBreak = TextTools.lineBreakValue(target.getLineBreak()); if (sourceLineBreak == null || taregtLineBreak == null) { return null; } List<File> files = new ArrayList<>(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, source.getCharset()))) { if (source.isWithBom()) { inputStream.skip(bomSize(source.getCharset().name())); } if (maxLines > 0) { int fileIndex = 0; while (true) { if (task != null && !task.isWorking()) { return null; } int linesNumber = 0; String line = null; File file = new File(FileNameTools.append(target.getFile().getAbsolutePath(), "-" + (++fileIndex))); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } while ((line = bufferedReader.readLine()) != null) { if (task != null && !task.isWorking()) { return null; } if (linesNumber++ > 0) { writer.write(taregtLineBreak + line); } else { writer.write(line); } if (linesNumber >= maxLines) { break; } } } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } if (file.exists() && file.length() > 0) { files.add(file); } if (line == null) { break; } } } else { File file = target.getFile(); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } String line; if ((line = bufferedReader.readLine()) != null) { writer.write(line); } while ((line = bufferedReader.readLine()) != null) { if (task != null && !task.isWorking()) { return null; } writer.write(taregtLineBreak + line); } } catch (Exception e) { MyBoxLog.debug(e); return null; } if (file.exists() && file.length() > 0) { files.add(file); } } } catch (Exception e) { MyBoxLog.debug(e); return null; } return files; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static IndexRange hexIndex(FxTask task, String text, Charset charset, String lineBreakValue, IndexRange textRange) { int hIndex = 0; int hBegin = 0; int hEnd = 0; int cBegin = textRange.getStart(); int cEnd = textRange.getEnd(); if (cBegin == 0 && cEnd == 0) { return new IndexRange(0, 0); } int lbLen = lineBreakValue.getBytes(charset).length * 3 + 1; for (int i = 0; i < text.length(); ++i) { if (cBegin == i) { hBegin = hIndex; } if (cEnd == i) { hEnd = hIndex; } char c = text.charAt(i); if (c == '\n') { hIndex += lbLen; } else { hIndex += String.valueOf(c).getBytes(charset).length * 3; } } if (cBegin == text.length()) { hBegin = hIndex; } if (cEnd == text.length()) { hEnd = hIndex; } return new IndexRange(hBegin, hEnd); } public static Line_Break checkLineBreak(FxTask task, File file) { if (file == null) { return Line_Break.LF; } try (InputStreamReader reader = new InputStreamReader( new BufferedInputStream(new FileInputStream(file)))) { int c; boolean cr = false; while ((c = reader.read()) > 0) { if (task != null && !task.isWorking()) { return Line_Break.LF; } if ((char) c == '\r') { cr = true; } else if ((char) c == '\n') { if (cr) { return Line_Break.CRLF; } else { return Line_Break.LF; } } else if (c != 0 && cr) { return Line_Break.CR; } } } catch (Exception e) { MyBoxLog.error(e); } return Line_Break.LF; } public static String lineBreakValue(Line_Break lb) { switch (lb) { case LF: return "\n"; case CRLF: return "\r\n"; case CR: return "\r"; default: return "\n"; } } public static byte[] lineBreakBytes(Line_Break lb, Charset charset) { switch (lb) { case LF: return "\n".getBytes(charset); case CRLF: return "\r\n".getBytes(charset); case CR: return "\r".getBytes(charset); default: return "\n".getBytes(charset); } } public static String lineBreakHex(Line_Break lb, Charset charset) { return ByteTools.bytesToHex(lineBreakBytes(lb, charset)); } public static String lineBreakHexFormat(Line_Break lb, Charset charset) { return ByteTools.bytesToHexFormat(lineBreakBytes(lb, charset)); } public static String delimiterValue(String delimiterName) { if (delimiterName == null) { return ","; } String delimiter; switch (delimiterName) { case TabName: case "tab": delimiter = "\t"; break; case BlankName: case "blank": delimiter = " "; break; case Blank4Name: case "blank4": delimiter = " "; break; case Blank8Name: case "blank8": delimiter = " "; break; case BlanksName: case "blanks": delimiter = " "; break; default: delimiter = delimiterName; break; } return delimiter; } public static String delimiterMessage(String delimiterName) { if (delimiterName == null || delimiterName.isEmpty()) { return message("Unknown"); } String msg; switch (delimiterName) { case TabName: case "tab": case "\t": msg = message("Tab"); break; case BlankName: case "blank": case " ": msg = message("Blank"); break; case Blank4Name: case "blank4": case " ": msg = message("Blank4"); break; case Blank8Name: case "blank8": case " ": msg = message("Blank8"); break; case BlanksName: case "blanks": msg = message("BlankCharacters"); break; default: if (delimiterName.isBlank()) { msg = message("BlankCharacters"); } else { msg = delimiterName; } break; } return msg; } public static String arrayText(FxTask task, Object[][] data, String delimiterName, List<String> colsNames, List<String> rowsNames) { if (data == null || data.length == 0 || delimiterName == null) { return ""; } try { StringBuilder s = new StringBuilder(); String delimiter = delimiterValue(delimiterName); int rowsNumber = data.length; int colsNumber = data[0].length; int colEnd; if (colsNames != null && colsNames.size() >= colsNumber) { if (rowsNames != null && !rowsNames.isEmpty()) { s.append(delimiter); } colEnd = colsNumber - 1; for (int c = 0; c <= colEnd; c++) { if (task != null && !task.isWorking()) { return null; } s.append(colsNames.get(c)); if (c < colEnd) { s.append(delimiter); } } s.append("\n"); } Object v; int rowEnd = rowsNumber - 1; for (int i = 0; i <= rowEnd; i++) { if (task != null && !task.isWorking()) { return null; } if (rowsNames != null && !rowsNames.isEmpty()) { s.append(rowsNames.get(i)).append(delimiter); } colEnd = colsNumber - 1; for (int c = 0; c <= colEnd; c++) { if (task != null && !task.isWorking()) { return null; } v = data[i][c]; s.append(v == null ? "" : v); if (c < colEnd) { s.append(delimiter); } } if (i < rowEnd) { s.append("\n"); } } return s.toString(); } catch (Exception e) { MyBoxLog.console(e); return ""; } } public static String rowsText(FxTask task, List<List<String>> rows, String delimiterName) { return arrayText(task, toArray(task, rows), delimiterName, null, null); } public static String rowsText(FxTask task, List<List<String>> rows, String delimiterName, List<String> colsNames, List<String> rowsNames) { return arrayText(task, toArray(task, rows), delimiterName, colsNames, rowsNames); } public static boolean validLine(String line) { return line != null && !line.isBlank() && !line.startsWith(CommentsMarker); } public static List<String> parseLine(String line, String delimiterName) { try { if (!validLine(line) || delimiterName == null) { return null; } String[] values; switch (delimiterName) { case TabName: case "tab": case "\t": values = line.split("\t", -1); break; case BlankName: case "blank": case " ": values = line.split("\\s", -1); break; case Blank4Name: case "blank4": case " ": values = line.split("\\s{4}", -1); break; case Blank8Name: case "blank8": case " ": values = line.split("\\s{8}", -1); break; case BlanksName: case "blanks": values = line.split("\\s+", -1); break; case "|": values = line.split("\\|", -1); break; case "*": values = line.split("\\*", -1); break; case ".": values = line.split("\\.", -1); break; case "?": values = line.split("\\?", -1); break; case "\\": values = line.split("\\\\", -1); break; default: if (delimiterName.isBlank()) { values = line.split("\\s+", -1); } else { values = line.split(delimiterName, -1); } break; } if (values == null || values.length == 0) { return null; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(values)); return row; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } public static String[][] toArray(FxTask task, List<List<String>> rows) { try { if (rows == null || rows.isEmpty()) { return null; } int rowSize = rows.size(); int colSize = -1; for (List<String> row : rows) { int len = row.size(); if (len > colSize) { colSize = len; } } String[][] data = new String[rowSize][colSize]; for (int r = 0; r < rows.size(); r++) { List<String> row = rows.get(r); for (int c = 0; c < row.size(); c++) { data[r][c] = row.get(c); } } return data; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static List<List<String>> toList(FxTask task, String[][] array) { try { int rowsNumber = array.length; int colsNumber = array[0].length; List<List<String>> data = new ArrayList<>(); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(array[i][j]); } data.add(row); } return data; } catch (Exception e) { return null; } } public static String vertical(FxTask task, String text, boolean leftToRight) { try { if (text == null) { return null; } StringBuilder s = new StringBuilder(); String[] lines = text.split("\n", -1); int maxLen = 0; for (String line : lines) { int lineLen = line.length(); if (lineLen > maxLen) { maxLen = lineLen; } } int end = lines.length - 1; if (leftToRight) { for (int r = 0; r < maxLen; r++) { for (int i = 0; i <= end; i++) { String line = lines[i]; int lineLen = line.length(); if (lineLen > r) { s.append(line.charAt(r)); } else { s.append(" "); } } s.append("\n"); } } else { for (int r = 0; r < maxLen; r++) { for (int i = end; i >= 0; i--) { String line = lines[i]; int lineLen = line.length(); if (lineLen > r) { s.append(line.charAt(r)); } else { s.append(" "); } } s.append("\n"); } } return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return text; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/CompressTools.java
released/MyBox/src/main/java/mara/mybox/tools/CompressTools.java
/* * Apache License Version 2.0 */ package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import mara.mybox.controller.BaseTaskController; import mara.mybox.data.FileInformation.FileType; import mara.mybox.data.FileNode; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.lz4.BlockLZ4CompressorInputStream; import org.apache.commons.io.IOUtils; /** * * @author mara */ public class CompressTools { public static Map<String, String> CompressExtension; public static Map<String, String> ExtensionCompress; public static Map<String, String> ArchiveExtension; public static Map<String, String> ExtensionArchive; public static Map<String, String> compressExtension() { if (CompressExtension != null) { return CompressExtension; } CompressExtension = new HashMap<>(); CompressExtension.put("gz", "gz"); CompressExtension.put("bzip2", "bz2"); CompressExtension.put("pack200", "pack"); CompressExtension.put("xz", "xz"); CompressExtension.put("lzma", "lzma"); CompressExtension.put("snappy-framed", "sz"); CompressExtension.put("snappy-raw", "sz"); CompressExtension.put("z", "z"); CompressExtension.put("deflate", "deflate"); CompressExtension.put("deflate64", "deflate"); CompressExtension.put("lz4-block", "lz4"); CompressExtension.put("lz4-framed", "lz4"); // CompressExtension.put("zstandard", "zstd"); // CompressExtension.put("brotli", "br"); return CompressExtension; } public static Map<String, String> extensionCompress() { if (ExtensionCompress != null) { return ExtensionCompress; } Map<String, String> formats = compressExtension(); ExtensionCompress = new HashMap<>(); for (String format : formats.keySet()) { ExtensionCompress.put(formats.get(format), format); } return ExtensionCompress; } public static Map<String, String> archiveExtension() { if (ArchiveExtension != null) { return ArchiveExtension; } ArchiveExtension = new HashMap<>(); ArchiveExtension.put("zip", "zip"); ArchiveExtension.put("7z", "7z"); ArchiveExtension.put("jar", "jar"); ArchiveExtension.put("tar", "tar"); ArchiveExtension.put("ar", "ar"); ArchiveExtension.put("arj", "arj"); ArchiveExtension.put("cpio", "cpio"); ArchiveExtension.put("dump", "dump"); return ArchiveExtension; } public static Map<String, String> extensionArchive() { if (ExtensionArchive != null) { return ExtensionArchive; } Map<String, String> formats = archiveExtension(); ExtensionArchive = new HashMap<>(); for (String format : formats.keySet()) { ExtensionArchive.put(formats.get(format), format); } return ExtensionArchive; } public static String extensionByCompressor(String compressor) { if (compressor == null) { return null; } return compressExtension().get(compressor.toLowerCase()); } public static String compressorByExtension(String ext) { if (ext == null) { return null; } return extensionCompress().get(ext.toLowerCase()); } public static Set<String> compressFormats() { return compressExtension().keySet(); } public static Set<String> archiveFormats() { return archiveExtension().keySet(); } public static String decompressedName(BaseTaskController taskController, File srcFile) { return decompressedName(taskController, srcFile, detectCompressor(taskController, srcFile)); } public static String decompressedName(BaseTaskController taskController, File srcFile, String compressor) { try { if (srcFile == null || compressor == null) { return null; } String ext = CompressTools.extensionByCompressor(compressor); if (ext == null) { return null; } String fname = srcFile.getName(); if (fname.toLowerCase().endsWith("." + ext)) { return fname.substring(0, fname.length() - ext.length() - 1); } else { return fname + "." + ext; } } catch (Exception e) { taskController.updateLogs(e.toString()); return null; } } public static String detectCompressor(BaseTaskController taskController, File srcFile) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return detectCompressor(taskController, srcFile, compressorByExtension(ext)); } public static String detectCompressor(BaseTaskController taskController, File srcFile, String extIn) { if (srcFile == null || "none".equals(extIn)) { return null; } String compressor = null; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { CompressorStreamFactory cFactory = new CompressorStreamFactory(); if (ext != null && cFactory.getInputStreamCompressorNames().contains(ext)) { try (CompressorInputStream in = cFactory.createCompressorInputStream(ext, fileIn)) { compressor = ext; } catch (Exception e) { compressor = detectCompressor(taskController, fileIn, ext); } } else { compressor = detectCompressor(taskController, fileIn, ext); } } catch (Exception e) { taskController.updateLogs(e.toString()); } return compressor; } public static String detectCompressor(BaseTaskController taskController, BufferedInputStream fileIn, String extIn) { String compressor = null; try { compressor = CompressorStreamFactory.detect(fileIn); } catch (Exception ex) { if ("lz4".equals(extIn)) { try (CompressorInputStream in = new BlockLZ4CompressorInputStream(fileIn)) { compressor = "lz4-block"; } catch (Exception e) { taskController.updateLogs(message("NotCompressFormat")); } } else { taskController.updateLogs(message("NotCompressFormat")); } } return compressor; } public static Map<String, Object> decompress(BaseTaskController taskController, File srcFile, File targetFile) { String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return CompressTools.decompress(taskController, srcFile, CompressTools.compressorByExtension(ext), targetFile); } public static Map<String, Object> decompress(BaseTaskController taskController, File srcFile, String extIn, File targetFile) { Map<String, Object> decompress = null; try { File decompressedFile = null; String compressor = null; boolean detect = false; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { CompressorStreamFactory cFactory = new CompressorStreamFactory(); if (ext != null && cFactory.getInputStreamCompressorNames().contains(ext)) { try (CompressorInputStream in = cFactory.createCompressorInputStream(ext, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = ext; detect = false; } } catch (Exception e) { // taskController.updateLogs(e.toString()); try { String defectValue = CompressorStreamFactory.detect(fileIn); try (CompressorInputStream in = cFactory.createCompressorInputStream(defectValue, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = defectValue; detect = true; } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } } else { try { String defectValue = CompressorStreamFactory.detect(fileIn); try (CompressorInputStream in = cFactory.createCompressorInputStream(defectValue, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = defectValue; detect = true; } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } } if (compressor != null && decompressedFile != null && decompressedFile.exists()) { decompress = new HashMap<>(); decompress.put("compressor", compressor); decompress.put("decompressedFile", decompressedFile); decompress.put("detect", detect); } else { taskController.updateLogs(message("NotCompressFormat")); } } catch (Exception e) { taskController.updateLogs(e.toString()); } return decompress; } public static File decompress(BaseTaskController taskController, CompressorInputStream compressorInputStream, File targetFile) { if (compressorInputStream == null) { return null; } File file = FileTmpTools.getTempFile(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { IOUtils.copy(compressorInputStream, out); } catch (Exception e) { taskController.updateLogs(e.toString()); return null; } if (targetFile == null) { return file; } else if (FileTools.override(file, targetFile)) { return targetFile; } else { return null; } } public static String detectArchiver(BaseTaskController taskController, File srcFile) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return detectArchiver(taskController, srcFile, ext); } public static String detectArchiver(BaseTaskController taskController, File srcFile, String extIn) { if (srcFile == null || "none".equals(extIn)) { return null; } String archiver = null; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { ArchiveStreamFactory aFactory = new ArchiveStreamFactory(); if (ext != null && aFactory.getInputStreamArchiveNames().contains(ext)) { try (ArchiveInputStream in = aFactory.createArchiveInputStream(ext, fileIn)) { archiver = ext; } catch (Exception e) { try { archiver = ArchiveStreamFactory.detect(fileIn); } catch (Exception ex) { taskController.updateLogs(ex.toString()); } } } else { try { archiver = ArchiveStreamFactory.detect(fileIn); } catch (Exception ex) { taskController.updateLogs(ex.toString()); } } } catch (Exception e) { taskController.updateLogs(e.toString()); } return archiver; } public static Map<String, Object> readEntries(BaseTaskController taskController, File srcFile, String encoding) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return readEntries(taskController, srcFile, ext, encoding); } public static Map<String, Object> readEntries(BaseTaskController taskController, File srcFile, String extIn, String encodingIn) { Map<String, Object> unarchive = new HashMap<>(); try { String encoding = (encodingIn != null) ? encodingIn : UserConfig.getString("FilesUnarchiveEncoding", Charset.defaultCharset().name()); if (srcFile == null || "none".equals(extIn) || encoding == null) { return null; } String ext = extIn; if (ArchiveStreamFactory.SEVEN_Z.equals(ext)) { return readEntries7z(taskController, srcFile, encoding); } else if (ArchiveStreamFactory.ZIP.equals(ext)) { return readEntriesZip(taskController, srcFile, encoding); } try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile));) { if (ext == null) { ext = ArchiveStreamFactory.detect(fileIn); } if (ext != null && !ArchiveStreamFactory.SEVEN_Z.equals(ext) && !ArchiveStreamFactory.ZIP.equals(ext)) { ArchiveStreamFactory aFactory = new ArchiveStreamFactory(); if (aFactory.getInputStreamArchiveNames().contains(ext)) { try (ArchiveInputStream in = aFactory.createArchiveInputStream(ext, fileIn, encoding)) { List<FileNode> entires = readEntries(taskController, in); if (entires != null && !entires.isEmpty()) { unarchive.put("archiver", ext); unarchive.put("entries", entires); } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } } } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } if (ext != null && unarchive.get("entries") == null) { if (ArchiveStreamFactory.SEVEN_Z.equals(ext)) { return readEntries7z(taskController, srcFile, encoding); } else if (ArchiveStreamFactory.ZIP.equals(ext)) { return readEntriesZip(taskController, srcFile, encoding); } } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } return unarchive; } public static List<FileNode> readEntries(BaseTaskController taskController, ArchiveInputStream archiveInputStream) { List<FileNode> entries = new ArrayList(); try { if (archiveInputStream == null) { return null; } ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { if (!archiveInputStream.canReadEntryData(entry)) { MyBoxLog.debug("Can not Read entry Data:" + entry.getName()); continue; } try { FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); entries.add(file); } catch (Exception e) { MyBoxLog.debug(e); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } return entries; } public static Map<String, Object> readEntriesZip(BaseTaskController taskController, File srcFile, String encoding) { Map<String, Object> unarchive = new HashMap<>(); try (ZipFile zipFile = ZipFile.builder().setFile(srcFile).setCharset(encoding).get()) { List<FileNode> fileEntries = new ArrayList(); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); fileEntries.add(file); } unarchive.put("archiver", ArchiveStreamFactory.ZIP); unarchive.put("entries", fileEntries); } catch (Exception e) { unarchive.put("error", e.toString()); } return unarchive; } public static Map<String, Object> readEntries7z(BaseTaskController taskController, File srcFile, String encoding) { Map<String, Object> unarchive = new HashMap<>(); try (SevenZFile sevenZFile = SevenZFile.builder().setFile(srcFile).get()) { SevenZArchiveEntry entry; List<FileNode> entries = new ArrayList(); while ((entry = sevenZFile.getNextEntry()) != null) { FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); entries.add(file); } unarchive.put("archiver", ArchiveStreamFactory.SEVEN_Z); unarchive.put("entries", entries); } catch (Exception e) { unarchive.put("error", e.toString()); } return unarchive; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/ScheduleTools.java
released/MyBox/src/main/java/mara/mybox/tools/ScheduleTools.java
package mara.mybox.tools; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** * @Author Mara * @CreateDate 2022-11-2 * @License Apache License Version 2.0 */ public class ScheduleTools { public final static ScheduledExecutorService service = Executors.newScheduledThreadPool(2); }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/UrlTools.java
released/MyBox/src/main/java/mara/mybox/tools/UrlTools.java
package mara.mybox.tools; import java.io.File; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class UrlTools { public static URL url(String address) { try { // some address may pop syntax error when run new URI(address).toURL() // So still use the deprecated api return new URL(address); } catch (Exception e) { return null; } } public static URL url(URL base, String address) { try { return new URL(base, address); } catch (Exception e) { return null; } } public static String checkURL(String value, Charset charset) { try { if (value == null || value.isBlank()) { return null; } String address = value; String addressS = address.toLowerCase(); if (addressS.startsWith("file:/") || addressS.startsWith("http://") || addressS.startsWith("https://")) { } else if (address.startsWith("//")) { address = "http:" + value; } else { File file = new File(address); if (file.exists()) { address = file.toURI().toString(); } else { address = "https://" + value; } } address = decodeURL(address, charset); return address; } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String decodeURL(String value, Charset charset) { try { if (value == null) { return null; } return URLDecoder.decode(value, charset); } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String decodeURL(File file, Charset charset) { try { if (file == null) { return null; } return decodeURL(file.toURI().toString(), charset); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String encodeURL(String value, Charset charset) { try { if (value == null) { return null; } return URLEncoder.encode(value, charset); } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String encodeURL(File file, Charset charset) { try { if (file == null) { return null; } return encodeURL(file.toURI().toString(), charset); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String fullAddress(String baseAddress, String address) { try { URL baseUrl = UrlTools.url(baseAddress); if (baseUrl == null) { return address; } URL url = fullUrl(baseUrl, address); return url.toString(); } catch (Exception e) { // MyBoxLog.debug(e); return address; } } public static URL fullUrl(URL baseURL, String address) { URL url = UrlTools.url(baseURL, address); if (url != null) { return url; } return UrlTools.url(address); } public static String filePrefix(URL url) { if (url == null) { return ""; } String file = file(url); if (file == null) { return ""; } int pos = file.lastIndexOf("."); file = pos < 0 ? file : file.substring(0, pos); return file; } public static URI uri(String address) { try { URI u; if (address.startsWith("file:")) { u = new URI(address); } else if (!address.startsWith("http")) { u = new URI("http://" + address); } else { u = new URI(address); } return u; } catch (Exception e) { // MyBoxLog.error(e.toString()); return null; } } public static String path(URL url) { if (url == null) { return null; } String urlPath = url.getPath(); int pos = urlPath.lastIndexOf("/"); String path = pos < 0 ? "" : urlPath.substring(0, pos + 1); return path; } public static String fullPath(URL url) { if (url == null) { return null; } String fullPath = url.getProtocol() + "://" + url.getHost() + path(url); return fullPath; } public static String fullPath(String address) { try { URL url = UrlTools.url(address); if (url == null) { return address; } String path = fullPath(url); return path == null ? address : path; } catch (Exception e) { return address; } } public static String fileSuffix(URL url) { if (url == null) { return ""; } String name = file(url); if (name == null) { return ""; } int pos = name.lastIndexOf("."); name = pos < 0 ? "" : name.substring(pos); return name; } public static String file(URL url) { if (url == null) { return null; } try { String urlPath = url.getPath(); int pos = urlPath.lastIndexOf("/"); if (pos >= 0) { return pos < urlPath.length() - 1 ? urlPath.substring(pos + 1) : null; } else { return urlPath; } } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/tools/JShellTools.java
released/MyBox/src/main/java/mara/mybox/tools/JShellTools.java
package mara.mybox.tools; import java.util.List; import jdk.jshell.JShell; import jdk.jshell.SnippetEvent; import jdk.jshell.SourceCodeAnalysis; import mara.mybox.data.JShellSnippet; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-6-1 * @License Apache License Version 2.0 */ public class JShellTools { public static String runSnippet(JShell jShell, String orignalSource, String source) { try { if (source == null || source.isBlank()) { return source; } String snippet = source.trim(); List<SnippetEvent> events = jShell.eval(snippet); String results = ""; for (int i = 0; i < events.size(); i++) { SnippetEvent e = events.get(i); JShellSnippet jShellSnippet = new JShellSnippet(jShell, e.snippet()); if (i > 0) { results += "\n"; } results += "id: " + jShellSnippet.getId() + "\n"; if (jShellSnippet.getStatus() != null) { results += message("Status") + ": " + jShellSnippet.getStatus() + "\n"; } if (jShellSnippet.getType() != null) { results += message("Type") + ": " + jShellSnippet.getType() + "\n"; } if (jShellSnippet.getName() != null) { results += message("Name") + ": " + jShellSnippet.getName() + "\n"; } if (jShellSnippet.getValue() != null) { results += message("Value") + ": " + jShellSnippet.getValue() + "\n"; } } return results; } catch (Exception e) { return e.toString(); } } public static String runSnippet(JShell jShell, String source) { return runSnippet(jShell, source, source); } public static boolean runScript(JShell jShell, String script) { try { if (script == null || script.isBlank()) { return false; } String leftCodes = script; while (leftCodes != null && !leftCodes.isBlank()) { SourceCodeAnalysis.CompletionInfo info = jShell.sourceCodeAnalysis().analyzeCompletion(leftCodes); String snippet = info.source().trim(); jShell.eval(snippet); leftCodes = info.remaining(); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String expValue(JShell jShell, String exp) { try { return new JShellSnippet(jShell, jShell.eval(exp).get(0).snippet()).getValue(); } catch (Exception e) { MyBoxLog.error(e, exp); return null; } } public static String classPath(JShell jShell) { try { String paths = expValue(jShell, "System.getProperty(\"java.class.path\")"); if (paths.startsWith("\"") && paths.endsWith("\"")) { paths = paths.substring(1, paths.length() - 1); } return paths; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static JShell initWithClassPath() { try { JShell jShell = JShell.create(); jShell.addToClasspath(System.getProperty("java.class.path")); return jShell; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static JShell initJEXL() { try { JShell jShell = JShell.create(); jShell.addToClasspath(System.getProperty("java.class.path")); String initCodes = "import org.apache.commons.jexl3.JexlBuilder;\n" + "import org.apache.commons.jexl3.JexlEngine;\n" + "import org.apache.commons.jexl3.JexlScript;\n" + "import org.apache.commons.jexl3.MapContext;\n" + "JexlEngine jexlEngine = new JexlBuilder().cache(512).strict(true).silent(false).create();\n" + "MapContext jexlContext = new MapContext();" + "JexlScript jexlScript;"; runScript(jShell, initCodes); return jShell; } catch (Exception e) { MyBoxLog.error(e); return null; } } // public static void clearSnippets(JShell jShell) { // try { // jShell.snippets().dropWhile(predicate) // return new JShellSnippet(jShell, jShell.eval(exp).get(0).snippet()).getValue(); // } catch (Exception e) { // MyBoxLog.error(e, exp); // return null; // } // } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ColorBlendTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ColorBlendTools.java
package mara.mybox.image.tools; import java.awt.Color; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorBlendTools { // https://www.cnblogs.com/xiaonanxia/p/9448444.html public static Color blendColor(Color foreColor, float opacity, Color backColor, boolean keepAlpha) { int red = (int) (foreColor.getRed() * opacity + backColor.getRed() * (1.0f - opacity)); int green = (int) (foreColor.getGreen() * opacity + backColor.getGreen() * (1.0f - opacity)); int blue = (int) (foreColor.getBlue() * opacity + backColor.getBlue() * (1.0f - opacity)); int alpha = keepAlpha ? (int) (foreColor.getAlpha() * opacity + backColor.getAlpha() * (1.0f - opacity)) : 255; return new Color( Math.min(Math.max(red, 0), 255), Math.min(Math.max(green, 0), 255), Math.min(Math.max(blue, 0), 255), Math.min(Math.max(alpha, 0), 255)); } public static Color blendColor(Color color, int opocity, Color bgColor, boolean keepAlpha) { return blendColor(color, opocity / 255.0F, bgColor, keepAlpha); } public static Color blendColor(Color color, float opocity, Color bgColor) { return blendColor(color, opocity, bgColor, false); } public static int blendPixel(int forePixel, int backPixel, float opacity, boolean orderReversed, boolean ignoreTransparency) { if (ignoreTransparency && forePixel == 0) { return backPixel; } if (ignoreTransparency && backPixel == 0) { return forePixel; } Color foreColor, backColor; if (orderReversed) { foreColor = new Color(backPixel, true); backColor = new Color(forePixel, true); } else { foreColor = new Color(forePixel, true); backColor = new Color(backPixel, true); } Color newColor = blendColor(foreColor, opacity, backColor, true); return newColor.getRGB(); } public static int blendPixel(int forePixel, int backPixel, float opacity) { return blendPixel(forePixel, backPixel, opacity, false, false); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ColorMatchTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ColorMatchTools.java
package mara.mybox.image.tools; import java.awt.Color; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorMatchTools { // distanceSquare = Math.pow(distance, 2) public static boolean isColorMatchSquare2(Color color1, Color color2, int distanceSquare) { if (color1 == null || color2 == null) { return false; } if (color1.getRGB() == color2.getRGB()) { return true; } else if (distanceSquare == 0 || color1.getRGB() == 0 || color2.getRGB() == 0) { return false; } return calculateColorDistanceSquare2(color1, color2) <= distanceSquare; } // https://en.wikipedia.org/wiki/Color_difference public static int calculateColorDistanceSquare2(Color color1, Color color2) { if (color1 == null || color2 == null) { return Integer.MAX_VALUE; } int redDiff = color1.getRed() - color2.getRed(); int greenDiff = color1.getGreen() - color2.getGreen(); int blueDiff = color1.getBlue() - color2.getBlue(); return 2 * redDiff * redDiff + 4 * greenDiff * greenDiff + 3 * blueDiff * blueDiff; } // Generally not use this value. Use distance square instead. public static int calculateColorDistance2(Color color1, Color color2) { if (color1 == null || color2 == null) { return Integer.MAX_VALUE; } int v = calculateColorDistanceSquare2(color1, color2); return (int) Math.round(Math.sqrt(v)); } // distance: 0-255 }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ShapeTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ShapeTools.java
package mara.mybox.image.tools; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.image.BufferedImage; import java.util.List; import java.util.Random; import javafx.scene.shape.Line; import mara.mybox.data.DoublePoint; import mara.mybox.data.DoublePolylines; import mara.mybox.data.DoubleShape; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageMosaic; import mara.mybox.image.data.PixelsBlend; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ShapeTools { public static BasicStroke stroke(ShapeStyle style) { if (style == null) { return new BasicStroke(); } else { return new BasicStroke(style.getStrokeWidth(), style.getStrokeLineCapAwt(), style.getStrokeLineJoinAwt(), style.getStrokeLineLimit(), style.isIsStrokeDash() ? style.getStrokeDashAwt() : null, 0.0F); } } public static BufferedImage drawShape(FxTask task, BufferedImage srcImage, DoubleShape doubleShape, ShapeStyle style, PixelsBlend blender) { try { if (srcImage == null || doubleShape == null || doubleShape.isEmpty() || style == null || blender == null) { return srcImage; } float strokeWidth = style.getStrokeWidth(); boolean showStroke = strokeWidth > 0; boolean fill = style.isIsFillColor(); if (!fill && !showStroke) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; Color strokeColor = Color.WHITE; Color fillColor = Color.BLACK; Color backgroundColor = Color.RED; BufferedImage shapeImage = new BufferedImage(width, height, imageType); Graphics2D g = shapeImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setStroke(stroke(style)); g.setBackground(backgroundColor); Shape shape = doubleShape.getShape(); if (fill) { g.setColor(fillColor); g.fill(shape); } if (showStroke) { g.setColor(strokeColor); g.draw(shape); } g.dispose(); if (task != null && !task.isWorking()) { return null; } BufferedImage target = new BufferedImage(width, height, imageType); int strokePixel = strokeColor.getRGB(); int fillPixel = fillColor.getRGB(); int realStrokePixel = style.getStrokeColorAwt().getRGB(); int realFillPixel = style.getFillColorAwt().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int srcPixel = srcImage.getRGB(i, j); int shapePixel = shapeImage.getRGB(i, j); if (shapePixel == strokePixel) { target.setRGB(i, j, blender.blend(realStrokePixel, srcPixel)); } else if (shapePixel == fillPixel) { target.setRGB(i, j, blender.blend(realFillPixel, srcPixel)); } else { target.setRGB(i, j, srcPixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage drawErase(FxTask task, BufferedImage srcImage, DoublePolylines linesData, ShapeStyle style) { try { if (linesData == null || linesData.getLinesSize() == 0 || style == null) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage linesImage = new BufferedImage(width, height, imageType); Graphics2D linesg = linesImage.createGraphics(); if (AppVariables.ImageHints != null) { linesg.addRenderingHints(AppVariables.ImageHints); } linesg.setStroke(stroke(style)); linesg.setBackground(Color.WHITE); linesg.setColor(Color.BLACK); for (List<DoublePoint> line : linesData.getLines()) { if (task != null && !task.isWorking()) { return null; } Path2D.Double path = new Path2D.Double(); DoublePoint p = line.get(0); path.moveTo(p.getX(), p.getY()); for (int i = 1; i < line.size(); i++) { p = line.get(i); path.lineTo(p.getX(), p.getY()); } linesg.draw(path); } if (task != null && !task.isWorking()) { return null; } linesg.dispose(); BufferedImage target = new BufferedImage(width, height, imageType); int black = Color.BLACK.getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (linesImage.getRGB(i, j) == black) { target.setRGB(i, j, 0); } else { target.setRGB(i, j, srcImage.getRGB(i, j)); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static boolean inLine(Line line, int x, int y) { double d = (x - line.getStartX()) * (line.getStartY() - line.getEndY()) - ((line.getStartX() - line.getEndX()) * (y - line.getStartY())); return Math.abs(d) < 1.0E-4 && (x >= Math.min(line.getStartX(), line.getEndX()) && x <= Math.max(line.getStartX(), line.getEndX())) && (y >= Math.min(line.getStartY(), line.getEndY())) && (y <= Math.max(line.getStartY(), line.getEndY())); } public static int mosaic(BufferedImage source, int imageWidth, int imageHeight, int x, int y, ImageMosaic.MosaicType type, int intensity) { int newColor; if (type == ImageMosaic.MosaicType.Mosaic) { int mx = Math.max(0, Math.min(imageWidth - 1, x - x % intensity)); int my = Math.max(0, Math.min(imageHeight - 1, y - y % intensity)); newColor = source.getRGB(mx, my); } else { int fx = Math.max(0, Math.min(imageWidth - 1, x - new Random().nextInt(intensity))); int fy = Math.max(0, Math.min(imageHeight - 1, y - new Random().nextInt(intensity))); newColor = source.getRGB(fx, fy); } return newColor; } public static BufferedImage drawMosaic(FxTask task, BufferedImage source, DoublePolylines linesData, ImageMosaic.MosaicType mosaicType, int strokeWidth, int intensity) { try { if (linesData == null || mosaicType == null || linesData.getLinesSize() == 0 || strokeWidth < 1 || intensity < 1) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D gt = target.createGraphics(); if (AppVariables.ImageHints != null) { gt.addRenderingHints(AppVariables.ImageHints); } gt.drawImage(source, 0, 0, width, height, null); gt.dispose(); if (task != null && !task.isWorking()) { return null; } int pixel; int w = strokeWidth / 2; for (Line line : linesData.getLineList()) { if (task != null && !task.isWorking()) { return null; } int x1 = Math.min(width, Math.max(0, (int) line.getStartX())); int y1 = Math.min(height, Math.max(0, (int) line.getStartY())); int x2 = Math.min(width, Math.max(0, (int) line.getEndX())); int y2 = Math.min(height, Math.max(0, (int) line.getEndY())); Polygon polygon = new Polygon(); polygon.addPoint(x1 - w, y1); polygon.addPoint(x1, y1 - w); polygon.addPoint(x1 + w, y1); polygon.addPoint(x2 - w, y2); polygon.addPoint(x2, y2 + w); polygon.addPoint(x2 + w, y2); Rectangle rect = polygon.getBounds(); int bx = (int) rect.getX(); int by = (int) rect.getY(); int bw = (int) rect.getWidth(); int bh = (int) rect.getHeight(); for (int x = bx; x < bx + bw; x++) { if (task != null && !task.isWorking()) { return null; } for (int y = by; y < by + bh; y++) { if (task != null && !task.isWorking()) { return null; } if (polygon.contains(x, y)) { pixel = mosaic(source, width, height, x, y, mosaicType, intensity); target.setRGB(x, y, pixel); } } } } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ColorComponentTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ColorComponentTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.util.HashMap; import java.util.Map; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorComponentTools { public static enum ColorComponent { Gray, RedChannel, GreenChannel, BlueChannel, Hue, Saturation, Brightness, AlphaChannel } public static Map<ColorComponent, Color> ComponentColor; public static Color color(ColorComponent c) { if (ComponentColor == null) { ComponentColor = new HashMap<>(); ComponentColor.put(ColorComponent.RedChannel, Color.RED); ComponentColor.put(ColorComponent.GreenChannel, Color.GREEN); ComponentColor.put(ColorComponent.BlueChannel, Color.BLUE); ComponentColor.put(ColorComponent.Hue, Color.PINK); ComponentColor.put(ColorComponent.Brightness, Color.ORANGE); ComponentColor.put(ColorComponent.Saturation, Color.CYAN); ComponentColor.put(ColorComponent.AlphaChannel, Color.YELLOW); ComponentColor.put(ColorComponent.Gray, Color.GRAY); } if (c == null) { return null; } return ComponentColor.get(c); } public static Color color(ColorComponent component, int value) { switch (component) { case RedChannel: return new Color(value, 0, 0, 255); case GreenChannel: return new Color(0, value, 0, 255); case BlueChannel: return new Color(0, 0, value, 255); case AlphaChannel: Color aColor = ColorComponentTools.color(component); return new Color(aColor.getRed(), aColor.getGreen(), aColor.getBlue(), value); case Gray: return new Color(value, value, value, 255); case Hue: return ColorConvertTools.hsb2rgb(value / 360.0F, 1.0F, 1.0F); case Saturation: float h1 = ColorConvertTools.getHue(ColorComponentTools.color(component)); return ColorConvertTools.hsb2rgb(h1, value / 100.0F, 1.0F); case Brightness: float h2 = ColorConvertTools.getHue(ColorComponentTools.color(component)); return ColorConvertTools.hsb2rgb(h2, 1.0F, value / 100.0F); } return null; } public static float percentage(ColorComponent component, int value) { switch (component) { case RedChannel: case GreenChannel: case BlueChannel: case AlphaChannel: case Gray: return value / 255f; case Hue: return value / 360f; case Saturation: case Brightness: return value / 100f; } return 0; } public static Color color(String name, int index) { return color(ColorComponentTools.component(name), index); } public static Color componentColor(String name) { return color(component(name)); } public static ColorComponent component(String name) { for (ColorComponent c : ColorComponent.values()) { if (c.name().equals(name) || Languages.message(c.name()).equals(name)) { return c; } } return null; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/TransformTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/TransformTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class TransformTools { public static BufferedImage rotateImage(FxTask task, BufferedImage source, int inAngle, boolean cutMargins) { int angle = inAngle % 360; if (angle == 0) { return source; } if (angle < 0) { angle = 360 + angle; } double radians = Math.toRadians(angle); double cos = Math.abs(Math.cos(radians)); double sin = Math.abs(Math.sin(radians)); int width = source.getWidth(); int height = source.getHeight(); int newWidth = (int) (width * cos + height * sin) + 2; int newHeight = (int) (height * cos + width * sin) + 2; int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } Color bgColor = Colors.TRANSPARENT; g.setBackground(bgColor); g.translate((newWidth - width) / 2, (newHeight - height) / 2); if (task != null && !task.isWorking()) { return null; } g.rotate(radians, width / 2, height / 2); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, null, null); g.dispose(); if (cutMargins) { target = MarginTools.cutMarginsByColor(task, target, bgColor, true, true, true, true); } return target; } public static BufferedImage shearImage(FxTask task, BufferedImage source, float shearX, float shearY, boolean cutMargins) { try { int width = source.getWidth(); int height = source.getHeight(); int offsetX = (int) (height * Math.abs(shearX)) + 1; int newWidth = width + offsetX + 1; if (shearX >= 0) { offsetX = 0; } int offsetY = (int) (width * Math.abs(shearY)) + 1; int newHeight = height + offsetY + 1; if (shearY >= 0) { offsetY = 0; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } Color bgColor = Colors.TRANSPARENT; g.setBackground(bgColor); g.translate(offsetX, offsetY); g.shear(shearX, shearY); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, null, null); if (task != null && !task.isWorking()) { return null; } g.dispose(); if (cutMargins) { target = MarginTools.cutMarginsByColor(task, target, bgColor, true, true, true, true); } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage horizontalMirrorImage(FxTask task, BufferedImage source) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } int l = 0; int r = width - 1; while (l < r) { if (task != null && !task.isWorking()) { return null; } int pl = source.getRGB(l, j); int pr = source.getRGB(r, j); target.setRGB(l, j, pr); target.setRGB(r, j, pl); l++; r--; } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage verticalMirrorImage(FxTask task, BufferedImage source) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int t = 0; int b = height - 1; while (t < b) { if (task != null && !task.isWorking()) { return null; } int pt = source.getRGB(i, t); int pb = source.getRGB(i, b); target.setRGB(i, t, pb); target.setRGB(i, b, pt); t++; b--; } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ColorConvertTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ColorConvertTools.java
package mara.mybox.image.tools; import java.awt.Color; import mara.mybox.db.data.ColorData; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorConvertTools { /* rgba */ public static Color pixel2rgba(int pixel) { return new Color(pixel, true); } public static Color rgba2color(String rgba) { javafx.scene.paint.Color c = javafx.scene.paint.Color.web(rgba); return converColor(c); } public static int rgba2Pixel(int r, int g, int b, int a) { return color2Pixel(new Color(r, g, b, a)); } public static int color2Pixel(Color color) { if (color == null) { return 0; } return color.getRGB(); } public static int setAlpha(int pixel, int a) { Color c = new Color(pixel); return new Color(c.getRed(), c.getGreen(), c.getBlue(), a).getRGB(); } public static String color2css(Color color) { return "rgba(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + "," + color.getTransparency() + ")"; } /* rgb */ public static Color rgb(Color color) { return new Color(color.getRed(), color.getGreen(), color.getBlue()); } public static Color pixel2rgb(int pixel) { return new Color(pixel); } public static int rgb2Pixel(int r, int g, int b) { return rgba2Pixel(r, g, b, 255); } /* hsb */ public static float[] color2hsb(Color color) { if (color == null) { return null; } return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); } public static float[] pixel2hsb(int pixel) { Color rgb = pixel2rgba(pixel); return Color.RGBtoHSB(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), null); } public static Color hsb2rgb(float h, float s, float b) { return new Color(Color.HSBtoRGB(h, s, b)); } // 0.0-1.0 public static float getHue(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[0]; } // 0.0-1.0 public static float getBrightness(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[2]; } public static float getBrightness(int pixel) { Color color = new Color(pixel); float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[2]; } // 0.0-1.0 public static float getSaturation(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[1]; } /* grey */ public static Color color2gray(Color color) { if (color == null) { return null; } int gray = color2grayValue(color); return new Color(gray, gray, gray, color.getAlpha()); } public static int color2grayValue(Color color) { if (color == null) { return 0; } return rgb2grayValue(color.getRed(), color.getGreen(), color.getBlue()); } public static int rgba2grayPixel(int r, int g, int b, int a) { int gray = rgb2grayValue(r, g, b); return rgba2Pixel(gray, gray, gray, a); } // https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness // https://en.wikipedia.org/wiki/Grayscale // Simplest:I = ( R + G + B ) / 3 // PAL和NTSC(Video) Y'UV and Y'IQ primaries Rec.601 : Y ′ = 0.299 R ′ + 0.587 G ′ + 0.114 B ′ // HDTV(High Definiton TV) ITU-R primaries Rec.709: Y ′ = 0.2126 R ′ + 0.7152 G ′ + 0.0722 B ′ // JDK internal: javafx.scene.paint.Color.grayscale() = 0.21 * red + 0.71 * green + 0.07 * blue public static int rgb2grayValue(int r, int g, int b) { int gray = (2126 * r + 7152 * g + 722 * b) / 10000; return gray; } public static int pixel2GrayPixel(int pixel) { Color c = pixel2rgb(pixel); return rgba2grayPixel(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); } public static int pixel2grayValue(int pixel) { Color c = new Color(pixel); return rgb2grayValue(c.getRed(), c.getGreen(), c.getBlue()); } /* others */ public static javafx.scene.paint.Color converColor(Color color) { return new javafx.scene.paint.Color(color.getRed() / 255.0, color.getGreen() / 255.0, color.getBlue() / 255.0, color.getAlpha() / 255.0); } public static Color converColor(javafx.scene.paint.Color color) { return new Color((int) (color.getRed() * 255), (int) (color.getGreen() * 255), (int) (color.getBlue() * 255), (int) (color.getOpacity() * 255)); } // https://stackoverflow.com/questions/21899824/java-convert-a-greyscale-and-sepia-version-of-an-image-with-bufferedimage/21900125#21900125 public static Color pixel2Sepia(int pixel, int sepiaIntensity) { return pixel2Sepia(pixel2rgb(pixel), sepiaIntensity); } public static Color pixel2Sepia(Color color, int sepiaIntensity) { int sepiaDepth = 20; int gray = color2grayValue(color); int r = gray; int g = gray; int b = gray; r = Math.min(r + (sepiaDepth * 2), 255); g = Math.min(g + sepiaDepth, 255); b = Math.min(Math.max(b - sepiaIntensity, 0), 255); Color newColor = new Color(r, g, b, color.getAlpha()); return newColor; } public static String pixel2hex(int pixel) { Color c = new Color(pixel); return String.format("#%02X%02X%02X", c.getRed(), c.getGreen(), c.getBlue()); } public static float[] color2srgb(Color color) { if (color == null) { return null; } float[] srgb = new float[3]; srgb[0] = color.getRed() / 255.0F; srgb[1] = color.getGreen() / 255.0F; srgb[2] = color.getBlue() / 255.0F; return srgb; } public static Color alphaColor() { return converColor(UserConfig.alphaColor()); } public static Color thresholdingColor(Color inColor, int threshold, int smallValue, int bigValue) { int red; int green; int blue; if (inColor.getRed() < threshold) { red = smallValue; } else { red = bigValue; } if (inColor.getGreen() < threshold) { green = smallValue; } else { green = bigValue; } if (inColor.getBlue() < threshold) { blue = smallValue; } else { blue = bigValue; } Color newColor = new Color(red, green, blue, inColor.getAlpha()); return newColor; } public static Color scaleSaturate(Color color, float scale) { float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return Color.getHSBColor(hsb[0], hsb[1] * scale, hsb[2]); } // https://blog.csdn.net/weixin_44938037/article/details/90599711 public static Color ryb2rgb(float angle) { float hue = ryb2hue(angle); float brightness = ryb2brightness(angle); return Color.getHSBColor(hue / 360, 1, brightness / 100); } public static Color rybComplementary(ColorData data) { if (data == null) { return null; } javafx.scene.paint.Color originalColor = data.getColor(); if (originalColor == null) { return null; } float colorRyb = data.getRyb(); if (colorRyb < 0) { return null; } float complementaryRyb = colorRyb + 180; float complementaryHue = ryb2hue(complementaryRyb) / 360; float complementaryRybBrightness = ryb2brightness(complementaryRyb); float colorRybBrightness = ryb2brightness(colorRyb); float colorBrightness = (float) data.getColor().getBrightness(); float complementaryBrightness = Math.min(1f, complementaryRybBrightness * colorBrightness / colorRybBrightness); Color c = Color.getHSBColor(complementaryHue, (float) originalColor.getSaturation(), complementaryBrightness); return new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (originalColor.getOpacity() * 255)); } public static float ryb2hue(float angle) { float a = angle % 360; float hue; if (a < 30) { hue = 2 * a / 3; } else if (a < 90) { hue = a / 3 + 10; } else if (a < 120) { hue = 2 * a / 3 - 20; } else if (a < 180) { hue = a - 60; } else if (a < 210) { hue = 2 * a - 240; } else if (a < 270) { hue = a - 30; } else if (a < 300) { hue = 2 * a - 300; } else { hue = a; } return hue; } // b = maxB - (maxB -minB) * (a - minA)/(maxA - minA) // b = minB + (maxB -minB) * (a - minA) /(maxA - minA) public static float ryb2brightness(float angle) { float a = angle % 360; float b; if (a <= 13) { b = 100 - 10 * a / 13; } else if (a <= 60) { b = 90 + 10 * (a - 13) / 47; } else if (a <= 120) { b = 100; } else if (a <= 180) { b = 100 - 5 * (a - 120) / 6; } else if (a <= 240) { b = 50 + 5 * (a - 180) / 6; } else if (a <= 300) { b = 100 - 5 * (a - 240) / 6; } else { b = 50 + 5 * (a - 300) / 6; } return b; } public static float hue2ryb(double hue) { return hue2ryb((float) hue); } public static float hue2ryb(float hue) { float h = hue % 360; float a; if (h < 20) { a = 1.5f * h; } else if (h < 40) { a = 3 * h - 30; } else if (h < 60) { a = 1.5f * h + 30; } else if (h < 120) { a = h + 60; } else if (h < 180) { a = h / 2 + 120; } else if (h < 240) { a = h + 30; } else if (h < 300) { a = h / 2 + 150; } else { a = h; } return a; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ImageScopeTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ImageScopeTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Random; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.controller.BaseController; import mara.mybox.data.DoubleCircle; import mara.mybox.data.DoubleEllipse; import mara.mybox.data.DoublePolygon; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.DoubleShape; import mara.mybox.data.ImageItem; import mara.mybox.data.IntPoint; import mara.mybox.data.StringTable; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.fxml.image.ScopeTools; import mara.mybox.image.data.ImageScope; import mara.mybox.image.data.ImageScope.ShapeType; import static mara.mybox.image.data.ImageScope.ShapeType.Matting4; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.AppPaths; import mara.mybox.value.InternalImages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-8-1 16:22:41 * @License Apache License Version 2.0 */ public class ImageScopeTools { public static void cloneValues(ImageScope targetScope, ImageScope sourceScope) { try { targetScope.setBackground(sourceScope.getBackground()); targetScope.setName(sourceScope.getName()); targetScope.setShapeData(sourceScope.getShapeData()); targetScope.setColorData(sourceScope.getColorData()); targetScope.setOutlineName(sourceScope.getOutlineName()); List<IntPoint> npoints = new ArrayList<>(); if (sourceScope.getPoints() != null) { npoints.addAll(sourceScope.getPoints()); } targetScope.setPoints(npoints); targetScope.setRectangle(sourceScope.getRectangle() != null ? sourceScope.getRectangle().copy() : null); targetScope.setCircle(sourceScope.getCircle() != null ? sourceScope.getCircle().copy() : null); targetScope.setEllipse(sourceScope.getEllipse() != null ? sourceScope.getEllipse().copy() : null); targetScope.setPolygon(sourceScope.getPolygon() != null ? sourceScope.getPolygon().copy() : null); targetScope.setShapeExcluded(sourceScope.isShapeExcluded()); targetScope.setColors(sourceScope.getColors()); targetScope.setColorExcluded(sourceScope.isColorExcluded()); sourceScope.getColorMatch().copyTo(targetScope.getColorMatch()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); targetScope.setOutlineSource(sourceScope.getOutlineSource()); targetScope.setOutline(sourceScope.getOutline()); targetScope.setOutlineName(sourceScope.getOutlineName()); targetScope.setClip(sourceScope.getClip()); targetScope.setMaskColor(sourceScope.getMaskColor()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); } catch (Exception e) { // MyBoxLog.debug(e); } } public static ImageScope cloneAll(ImageScope sourceScope) { ImageScope targetScope = new ImageScope(); ImageScopeTools.cloneAll(targetScope, sourceScope); return targetScope; } public static void cloneAll(ImageScope targetScope, ImageScope sourceScope) { try { targetScope.setImage(sourceScope.getImage()); targetScope.setShapeType(sourceScope.getShapeType()); cloneValues(targetScope, sourceScope); } catch (Exception e) { } } public static boolean inShape(DoubleShape shape, boolean areaExcluded, int x, int y) { if (areaExcluded) { return !DoubleShape.contains(shape, x, y); } else { return DoubleShape.contains(shape, x, y); } } /* make scope from */ public static ImageScope fromDataNode(FxTask task, BaseController controller, DataNode node) { try { if (node == null) { return null; } ImageScope scope = new ImageScope(); scope.setName(node.getTitle()); scope.setShapeType(node.getStringValue("shape_type")); scope.setShapeData(node.getStringValue("shape_data")); scope.setShapeExcluded(node.getBooleanValue("shape_excluded")); scope.setColorAlgorithm(node.getStringValue("color_algorithm")); scope.setColorData(node.getStringValue("color_data")); scope.setColorThreshold(node.getDoubleValue("color_threshold")); scope.setColorWeights(node.getStringValue("color_weights")); scope.setColorExcluded(node.getBooleanValue("color_excluded")); scope.setBackground(node.getStringValue("background_file")); scope.setOutlineName(node.getStringValue("outline_file")); scope.decode(task); return scope; } catch (Exception e) { // MyBoxLog.error(e); return null; } } /* convert scope to */ public static DataNode toDataNode(DataNode inNode, ImageScope scope) { try { if (scope == null) { return null; } ShapeType type = scope.getShapeType(); if (type == null) { type = ShapeType.Whole; } DataNode node = inNode; if (node == null) { node = DataNode.create(); } node.setValue("shape_type", type.name()); node.setValue("shape_data", encodeShapeData(scope)); node.setValue("shape_excluded", scope.isShapeExcluded()); node.setValue("color_algorithm", scope.getColorAlgorithm().name()); node.setValue("color_data", encodeColorData(scope)); node.setValue("color_excluded", scope.isColorExcluded()); node.setValue("color_threshold", scope.getColorThreshold()); node.setValue("color_weights", scope.getColorWeights()); node.setValue("background_file", scope.getBackground()); node.setValue("outline_file", encodeOutline(null, scope)); return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } // scope should have been decoded public static String toHtml(FxTask task, ImageScope scope) { try { if (scope == null || scope.isWhole()) { return null; } String html = ""; StringTable htmlTable = new StringTable(); List<String> row; try { ImageItem item = new ImageItem(scope.getBackground()); Image image = item.readImage(); if (image == null) { image = new Image(InternalImages.exampleImageName()); } if (task != null && !task.isWorking()) { return null; } if (scope.getShapeType() == ShapeType.Outline) { makeOutline(task, scope, image, scope.getRectangle(), true); } image = ScopeTools.maskScope(task, image, scope, false, true); if (task != null && !task.isWorking()) { return null; } if (image != null) { File imgFile = FxImageTools.writeImage(task, image); if (imgFile != null) { html = "<P align=\"center\"><Img src='" + imgFile.toURI().toString() + "' width=500></P><BR>"; } } String v = scope.getName(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Name"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ShapeType"), message(scope.getShapeType().name()))); htmlTable.add(row); v = scope.getBackground(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Background"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } v = scope.getOutlineName(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Outline"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorMatchAlgorithm"), message(scope.getColorAlgorithm().name()))); htmlTable.add(row); v = scope.getShapeData(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Shape"), v)); htmlTable.add(row); } v = scope.getColorData(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Colors"), v)); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorMatchThreshold"), scope.getColorThreshold() + "")); htmlTable.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("ShapeExcluded"), scope.isShapeExcluded() ? message("Yes") : "")); htmlTable.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorExcluded"), scope.isColorExcluded() ? message("Yes") : "")); htmlTable.add(row); } catch (Exception e) { } return html + htmlTable.div(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoubleRectangle makeOutline(FxTask task, ImageScope scope, Image bgImage, DoubleRectangle reck, boolean keepRatio) { try { if (scope.getOutlineSource() == null) { if (scope.getOutlineName() != null) { Image image = new ImageItem(scope.getOutlineName()).readImage(); if (image != null) { scope.setOutlineSource(SwingFXUtils.fromFXImage(image, null)); } } } if (scope.getOutlineSource() == null) { return null; } BufferedImage[] outline = AlphaTools.outline(task, scope.getOutlineSource(), reck, (int) bgImage.getWidth(), (int) bgImage.getHeight(), keepRatio); if (outline == null || (task != null && !task.isWorking())) { return null; } DoubleRectangle outlineReck = DoubleRectangle.xywh( reck.getX(), reck.getY(), outline[0].getWidth(), outline[0].getHeight()); scope.setOutline(outline[1]); scope.setRectangle(outlineReck.copy()); return outlineReck; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* extract value from scope */ public static Image encodeBackground(FxTask task, String address) { try { String background = address; ImageItem item = new ImageItem(background); Image image = item.readImage(); if (image == null) { background = InternalImages.exampleImageName(); image = new Image(background); } return image; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean decodeColorData(ImageScope scope) { if (scope == null) { return false; } return decodeColorData(scope.getColorData(), scope); } public static boolean decodeColorData(String colorData, ImageScope scope) { if (colorData == null || scope == null) { return false; } try { List<Color> colors = new ArrayList<>(); if (!colorData.isBlank()) { String[] items = colorData.split(ImageScope.ValueSeparator); for (String item : items) { try { colors.add(new Color(Integer.parseInt(item), true)); } catch (Exception e) { MyBoxLog.error(e); } } } scope.setColors(colors); scope.setColorData(colorData); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String encodeColorData(ImageScope scope) { if (scope == null) { return ""; } String s = ""; try { List<Color> colors = scope.getColors(); if (colors != null) { for (Color color : colors) { s += color.getRGB() + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } scope.setColorData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static String encodeShapeData(ImageScope scope) { if (scope == null) { return ""; } String s = ""; try { switch (scope.getShapeType()) { case Matting4: case Matting8: { List<IntPoint> points = scope.getPoints(); if (points != null) { for (IntPoint p : points) { s += p.getX() + ImageScope.ValueSeparator + p.getY() + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } } break; case Rectangle: case Outline: DoubleRectangle rect = scope.getRectangle(); if (rect != null) { s = (int) rect.getX() + ImageScope.ValueSeparator + (int) rect.getY() + ImageScope.ValueSeparator + (int) rect.getMaxX() + ImageScope.ValueSeparator + (int) rect.getMaxY(); } break; case Circle: DoubleCircle circle = scope.getCircle(); if (circle != null) { s = (int) circle.getCenterX() + ImageScope.ValueSeparator + (int) circle.getCenterY() + ImageScope.ValueSeparator + (int) circle.getRadius(); } break; case Ellipse: DoubleEllipse ellipse = scope.getEllipse(); if (ellipse != null) { s = (int) ellipse.getX() + ImageScope.ValueSeparator + (int) ellipse.getY() + ImageScope.ValueSeparator + (int) ellipse.getMaxX() + ImageScope.ValueSeparator + (int) ellipse.getMaxY(); } break; case Polygon: DoublePolygon polygon = scope.getPolygon(); if (polygon != null) { for (Double d : polygon.getData()) { s += Math.round(d) + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } break; } scope.setShapeData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static boolean decodeShapeData(ImageScope scope) { try { if (scope == null) { return false; } ShapeType type = scope.getShapeType(); String shapeData = scope.getShapeData(); if (shapeData == null) { return false; } switch (type) { case Matting4: case Matting8: { String[] items = shapeData.split(ImageScope.ValueSeparator); for (int i = 0; i < items.length / 2; ++i) { int x = (int) Double.parseDouble(items[i * 2]); int y = (int) Double.parseDouble(items[i * 2 + 1]); scope.addPoint(x, y); } } break; case Rectangle: case Outline: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 4) { DoubleRectangle rect = DoubleRectangle.xy12(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2]), Double.parseDouble(items[3])); scope.setRectangle(rect); } else { return false; } } break; case Circle: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 3) { DoubleCircle circle = new DoubleCircle(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2])); scope.setCircle(circle); } else { return false; } } break; case Ellipse: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 4) { DoubleEllipse ellipse = DoubleEllipse.xy12(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2]), Double.parseDouble(items[3])); scope.setEllipse(ellipse); } else { return false; } } break; case Polygon: { String[] items = shapeData.split(ImageScope.ValueSeparator); DoublePolygon polygon = new DoublePolygon(); for (int i = 0; i < items.length / 2; ++i) { int x = (int) Double.parseDouble(items[i * 2]); int y = (int) Double.parseDouble(items[i * 2 + 1]); polygon.add(x, y); } scope.setPolygon(polygon); } break; } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String encodeOutline(FxTask task, ImageScope scope) { if (scope == null || scope.getShapeType() != ImageScope.ShapeType.Outline) { return ""; } String outlineName = scope.getOutlineName(); try { if (outlineName != null && (outlineName.startsWith("img/") || outlineName.startsWith("buttons/"))) { return outlineName; } BufferedImage outlineSource = scope.getOutlineSource(); if (outlineSource == null) { return ""; } String prefix = AppPaths.getImageScopePath() + File.separator + scope.getShapeType() + "_"; String name = prefix + (new Date().getTime()) + "_" + new Random().nextInt(1000) + ".png"; while (new File(name).exists()) { name = prefix + (new Date().getTime()) + "_" + new Random().nextInt(1000) + ".png"; } if (ImageFileWriters.writeImageFile(task, outlineSource, "png", name)) { outlineName = name; } scope.setOutlineName(outlineName); } catch (Exception e) { // MyBoxLog.error(e); outlineName = ""; } return outlineName; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ImageTextTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ImageTextTools.java
package mara.mybox.image.tools; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.PixelsBlend; import static mara.mybox.image.tools.ShapeTools.stroke; import mara.mybox.controller.ControlImageText; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ImageTextTools { public static BufferedImage addText(FxTask task, BufferedImage sourceImage, ControlImageText optionsController) { try { String text = optionsController.text(); if (text == null || text.isEmpty()) { return sourceImage; } int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; Font font = optionsController.font(); BufferedImage shapeImage = new BufferedImage(width, height, imageType); Graphics2D g = shapeImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } FontMetrics metrics = g.getFontMetrics(font); optionsController.countValues(g, metrics, width, height); PixelsBlend blend = optionsController.getBlend(); if (blend == null || (task != null && !task.isWorking())) { return null; } int textBaseX = optionsController.getBaseX(); int textBaseY = optionsController.getTextY(); int shadowSize = optionsController.getShadow(); g.rotate(Math.toRadians(optionsController.getAngle()), textBaseX, textBaseY); Color textColor = Color.BLACK; Color shadowColor = Color.GRAY; Color borderColor = Color.GREEN; Color fillColor = Color.RED; Color backgroundColor = Color.BLUE; g.setBackground(backgroundColor); if (optionsController.showBorders()) { ShapeStyle style = optionsController.getBorderStyle(); if (style == null || (task != null && !task.isWorking())) { return null; } g.setStroke(stroke(style)); int m = optionsController.getBordersMargin(); DoubleRectangle border = DoubleRectangle.xywh( optionsController.getBaseX() - m, optionsController.getBaseY() - m, optionsController.getTextWidth() + 2 * m, optionsController.getTextHeight() + 2 * m); border.setRoundx(optionsController.getBordersArc()); border.setRoundy(optionsController.getBordersArc()); Shape shape = border.getShape(); if (style == null || (task != null && !task.isWorking())) { return null; } if (optionsController.bordersFilled()) { g.setColor(fillColor); g.fill(shape); } if (optionsController.getBordersStrokeWidth() > 0) { g.setColor(borderColor); g.draw(shape); } } if (blend == null || (task != null && !task.isWorking())) { return null; } g.setStroke(new BasicStroke()); g.setFont(font); if (shadowSize > 0) { g.setColor(shadowColor); drawText(g, optionsController, text, shadowSize); } g.setColor(textColor); drawText(g, optionsController, text, 0); g.dispose(); if (blend == null || (task != null && !task.isWorking())) { return null; } BufferedImage target = new BufferedImage(width, height, imageType); int textPixel = textColor.getRGB(); int shadowPixel = shadowColor.getRGB(); int borderPixel = borderColor.getRGB(); int fillPixel = fillColor.getRGB(); int realTextPixel = optionsController.textColor().getRGB(); int realShadowPixel = optionsController.shadowColor().getRGB(); int realBorderPixel = optionsController.bordersStrokeColor().getRGB(); int realFillPixel = optionsController.bordersFillColor().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int srcPixel = sourceImage.getRGB(i, j); int shapePixel = shapeImage.getRGB(i, j); if (shapePixel == textPixel) { target.setRGB(i, j, blend.blend(realTextPixel, srcPixel)); } else if (shapePixel == shadowPixel) { target.setRGB(i, j, blend.blend(realShadowPixel, srcPixel)); } else if (shapePixel == borderPixel) { target.setRGB(i, j, blend.blend(realBorderPixel, srcPixel)); } else if (shapePixel == fillPixel) { target.setRGB(i, j, blend.blend(realFillPixel, srcPixel)); } else { target.setRGB(i, j, srcPixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean drawText(Graphics2D g, ControlImageText optionsController, String text, int shadow) { try { if (g == null) { return false; } int textBaseX = optionsController.getBaseX(); int textBaseY = optionsController.getTextY(); int rowx = textBaseX, rowy = textBaseY, rowHeight = optionsController.getRowHeight(); String[] lines = text.split("\n", -1); int lend = lines.length - 1; boolean isOutline = optionsController.isOutline(); boolean leftToRight = optionsController.isLeftToRight(); Font font = optionsController.font(); FontMetrics metrics = g.getFontMetrics(font); if (optionsController.isVertical()) { for (int r = (leftToRight ? 0 : lend); (leftToRight ? r <= lend : r >= 0);) { String line = lines[r]; rowy = textBaseY; double cWidthMax = 0; for (int i = 0; i < line.length(); i++) { String c = line.charAt(i) + ""; drawText(g, c, font, rowx, rowy, shadow, isOutline); Rectangle2D cBound = metrics.getStringBounds(c, g); rowy += cBound.getHeight(); if (rowHeight <= 0) { double cWidth = cBound.getWidth(); if (cWidth > cWidthMax) { cWidthMax = cWidth; } } } if (rowHeight > 0) { rowx += rowHeight; } else { rowx += cWidthMax; } if (leftToRight) { r++; } else { r--; } } } else { for (String line : lines) { drawText(g, line, font, rowx, rowy, shadow, isOutline); if (rowHeight > 0) { rowy += rowHeight; } else { rowy += g.getFontMetrics(font).getStringBounds(line, g).getHeight(); } } } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void drawText(Graphics2D g, String text, Font font, int x, int y, int shadow, boolean isOutline) { try { if (text == null || text.isEmpty()) { return; } if (shadow > 0) { // Not blurred. Can improve g.drawString(text, x + shadow, y + shadow); } else { if (isOutline) { FontRenderContext frc = g.getFontRenderContext(); TextLayout textTl = new TextLayout(text, font, frc); Shape outline = textTl.getOutline(null); g.translate(x, y); g.draw(outline); g.translate(-x, -y); } else { g.drawString(text, x, y); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ScaleTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ScaleTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ScaleTools { public static BufferedImage scaleImage(BufferedImage source, int width, int height, Color bgColor) { if (width <= 0 || height <= 0 || (width == source.getWidth() && height == source.getHeight())) { return source; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setBackground(bgColor); g.drawImage(source, 0, 0, width, height, null); g.dispose(); return target; } public static BufferedImage scaleImage(BufferedImage source, int width, int height) { return scaleImage(source, width, height, Colors.TRANSPARENT); } public static BufferedImage scaleImage(BufferedImage source, int targetW, int targetH, boolean keepRatio, int keepType) { int finalW = targetW; int finalH = targetH; if (keepRatio) { int[] wh = ScaleTools.scaleValues(source.getWidth(), source.getHeight(), targetW, targetH, keepType); finalW = wh[0]; finalH = wh[1]; } return scaleImageBySize(source, finalW, finalH); } public static int[] scaleValues(int sourceX, int sourceY, int newWidth, int newHeight, int keepRatioType) { int finalW = newWidth; int finalH = newHeight; if (keepRatioType != BufferedImageTools.KeepRatioType.None) { double ratioW = (double) newWidth / sourceX; double ratioH = (double) newHeight / sourceY; if (ratioW != ratioH) { switch (keepRatioType) { case BufferedImageTools.KeepRatioType.BaseOnWidth: finalH = (int) (ratioW * sourceY); break; case BufferedImageTools.KeepRatioType.BaseOnHeight: finalW = (int) (ratioH * sourceX); break; case BufferedImageTools.KeepRatioType.BaseOnLarger: if (ratioW > ratioH) { finalH = (int) (ratioW * sourceY); } else { finalW = (int) (ratioH * sourceX); } break; case BufferedImageTools.KeepRatioType.BaseOnSmaller: if (ratioW < ratioH) { finalH = (int) (ratioW * sourceY); } else { finalW = (int) (ratioH * sourceX); } break; } } } int[] d = new int[2]; d[0] = finalW; d[1] = finalH; return d; } public static BufferedImage scaleImageByScale(BufferedImage source, float scale) { return scaleImageByScale(source, scale, scale); } public static BufferedImage scaleImageByScale(BufferedImage source, float xscale, float yscale) { int width = (int) (source.getWidth() * xscale); int height = (int) (source.getHeight() * yscale); return scaleImage(source, width, height); } public static BufferedImage scaleImageHeightKeep(BufferedImage source, int height) { int width = source.getWidth() * height / source.getHeight(); return scaleImage(source, width, height); } public static BufferedImage scaleImageBySize(BufferedImage source, int width, int height) { return scaleImage(source, width, height); } public static BufferedImage scaleImageWidthKeep(BufferedImage source, int width) { if (width <= 0 || width == source.getWidth()) { return source; } int height = source.getHeight() * width / source.getWidth(); return scaleImage(source, width, height); } public static BufferedImage demoImage(BufferedImage source) { return scaleImageLess(source, AppVariables.maxDemoImage); } public static BufferedImage scaleImageLess(BufferedImage source, long size) { if (size <= 0) { return source; } float scale = size * 1f / (source.getWidth() * source.getHeight()); if (scale >= 1) { return source; } return scaleImageByScale(source, scale); } public static BufferedImage fitSize(BufferedImage source, int targetW, int targetH) { try { int[] wh = ScaleTools.scaleValues(source.getWidth(), source.getHeight(), targetW, targetH, BufferedImageTools.KeepRatioType.BaseOnSmaller); int finalW = wh[0]; int finalH = wh[1]; int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(targetW, targetH, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setBackground(Colors.TRANSPARENT); g.drawImage(source, (targetW - finalW) / 2, (targetH - finalH) / 2, finalW, finalH, null); g.dispose(); return target; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/ImageConvertTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/ImageConvertTools.java
package mara.mybox.image.tools; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageBinary; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.image.file.ImageFileReaders.getReader; import static mara.mybox.image.file.ImageFileReaders.readBrokenImage; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import thridparty.image4j.ICODecoder; import thridparty.image4j.ICOEncoder; /** * @Author Mara * @CreateDate 2019-6-22 9:52:02 * @License Apache License Version 2.0 */ public class ImageConvertTools { // dpi(dot per inch) convert to dpm(dot per millimeter) public static int dpi2dpmm(int dpi) { return Math.round(dpi / 25.4f); } // dpi(dot per inch) convert to ppm(dot per meter) public static int dpi2dpm(int dpi) { return Math.round(1000 * dpi / 25.4f); } // ppm(dot Per Meter) convert to dpi(dot per inch) public static int dpm2dpi(int dpm) { return Math.round(dpm * 25.4f / 1000f); } // dpi(dot per inch) convert to dpm(dot per centimeter) public static int dpi2dpcm(int dpi) { return Math.round(dpi / 2.54f); } // dpm(dot per centimeter) convert to dpi(dot per inch) public static int dpcm2dpi(int dpcm) { return Math.round(dpcm * 2.54f); } public static int inch2cm(float inch) { return Math.round(inch / 2.54f); } // "pixel size in millimeters" convert to dpi(dot per inch) public static int pixelSizeMm2dpi(float psmm) { // if (psmm == 0) { return 0; } return Math.round(25.4f / psmm); } // dpi(dot per inch) convert to "pixel size in millimeters" public static float dpi2pixelSizeMm(int dpi) { // if (dpi == 0) { return 0; } return 25.4f / dpi; } public static BufferedImage convert(FxTask task, BufferedImage srcImage, String format) { return convertColorSpace(task, srcImage, new ImageAttributes(srcImage, format)); } public static BufferedImage convertBinary(FxTask task, BufferedImage srcImage, ImageAttributes attributes) { try { if (srcImage == null || attributes == null) { return srcImage; } ImageBinary imageBinary = attributes.getImageBinary(); if (imageBinary == null) { imageBinary = new ImageBinary(); } imageBinary.setImage(srcImage).setTask(task); BufferedImage targetImage = imageBinary.start(); if (targetImage == null) { return null; } targetImage = ImageBinary.byteBinary(task, targetImage); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static BufferedImage convertColorSpace(FxTask task, BufferedImage srcImage, ImageAttributes attributes) { try { if (srcImage == null || attributes == null) { return srcImage; } String targetFormat = attributes.getImageFormat(); if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) { return convertToIcon(task, srcImage, attributes); } BufferedImage tmpImage = srcImage; if (null != attributes.getAlpha()) { switch (attributes.getAlpha()) { case PremultipliedAndKeep: tmpImage = AlphaTools.premultipliedAlpha(task, srcImage, false); break; case PremultipliedAndRemove: tmpImage = AlphaTools.premultipliedAlpha(task, srcImage, true); break; case Remove: tmpImage = AlphaTools.removeAlpha(task, srcImage); break; } } if (tmpImage == null) { return null; } ICC_Profile targetProfile = attributes.getProfile(); String csName = attributes.getColorSpaceName(); if (targetProfile == null) { if (csName == null) { return tmpImage; } if ("BlackOrWhite".equals(csName) || message("BlackOrWhite").equals(csName)) { return convertBinary(task, tmpImage, attributes); } else { if (message("Gray").equals(csName)) { csName = "Gray"; tmpImage = AlphaTools.removeAlpha(task, srcImage); } targetProfile = ImageColorSpace.internalProfileByName(csName); attributes.setProfile(targetProfile); attributes.setProfileName(csName); } } if (tmpImage == null || (task != null && !task.isWorking())) { return null; } ICC_ColorSpace targetColorSpace = new ICC_ColorSpace(targetProfile); ColorConvertOp c = new ColorConvertOp(targetColorSpace, null); BufferedImage targetImage = c.filter(tmpImage, null); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertColorSpace(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null || attributes == null) { return false; } String targetFormat = attributes.getImageFormat(); if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) { return convertToIcon(task, srcFile, attributes, targetFile); } String sourceFormat = FileNameTools.ext(srcFile.getName()); if ("ico".equals(sourceFormat) || "icon".equals(sourceFormat)) { return convertFromIcon(task, srcFile, attributes, targetFile); } boolean supportMultiFrames = FileExtensions.MultiFramesImages.contains(targetFormat); ImageWriter writer = ImageFileWriters.getWriter(targetFormat); if (writer == null) { return false; } ImageWriteParam param = ImageFileWriters.getWriterParam(attributes, writer); File tmpFile = FileTmpTools.getTempFile(); try (ImageInputStream iis = ImageIO.createImageInputStream(srcFile); ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { ImageReader reader = ImageFileReaders.getReader(iis, sourceFormat); if (reader == null) { writer.dispose(); return false; } reader.setInput(iis, false); writer.setOutput(out); if (supportMultiFrames) { writer.prepareWriteSequence(null); } BufferedImage bufferedImage; int index = 0; ImageInformation info = new ImageInformation(srcFile); while (true) { if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return false; } try { bufferedImage = reader.read(index); } catch (Exception e) { if (e.toString().contains("java.lang.IndexOutOfBoundsException")) { break; } bufferedImage = readBrokenImage(task, e, info.setIndex(index)); } if (bufferedImage == null) { continue; } bufferedImage = ImageConvertTools.convertColorSpace(task, bufferedImage, attributes); if (bufferedImage == null) { continue; } IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, bufferedImage, writer, param); if (supportMultiFrames) { writer.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } else { writer.write(metaData, new IIOImage(bufferedImage, null, metaData), param); } index++; } if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return false; } if (supportMultiFrames) { writer.endWriteSequence(); } out.flush(); reader.dispose(); } writer.dispose(); return FileTools.override(tmpFile, targetFile); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static BufferedImage convertToPNG(BufferedImage srcImage) { try { if (srcImage == null || srcImage.getType() == BufferedImage.TYPE_4BYTE_ABGR || srcImage.getType() == BufferedImage.TYPE_4BYTE_ABGR_PRE) { return srcImage; } ICC_Profile targetProfile = ICC_Profile.getInstance(ICC_ColorSpace.CS_sRGB); ICC_ColorSpace targetColorSpace = new ICC_ColorSpace(targetProfile); ColorConvertOp c = new ColorConvertOp(targetColorSpace, null); BufferedImage targetImage = c.filter(srcImage, null); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertToIcon(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null) { return false; } List<BufferedImage> images = new ArrayList(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(srcFile)))) { ImageReader reader = getReader(iis, FileNameTools.ext(srcFile.getName())); if (reader == null) { return false; } reader.setInput(iis, false); BufferedImage bufferedImage; int index = 0; ImageInformation info = new ImageInformation(srcFile); while (true) { if (task != null && !task.isWorking()) { reader.dispose(); return false; } try { bufferedImage = reader.read(index); } catch (Exception e) { if (e.toString().contains("java.lang.IndexOutOfBoundsException")) { break; } bufferedImage = readBrokenImage(task, e, info.setIndex(index)); } if (task != null && !task.isWorking()) { reader.dispose(); return false; } if (bufferedImage != null) { bufferedImage = convertToIcon(task, bufferedImage, attributes); images.add(bufferedImage); index++; } else { break; } } reader.dispose(); } if (images.isEmpty()) { return false; } ICOEncoder.write(images, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean convertToIcon(FxTask task, BufferedImage bufferedImage, ImageAttributes attributes, File targetFile) { try { if (bufferedImage == null || targetFile == null) { return false; } BufferedImage icoImage = convertToIcon(task, bufferedImage, attributes); if (icoImage == null || (task != null && !task.isWorking())) { return false; } ICOEncoder.write(icoImage, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static BufferedImage convertToIcon(FxTask task, BufferedImage bufferedImage, ImageAttributes attributes) { try { if (bufferedImage == null) { return null; } int width = 0; if (attributes != null) { width = attributes.getWidth(); } if (width <= 0) { width = Math.min(512, bufferedImage.getWidth()); } BufferedImage icoImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width); return icoImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertFromIcon(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null) { return false; } List<BufferedImage> images = ICODecoder.read(srcFile); if (images == null || images.isEmpty() || (task != null && !task.isWorking())) { return false; } String targetFormat = attributes.getImageFormat(); boolean supportMultiFrames = FileExtensions.MultiFramesImages.contains(targetFormat); ImageWriter writer = ImageFileWriters.getWriter(targetFormat); ImageWriteParam param = ImageFileWriters.getWriterParam(attributes, writer); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); int num; if (supportMultiFrames) { num = images.size(); writer.prepareWriteSequence(null); } else { num = 1; } BufferedImage bufferedImage; for (int i = 0; i < num; ++i) { if (task != null && !task.isWorking()) { writer.dispose(); return false; } bufferedImage = images.get(i); bufferedImage = ImageConvertTools.convertColorSpace(task, bufferedImage, attributes); if (task != null && !task.isWorking()) { writer.dispose(); return false; } if (bufferedImage == null) { continue; } IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, bufferedImage, writer, param); if (supportMultiFrames) { writer.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } else { writer.write(metaData, new IIOImage(bufferedImage, null, metaData), param); } } if (task != null && !task.isWorking()) { writer.dispose(); return false; } if (supportMultiFrames) { writer.endWriteSequence(); } out.flush(); } writer.dispose(); return FileTools.override(tmpFile, targetFile); } catch (Exception e) { MyBoxLog.error(e); return false; } } // https://stackoverflow.com/questions/2408613/unable-to-read-jpeg-image-using-imageio-readfile-file/12132805#12132805 // https://stackoverflow.com/questions/50798014/determining-color-space-for-jpeg/50861048?r=SearchResults#50861048 // https://blog.idrsolutions.com/2011/10/ycck-color-conversion-in-pdf-files/ // https://community.oracle.com/message/10003648?tstart=0 public static void ycck2cmyk(FxTask task, WritableRaster rast, boolean invertedColors) { int w = rast.getWidth(), h = rast.getHeight(); double c, m, y, k; double Y, Cb, Cr, K; int[] pixels = null; for (int row = 0; row < h; row++) { if (task != null && !task.isWorking()) { return; } pixels = rast.getPixels(0, row, w, 1, pixels); for (int i = 0; i < pixels.length; i += 4) { if (task != null && !task.isWorking()) { return; } Y = pixels[i]; Cb = pixels[i + 1]; Cr = pixels[i + 2]; K = pixels[i + 3]; c = Math.min(255, Math.max(0, 255 - (Y + 1.402 * Cr - 179.456))); m = Math.min(255, Math.max(0, 255 - (Y - 0.34414 * Cb - 0.71414 * Cr + 135.45984))); y = Math.min(255, Math.max(0, 255 - (Y + 1.7718d * Cb - 226.816))); k = K; if (invertedColors) { pixels[i] = (byte) (255 - c); pixels[i + 1] = (byte) (255 - m); pixels[i + 2] = (byte) (255 - y); pixels[i + 3] = (byte) (255 - k); } else { pixels[i] = (byte) c; pixels[i + 1] = (byte) m; pixels[i + 2] = (byte) y; pixels[i + 3] = (byte) k; } } rast.setPixels(0, row, w, 1, pixels); } } public static void invertPixelValue(FxTask task, WritableRaster raster) { int height = raster.getHeight(); int width = raster.getWidth(); int stride = width * 4; int[] pixelRow = new int[stride]; for (int h = 0; h < height; h++) { if (task != null && !task.isWorking()) { return; } raster.getPixels(0, h, width, 1, pixelRow); for (int x = 0; x < stride; x++) { if (task != null && !task.isWorking()) { return; } pixelRow[x] = 255 - pixelRow[x]; } raster.setPixels(0, h, width, 1, pixelRow); } } public static Raster ycck2cmyk(FxTask task, final byte[] buffer, final int w, final int h) throws IOException { final int pixelCount = w * h * 4; for (int i = 0; i < pixelCount; i = i + 4) { if (task != null && !task.isWorking()) { return null; } int y = (buffer[i] & 255); int cb = (buffer[i + 1] & 255); int cr = (buffer[i + 2] & 255); // int k = (buffer[i + 3] & 255); int r = Math.max(0, Math.min(255, (int) (y + 1.402 * cr - 179.456))); int g = Math.max(0, Math.min(255, (int) (y - 0.34414 * cb - 0.71414 * cr + 135.95984))); int b = Math.max(0, Math.min(255, (int) (y + 1.772 * cb - 226.316))); buffer[i] = (byte) (255 - r); buffer[i + 1] = (byte) (255 - g); buffer[i + 2] = (byte) (255 - b); } return Raster.createInterleavedRaster(new DataBufferByte(buffer, pixelCount), w, h, w * 4, 4, new int[]{ 0, 1, 2, 3}, null); } public static BufferedImage rgb2cmyk(ICC_Profile cmykProfile, BufferedImage inImage) throws IOException { if (cmykProfile == null) { cmykProfile = ImageColorSpace.eciCmykProfile(); } ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile); ColorConvertOp rgb2cmyk = new ColorConvertOp(cmykCS, null); return rgb2cmyk.filter(inImage, null); } public static BufferedImage cmyk2rgb(Raster cmykRaster, ICC_Profile cmykProfile) throws IOException { if (cmykProfile == null) { cmykProfile = ImageColorSpace.eciCmykProfile(); } ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile); BufferedImage rgbImage = new BufferedImage(cmykRaster.getWidth(), cmykRaster.getHeight(), BufferedImage.TYPE_INT_RGB); WritableRaster rgbRaster = rgbImage.getRaster(); ColorSpace rgbCS = rgbImage.getColorModel().getColorSpace(); ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null); cmykToRgb.filter(cmykRaster, rgbRaster); return rgbImage; } // https://bugs.openjdk.java.net/browse/JDK-8041125 public static BufferedImage cmyk2rgb(FxTask task, final byte[] buffer, final int w, final int h) throws IOException { final ColorSpace CMYK = ImageColorSpace.adobeCmykColorSpace(); final int pixelCount = w * h * 4; int C, M, Y, K, lastC = -1, lastM = -1, lastY = -1, lastK = -1; int j = 0; float[] RGB = new float[]{0f, 0f, 0f}; //turn YCC in Buffer to CYM using profile for (int i = 0; i < pixelCount; i = i + 4) { if (task != null && !task.isWorking()) { return null; } C = (buffer[i] & 255); M = (buffer[i + 1] & 255); Y = (buffer[i + 2] & 255); K = (buffer[i + 3] & 255); // System.out.println(C+" "+M+" "+Y+" "+K); if (C == lastC && M == lastM && Y == lastY && K == lastK) { //no change so use last value } else { //new value RGB = CMYK.toRGB(new float[]{C / 255f, M / 255f, Y / 255f, K / 255f}); //flag so we can just reuse if next value the same lastC = C; lastM = M; lastY = Y; lastK = K; } //put back as CMY buffer[j] = (byte) (RGB[0] * 255f); buffer[j + 1] = (byte) (RGB[1] * 255f); buffer[j + 2] = (byte) (RGB[2] * 255f); j = j + 3; } /** * create CMYK raster from buffer */ final Raster raster = Raster.createInterleavedRaster(new DataBufferByte(buffer, j), w, h, w * 3, 3, new int[]{ 0, 1, 2}, null); //data now sRGB so create image final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); image.setData(raster); return image; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/AlphaTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/AlphaTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.data.DoubleRectangle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; import mara.mybox.value.FileExtensions; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class AlphaTools { // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4836466 public static BufferedImage checkAlpha(FxTask task, BufferedImage source, String targetFormat) { if (targetFormat == null) { return source; } BufferedImage checked = source; if (FileExtensions.NoAlphaImages.contains(targetFormat.toLowerCase())) { if (hasAlpha(source)) { checked = AlphaTools.premultipliedAlpha(task, source, true); } } return checked; } public static boolean hasAlpha(BufferedImage source) { switch (source.getType()) { case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_BYTE_BINARY: case BufferedImage.TYPE_BYTE_GRAY: case BufferedImage.TYPE_BYTE_INDEXED: case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_USHORT_555_RGB: case BufferedImage.TYPE_USHORT_565_RGB: case BufferedImage.TYPE_USHORT_GRAY: return false; default: if (source.getColorModel() != null) { return source.getColorModel().hasAlpha(); } else { return true; } } } public static BufferedImage removeAlpha(FxTask task, BufferedImage source) { return AlphaTools.removeAlpha(task, source, ColorConvertTools.alphaColor()); } public static BufferedImage removeAlpha(FxTask task, BufferedImage source, Color alphaColor) { try { if (!hasAlpha(source)) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_RGB; BufferedImage target = new BufferedImage(width, height, imageType); int alphaPixel = alphaColor.getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, alphaPixel); } else { target.setRGB(i, j, new Color(pixel, false).getRGB()); } } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage[] extractAlpha(FxTask task, BufferedImage source) { try { if (source == null) { return null; } BufferedImage[] bfs = new BufferedImage[2]; int width = source.getWidth(); int height = source.getHeight(); BufferedImage alphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); BufferedImage noAlphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Color color; Color newColor; int pixel; int alphaPixel = ColorConvertTools.alphaColor().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } pixel = source.getRGB(i, j); if (pixel == 0) { noAlphaImage.setRGB(i, j, alphaPixel); alphaImage.setRGB(i, j, 0); } else { color = new Color(pixel, true); newColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); noAlphaImage.setRGB(i, j, newColor.getRGB()); newColor = new Color(0, 0, 0, color.getAlpha()); alphaImage.setRGB(i, j, newColor.getRGB()); } } } bfs[0] = noAlphaImage; bfs[1] = alphaImage; return bfs; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage extractAlphaOnly(FxTask task, BufferedImage source) { try { if (source == null) { return null; } int width = source.getWidth(); int height = source.getHeight(); BufferedImage alphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Color color; Color newColor; int pixel; for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } pixel = source.getRGB(i, j); color = new Color(pixel, true); newColor = new Color(0, 0, 0, color.getAlpha()); alphaImage.setRGB(i, j, newColor.getRGB()); } } return alphaImage; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage premultipliedAlpha(FxTask task, BufferedImage source, boolean removeAlpha) { try { if (source == null || !AlphaTools.hasAlpha(source) || (source.isAlphaPremultiplied() && !removeAlpha)) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); int imageType; if (removeAlpha) { imageType = BufferedImage.TYPE_INT_RGB; } else { imageType = BufferedImage.TYPE_INT_ARGB_PRE; } BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, imageType); Color sourceColor; Color newColor; Color bkColor = ColorConvertTools.alphaColor(); int bkPixel = bkColor.getRGB(); for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, bkPixel); continue; } sourceColor = new Color(pixel, true); newColor = ColorBlendTools.blendColor(sourceColor, sourceColor.getAlpha(), bkColor, !removeAlpha); target.setRGB(i, j, newColor.getRGB()); } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return source; } } public static BufferedImage addAlpha(FxTask task, BufferedImage source, BufferedImage alpha, boolean isPlus) { try { if (source == null || alpha == null || !alpha.getColorModel().hasAlpha()) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); int alphaWidth = alpha.getWidth(); int alphaHeight = alpha.getHeight(); boolean addAlpha = isPlus && source.getColorModel().hasAlpha(); BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_ARGB); Color sourceColor; Color alphaColor; Color newColor; int alphaValue; for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } if (i < alphaWidth && j < alphaHeight) { sourceColor = new Color(source.getRGB(i, j), addAlpha); alphaColor = new Color(alpha.getRGB(i, j), true); alphaValue = alphaColor.getAlpha(); if (addAlpha) { alphaValue = Math.min(255, alphaValue + sourceColor.getAlpha()); } newColor = new Color(sourceColor.getRed(), sourceColor.getGreen(), sourceColor.getBlue(), alphaValue); target.setRGB(i, j, newColor.getRGB()); } else { target.setRGB(i, j, source.getRGB(i, j)); } } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage addAlpha(FxTask task, BufferedImage source, float opacity, boolean isPlus) { try { if (source == null || opacity < 0) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); boolean addAlpha = isPlus && source.getColorModel().hasAlpha(); BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_ARGB); Color sourceColor; Color newColor; int opacityValue = Math.min(255, Math.round(opacity * 255)); for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } sourceColor = new Color(source.getRGB(i, j), addAlpha); if (addAlpha) { opacityValue = Math.min(255, opacityValue + sourceColor.getAlpha()); } newColor = new Color(sourceColor.getRed(), sourceColor.getGreen(), sourceColor.getBlue(), opacityValue); target.setRGB(i, j, newColor.getRGB()); } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage premultipliedAlpha2(FxTask task, BufferedImage source, boolean removeAlpha) { try { if (source == null || !AlphaTools.hasAlpha(source) || (source.isAlphaPremultiplied() && !removeAlpha)) { return source; } BufferedImage target = BufferedImageTools.clone(source); target.coerceData(true); if (removeAlpha) { target = AlphaTools.removeAlpha(task, target); } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return source; } } public static BufferedImage[] outline(FxTask task, BufferedImage alphaImage, DoubleRectangle rect, int bgWidth, int bgHeight, boolean keepRatio) { try { if (alphaImage == null) { return null; } BufferedImage scaledImage = ScaleTools.scaleImage(alphaImage, (int) rect.getWidth(), (int) rect.getHeight(), keepRatio, BufferedImageTools.KeepRatioType.BaseOnWidth); int offsetX = (int) rect.getX(); int offsetY = (int) rect.getY(); int scaledWidth = scaledImage.getWidth(); int scaledHeight = scaledImage.getHeight(); int width = offsetX >= 0 ? Math.max(bgWidth, scaledWidth + offsetX) : Math.max(bgWidth - offsetX, scaledWidth); int height = offsetY >= 0 ? Math.max(bgHeight, scaledHeight + offsetY) : Math.max(bgHeight - offsetY, scaledHeight); int startX = offsetX >= 0 ? offsetX : 0; int startY = offsetY >= 0 ? offsetY : 0; BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setColor(Colors.TRANSPARENT); g.fillRect(0, 0, width, height); int imagePixel; int inPixel = 64, outPixel = -64; for (int j = 0; j < scaledHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < scaledWidth; ++i) { if (task != null && !task.isWorking()) { return null; } imagePixel = scaledImage.getRGB(i, j); target.setRGB(i + startX, j + startY, imagePixel == 0 ? outPixel : inPixel); } } g.dispose(); BufferedImage[] ret = new BufferedImage[2]; ret[0] = scaledImage; ret[1] = target; return ret; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/RepeatTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/RepeatTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.CropTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2022-9-25 * @License Apache License Version 2.0 */ public class RepeatTools { public static BufferedImage repeat(FxTask task, BufferedImage source, int repeatH, int repeatV, int interval, int margin, Color bgColor) { try { if (source == null || repeatH <= 0 || repeatV <= 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; int stepx = width + interval; int stepy = height + interval; int totalWidth = width + stepx * (repeatH - 1) + margin * 2; int totalHeight = height + stepy * (repeatV - 1) + margin * 2; BufferedImage target = new BufferedImage(totalWidth, totalHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, totalWidth, totalHeight); int x, y = margin; for (int v = 0; v < repeatV; ++v) { if (task != null && !task.isWorking()) { return null; } x = margin; for (int h = 0; h < repeatH; ++h) { if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, width, height, null); x += stepx; } y += stepy; } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage tile(FxTask task, BufferedImage source, int canvasWidth, int canvasHeight, int interval, int margin, Color bgColor) { try { if (source == null || canvasWidth <= 0 || canvasHeight <= 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(canvasWidth, canvasHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, canvasWidth, canvasHeight); int x = margin, y = margin; int stepx = width + interval; int stepy = height + interval; for (int v = margin; v < canvasHeight - height - margin; v += stepy) { if (task != null && !task.isWorking()) { return null; } for (int h = margin; h < canvasWidth - width - margin; h += stepx) { if (task != null && !task.isWorking()) { return null; } g.drawImage(source, h, v, width, height, null); x = h + stepx; y = v + stepy; } } int leftWidth = canvasWidth - margin - x; if (leftWidth > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, leftWidth, height); if (cropped == null || (task != null && !task.isWorking())) { return null; } for (int v = margin; v < canvasHeight - height - margin; v += stepy) { if (task != null && !task.isWorking()) { return null; } g.drawImage(cropped, x, v, leftWidth, height, null); } } int leftHeight = canvasHeight - margin - y; if (leftHeight > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, width, leftHeight); if (cropped == null || (task != null && !task.isWorking())) { return null; } for (int h = margin; h < canvasWidth - width - margin; h += stepx) { if (task != null && !task.isWorking()) { return null; } g.drawImage(cropped, h, y, width, leftHeight, null); } } if (leftWidth > 0 && leftHeight > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, leftWidth, leftHeight); if (cropped == null || (task != null && !task.isWorking())) { return null; } g.drawImage(cropped, x, y, leftWidth, leftHeight, null); } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/CombineTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/CombineTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.image.data.ImageCombine; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class CombineTools { public static Image combineSingleRow(FxTask task, ImageCombine imageCombine, List<ImageInformation> images, boolean isPart, boolean careTotal) { if (imageCombine == null || images == null) { return null; } try { int imageWidth; int imageHeight; int totalWidth = 0; int totalHeight = 0; int maxHeight = 0; int minHeight = Integer.MAX_VALUE; int sizeType = imageCombine.getSizeType(); if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { for (ImageInformation imageInfo : images) { if (task != null && !task.isWorking()) { return null; } imageHeight = (int) imageInfo.getPickedHeight(); if (imageHeight > maxHeight) { maxHeight = imageHeight; } } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { for (ImageInformation imageInfo : images) { if (task != null && !task.isWorking()) { return null; } imageHeight = (int) imageInfo.getPickedHeight(); if (imageHeight < minHeight) { minHeight = imageHeight; } } } int x = isPart ? 0 : imageCombine.getMarginsValue(); int y = isPart ? 0 : imageCombine.getMarginsValue(); List<Integer> xs = new ArrayList<>(); List<Integer> ys = new ArrayList<>(); List<Integer> widths = new ArrayList<>(); List<Integer> heights = new ArrayList<>(); for (int i = 0; i < images.size(); i++) { if (task != null && !task.isWorking()) { return null; } ImageInformation imageInfo = images.get(i); imageWidth = (int) imageInfo.getPickedWidth(); imageHeight = (int) imageInfo.getPickedHeight(); if (sizeType == ImageCombine.CombineSizeType.KeepSize || sizeType == ImageCombine.CombineSizeType.TotalWidth || sizeType == ImageCombine.CombineSizeType.TotalHeight) { } else if (sizeType == ImageCombine.CombineSizeType.EachWidth) { imageHeight = (imageHeight * imageCombine.getEachWidthValue()) / imageWidth; imageWidth = imageCombine.getEachWidthValue(); } else if (sizeType == ImageCombine.CombineSizeType.EachHeight) { imageWidth = (imageWidth * imageCombine.getEachHeightValue()) / imageHeight; imageHeight = imageCombine.getEachHeightValue(); } else if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { imageWidth = (imageWidth * maxHeight) / imageHeight; imageHeight = maxHeight; } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { imageWidth = (imageWidth * minHeight) / imageHeight; imageHeight = minHeight; } xs.add(x); ys.add(y); widths.add(imageWidth); heights.add(imageHeight); x += imageWidth + imageCombine.getIntervalValue(); if (imageHeight > totalHeight) { totalHeight = imageHeight; } } totalWidth = x - imageCombine.getIntervalValue(); if (!isPart) { totalWidth += imageCombine.getMarginsValue(); totalHeight += 2 * imageCombine.getMarginsValue(); } Image newImage = combineImages(task, images, (int) totalWidth, (int) totalHeight, FxColorTools.toAwtColor(imageCombine.getBgColor()), xs, ys, widths, heights, imageCombine.getTotalWidthValue(), imageCombine.getTotalHeightValue(), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalWidth), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalHeight)); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineSingleColumn(FxTask task, ImageCombine imageCombine, List<ImageInformation> imageInfos, boolean isPart, boolean careTotal) { if (imageCombine == null || imageInfos == null) { return null; } try { int imageWidth; int imageHeight; int totalWidth = 0; int totalHeight = 0; int maxWidth = 0; int minWidth = Integer.MAX_VALUE; int sizeType = imageCombine.getSizeType(); if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); if (imageWidth > maxWidth) { maxWidth = imageWidth; } } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); if (imageWidth < minWidth) { minWidth = imageWidth; } } } int x = isPart ? 0 : imageCombine.getMarginsValue(); int y = isPart ? 0 : imageCombine.getMarginsValue(); List<Integer> xs = new ArrayList<>(); List<Integer> ys = new ArrayList<>(); List<Integer> widths = new ArrayList<>(); List<Integer> heights = new ArrayList<>(); for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); imageHeight = (int) imageInfo.getPickedHeight(); if (sizeType == ImageCombine.CombineSizeType.KeepSize || sizeType == ImageCombine.CombineSizeType.TotalWidth || sizeType == ImageCombine.CombineSizeType.TotalHeight) { } else if (sizeType == ImageCombine.CombineSizeType.EachWidth) { if (!isPart) { imageHeight = (imageHeight * imageCombine.getEachWidthValue()) / imageWidth; imageWidth = imageCombine.getEachWidthValue(); } } else if (sizeType == ImageCombine.CombineSizeType.EachHeight) { if (!isPart) { imageWidth = (imageWidth * imageCombine.getEachHeightValue()) / imageHeight; imageHeight = imageCombine.getEachHeightValue(); } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { imageHeight = (imageHeight * maxWidth) / imageWidth; imageWidth = maxWidth; } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { imageHeight = (imageHeight * minWidth) / imageWidth; imageWidth = minWidth; } xs.add(x); ys.add(y); widths.add((int) imageWidth); heights.add((int) imageHeight); y += imageHeight + imageCombine.getIntervalValue(); if (imageWidth > totalWidth) { totalWidth = imageWidth; } } totalHeight = y - imageCombine.getIntervalValue(); if (!isPart) { totalWidth += 2 * imageCombine.getMarginsValue(); totalHeight += imageCombine.getMarginsValue(); } Image newImage = combineImages(task, imageInfos, (int) totalWidth, (int) totalHeight, FxColorTools.toAwtColor(imageCombine.getBgColor()), xs, ys, widths, heights, imageCombine.getTotalWidthValue(), imageCombine.getTotalHeightValue(), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalWidth), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalHeight)); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineImages(FxTask task, List<ImageInformation> imageInfos, int totalWidth, int totalHeight, Color bgColor, List<Integer> xs, List<Integer> ys, List<Integer> widths, List<Integer> heights, int trueTotalWidth, int trueTotalHeight, boolean isTotalWidth, boolean isTotalHeight) { if (imageInfos == null || xs == null || ys == null || widths == null || heights == null) { return null; } try { BufferedImage target = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, totalWidth, totalHeight); for (int i = 0; i < imageInfos.size(); ++i) { if (task != null && !task.isWorking()) { return null; } ImageInformation imageInfo = imageInfos.get(i); Image image = imageInfo.loadImage(task); if (image == null || (task != null && !task.isWorking())) { return null; } BufferedImage source = SwingFXUtils.fromFXImage(image, null); g.drawImage(source, xs.get(i), ys.get(i), widths.get(i), heights.get(i), null); } if (isTotalWidth) { target = ScaleTools.scaleImageBySize(target, trueTotalWidth, (trueTotalWidth * totalHeight) / totalWidth); } else if (isTotalHeight) { target = ScaleTools.scaleImageBySize(target, (trueTotalHeight * totalWidth) / totalHeight, trueTotalHeight); } if (target == null || (task != null && !task.isWorking())) { return null; } Image newImage = SwingFXUtils.toFXImage(target, null); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineImagesColumns(FxTask currentTask, ImageCombine imageCombine, List<ImageInformation> imageInfos) { if (imageInfos == null || imageInfos.isEmpty() || imageCombine.getColumnsValue() <= 0) { return null; } try { List<ImageInformation> rowImages = new ArrayList<>(); List<ImageInformation> rows = new ArrayList<>(); for (ImageInformation imageInfo : imageInfos) { if (currentTask != null && !currentTask.isWorking()) { return null; } rowImages.add(imageInfo); if (rowImages.size() == imageCombine.getColumnsValue()) { Image rowImage = CombineTools.combineSingleRow(currentTask, imageCombine, rowImages, true, false); if (rowImage == null || (currentTask != null && !currentTask.isWorking())) { return null; } rows.add(new ImageInformation(rowImage)); rowImages = new ArrayList<>(); } } if (!rowImages.isEmpty()) { Image rowImage = CombineTools.combineSingleRow(currentTask, imageCombine, rowImages, true, false); if (rowImage == null || (currentTask != null && !currentTask.isWorking())) { return null; } rows.add(new ImageInformation(rowImage)); } Image newImage = CombineTools.combineSingleColumn(currentTask, imageCombine, rows, false, true); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/MarginTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/MarginTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.CropTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class MarginTools { public static BufferedImage blurMarginsAlpha(FxTask task, BufferedImage source, int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; Color newColor; for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, 0); continue; } iOpocity = jOpacity = 1.0F; if (i < blurWidth) { if (blurLeft) { iOpocity = 1.0F * i / blurWidth; } } else if (i > width - blurWidth) { if (blurRight) { iOpocity = 1.0F * (width - i) / blurWidth; } } if (j < blurWidth) { if (blurTop) { jOpacity = 1.0F * j / blurWidth; } } else if (j > height - blurWidth) { if (blurBottom) { jOpacity = 1.0F * (height - j) / blurWidth; } } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { target.setRGB(i, j, pixel); } else { newColor = new Color(pixel); opocity = newColor.getAlpha() * opocity; newColor = new Color(newColor.getRed(), newColor.getGreen(), newColor.getBlue(), (int) opocity); target.setRGB(i, j, newColor.getRGB()); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage cutMarginsByColor(FxTask task, BufferedImage source, Color cutColor, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) { try { if (cutColor.getRGB() == Colors.TRANSPARENT.getRGB() && !AlphaTools.hasAlpha(source)) { return source; } int width = source.getWidth(); int height = source.getHeight(); int top, bottom, left, right; int cutValue = cutColor.getRGB(); if (cutTop) { top = -1; toploop: for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { top = j; break toploop; } } } if (top < 0) { return null; } } else { top = 0; } if (cutBottom) { bottom = -1; bottomploop: for (int j = height - 1; j >= 0; --j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { bottom = j + 1; break bottomploop; } } } if (bottom < 0) { return null; } } else { bottom = height; } if (cutLeft) { left = -1; leftloop: for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { left = i; break leftloop; } } } if (left < 0) { return null; } } else { left = 0; } if (cutRight) { right = -1; rightloop: for (int i = width - 1; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { right = i + 1; break rightloop; } } } if (right < 0) { return null; } } else { right = width; } BufferedImage target = CropTools.cropOutside(task, source, left, top, right, bottom); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage cutMarginsByWidth(FxTask task, BufferedImage source, int MarginWidth, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) { try { if (source == null || MarginWidth <= 0) { return source; } if (!cutTop && !cutBottom && !cutLeft && !cutRight) { return source; } int width = source.getWidth(); int height = source.getHeight(); int x1 = 0; int y1 = 0; int x2 = width; int y2 = height; if (cutLeft) { x1 = MarginWidth; } if (cutRight) { x2 = width - MarginWidth; } if (cutTop) { y1 = MarginWidth; } if (cutBottom) { y2 = height - MarginWidth; } return CropTools.cropOutside(task, source, x1, y1, x2, y2); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage blurMarginsNoAlpha(FxTask task, BufferedImage source, int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_RGB; BufferedImage target = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; Color alphaColor = ColorConvertTools.alphaColor(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, alphaColor.getRGB()); continue; } iOpocity = jOpacity = 1.0F; if (i < blurWidth) { if (blurLeft) { iOpocity = 1.0F * i / blurWidth; } } else if (i > width - blurWidth) { if (blurRight) { iOpocity = 1.0F * (width - i) / blurWidth; } } if (j < blurWidth) { if (blurTop) { jOpacity = 1.0F * j / blurWidth; } } else if (j > height - blurWidth) { if (blurBottom) { jOpacity = 1.0F * (height - j) / blurWidth; } } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { target.setRGB(i, j, pixel); } else { Color color = ColorBlendTools.blendColor(new Color(pixel), opocity, alphaColor); target.setRGB(i, j, color.getRGB()); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage addMargins(FxTask task, BufferedImage source, Color addColor, int MarginWidth, boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) { try { if (source == null || MarginWidth <= 0) { return source; } if (!addTop && !addBottom && !addLeft && !addRight) { return source; } int width = source.getWidth(); int height = source.getHeight(); int totalWidth = width; int totalHegiht = height; int x = 0; int y = 0; if (addLeft) { totalWidth += MarginWidth; x = MarginWidth; } if (addRight) { totalWidth += MarginWidth; } if (addTop) { totalHegiht += MarginWidth; y = MarginWidth; } if (addBottom) { totalHegiht += MarginWidth; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(totalWidth, totalHegiht, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setColor(addColor); g.fillRect(0, 0, totalWidth, totalHegiht); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, width, height, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/tools/BufferedImageTools.java
released/MyBox/src/main/java/mara/mybox/image/tools/BufferedImageTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Arrays; import java.util.Base64; import java.util.Hashtable; import java.util.Map; import javax.imageio.ImageIO; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.tools.MessageDigestTools; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; import mara.mybox.value.FileExtensions; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class BufferedImageTools { public static enum Direction { Top, Bottom, Left, Right, LeftTop, RightBottom, LeftBottom, RightTop } public static class KeepRatioType { public static final int BaseOnWidth = 0; public static final int BaseOnHeight = 1; public static final int BaseOnLarger = 2; public static final int BaseOnSmaller = 3; public static final int None = 9; } public static BufferedImage addShadow(FxTask task, BufferedImage source, int shadowX, int shadowY, Color shadowColor, boolean isBlur) { try { if (source == null || shadowColor == null || (shadowX == 0 && shadowY == 0)) { return source; } int width = source.getWidth(); int height = source.getHeight(); boolean blend = !AlphaTools.hasAlpha(source); int imageType = blend ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage shadowImage = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; float shadowRed = shadowColor.getRed() / 255.0F; float shadowGreen = shadowColor.getGreen() / 255.0F; float shadowBlue = shadowColor.getBlue() / 255.0F; Color newColor; Color alphaColor = blend ? ColorConvertTools.alphaColor() : Colors.TRANSPARENT; int alphaPixel = alphaColor.getRGB(); int offsetX = Math.abs(shadowX); int offsetY = Math.abs(shadowY); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { shadowImage.setRGB(i, j, alphaPixel); continue; } if (isBlur) { iOpocity = jOpacity = 1.0F; if (i < offsetX) { iOpocity = 1.0F * i / offsetX; } else if (i > width - offsetX) { iOpocity = 1.0F * (width - i) / offsetX; } if (j < offsetY) { jOpacity = 1.0F * j / offsetY; } else if (j > height - offsetY) { jOpacity = 1.0F * (height - j) / offsetY; } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { newColor = shadowColor; } else if (blend) { newColor = ColorBlendTools.blendColor(shadowColor, opocity, alphaColor); } else { newColor = new Color(shadowRed, shadowGreen, shadowBlue, opocity); } } else { newColor = shadowColor; } shadowImage.setRGB(i, j, newColor.getRGB()); } } if (task != null && !task.isWorking()) { return null; } BufferedImage target = new BufferedImage(width + offsetX, height + offsetY, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); if (task != null && !task.isWorking()) { return null; } int x = shadowX > 0 ? 0 : -shadowX; int y = shadowY > 0 ? 0 : -shadowY; int sx = shadowX > 0 ? shadowX : 0; int sy = shadowY > 0 ? shadowY : 0; g.drawImage(shadowImage, sx, sy, null); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, null); g.dispose(); return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage setRound(FxTask task, BufferedImage source, int roundX, int roundY, Color bgColor) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, width, height); if (task != null && !task.isWorking()) { return null; } g.setClip(new RoundRectangle2D.Double(0, 0, width, height, roundX, roundY)); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, 0, 0, null); g.dispose(); return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } // https://stackoverflow.com/questions/3514158/how-do-you-clone-a-bufferedimage# public static BufferedImage clone(BufferedImage source) { if (source == null) { return null; } try { ColorModel cm = source.getColorModel(); Hashtable<String, Object> properties = null; String[] keys = source.getPropertyNames(); if (keys != null) { properties = new Hashtable<>(); for (String key : keys) { properties.put(key, source.getProperty(key)); } } return new BufferedImage(cm, source.copyData(null), cm.isAlphaPremultiplied(), properties) .getSubimage(0, 0, source.getWidth(), source.getHeight()); } catch (Exception e) { MyBoxLog.error(e); return null; } } // https://stackoverflow.com/questions/24038524/how-to-get-byte-from-javafx-imageview public static byte[] bytes(FxTask task, BufferedImage srcImage, String format) { byte[] bytes = null; try (ByteArrayOutputStream stream = new ByteArrayOutputStream();) { BufferedImage tmpImage = srcImage; if (!FileExtensions.AlphaImages.contains(format)) { tmpImage = AlphaTools.removeAlpha(task, srcImage); if (tmpImage == null) { return null; } } ImageIO.write(tmpImage, format, stream); bytes = stream.toByteArray(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } return bytes; } public static String base64(FxTask task, BufferedImage image, String format) { try { if (image == null || format == null) { return null; } Base64.Encoder encoder = Base64.getEncoder(); byte[] bytes = bytes(task, image, format); if (bytes == null) { return null; } return encoder.encodeToString(bytes); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static String base64(FxTask task, File file, String format) { try { if (file == null) { return null; } return base64(task, ImageFileReaders.readImage(task, file), format == null ? "jpg" : format); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static boolean sameByMD5(FxTask task, BufferedImage imageA, BufferedImage imageB) { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } byte[] bA = MessageDigestTools.MD5(task, imageA); if (bA == null || (task != null && !task.isWorking())) { return false; } byte[] bB = MessageDigestTools.MD5(task, imageB); if (bB == null || (task != null && !task.isWorking())) { return false; } return Arrays.equals(bA, bB); } // This way may be quicker than comparing digests public static boolean same(FxTask task, BufferedImage imageA, BufferedImage imageB) { try { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } int width = imageA.getWidth(), height = imageA.getHeight(); for (int y = 0; y < height / 2; y++) { if (task != null && !task.isWorking()) { return false; } for (int x = 0; x < width / 2; x++) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } for (int x = width - 1; x >= width / 2; x--) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } } for (int y = height - 1; y >= height / 2; y--) { if (task != null && !task.isWorking()) { return false; } for (int x = 0; x < width / 2; x++) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } for (int x = width - 1; x >= width / 2; x--) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } } return true; } catch (Exception e) { return false; } } // This way may be quicker than comparing digests public static boolean sameImage(FxTask task, BufferedImage imageA, BufferedImage imageB) { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } for (int y = 0; y < imageA.getHeight(); y++) { if (task != null && !task.isWorking()) { return false; } for (int x = 0; x < imageA.getWidth(); x++) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageB.getRGB(x, y)) { return false; } } } return true; } public static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); } public static BufferedImage createCompatibleImage(int width, int height) { return createCompatibleImage(width, height, Transparency.TRANSLUCENT); } public static BufferedImage createCompatibleImage(int width, int height, int transparency) { BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency); image.coerceData(true); return image; } public static BufferedImage applyRenderHints(BufferedImage srcImage, Map<RenderingHints.Key, Object> hints) { try { if (srcImage == null || hints == null) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); g.addRenderingHints(hints); g.drawImage(srcImage, 0, 0, width, height, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageGifFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageGifFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.gif.GIFImageMetadata; import com.github.jaiimageio.impl.plugins.gif.GIFImageWriter; import com.github.jaiimageio.impl.plugins.gif.GIFImageWriterSpi; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.ScaleTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import thridparty.GifDecoder; import thridparty.GifDecoder.GifImage; /** * @Author Mara * @CreateDate 2018-6-24 * * @Description * @License Apache License Version 2.0 */ public class ImageGifFile { public static GIFImageMetadata getGifMetadata(File file) { try { // ImageReaderSpi readerSpi = new GIFImageReaderSpi(); // GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) { ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); reader.setInput(iis, false); GIFImageMetadata metadata = (GIFImageMetadata) reader.getImageMetadata(0); reader.dispose(); return metadata; } } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } // https://stackoverflow.com/questions/22259714/arrayindexoutofboundsexception-4096-while-reading-gif-file // https://github.com/DhyanB/Open-Imaging public static BufferedImage readBrokenGifFile(FxTask task, ImageInformation imageInfo) { try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageInfo.getFile()))) { GifImage gif = GifDecoder.read(in); BufferedImage bufferedImage = gif.getFrame(imageInfo.getIndex()); if (task != null && !task.isWorking()) { return null; } return ImageFileReaders.adjust(task, imageInfo, bufferedImage); } catch (Exception e) { MyBoxLog.error(e.toString()); imageInfo.setError(e.toString()); return null; } } // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html#image public static ImageWriter getWriter() { GIFImageWriterSpi gifspi = new GIFImageWriterSpi(); GIFImageWriter writer = new GIFImageWriter(gifspi); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { GIFImageMetadata metaData; try { metaData = (GIFImageMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); } catch (Exception e) { MyBoxLog.error(e.toString()); metaData = null; } if (attributes.getDensity() > 0) { // Have not found the way to set density data in meta data of GIF format. } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void writeGifImageFile(BufferedImage image, ImageAttributes attributes, String outFile) { try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); try (ImageOutputStream out = ImageIO.createImageOutputStream(new File(outFile))) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static boolean getParaMeta(long duration, boolean loop, ImageWriteParam param, GIFImageMetadata metaData) { try { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType("LZW"); param.setCompressionQuality(1); String durationV; if (duration > 0) { durationV = duration / 10 + ""; } else { durationV = "100"; } String format = metaData.getNativeMetadataFormatName(); IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(format); IIOMetadataNode graphicsControlExtensionNode = new IIOMetadataNode("GraphicControlExtension"); graphicsControlExtensionNode.setAttribute("delayTime", durationV); graphicsControlExtensionNode.setAttribute("disposalMethod", "restoreToBackgroundColor"); graphicsControlExtensionNode.setAttribute("userInputFlag", "false"); graphicsControlExtensionNode.setAttribute("transparentColorFlag", "false"); graphicsControlExtensionNode.setAttribute("delayTime", durationV); graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0"); tree.appendChild(graphicsControlExtensionNode); if (loop) { IIOMetadataNode applicationExtensionsNode = new IIOMetadataNode("ApplicationExtensions"); IIOMetadataNode applicationExtensionNode = new IIOMetadataNode("ApplicationExtension"); applicationExtensionNode.setAttribute("applicationID", "NETSCAPE"); applicationExtensionNode.setAttribute("authenticationCode", "2.0"); byte[] k = {1, 0, 0}; applicationExtensionNode.setUserObject(k); applicationExtensionsNode.appendChild(applicationExtensionNode); tree.appendChild(applicationExtensionsNode); } metaData.mergeTree(format, tree); return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } // https://www.programcreek.com/java-api-examples/javax.imageio.ImageWriter // http://www.java2s.com/Code/Java/2D-Graphics-GUI/GiffileEncoder.htm // https://programtalk.com/python-examples/com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi/ // https://www.jianshu.com/p/df52f1511cf8 // http://giflib.sourceforge.net/whatsinagif/index.html public static String writeImages(FxTask task, List<ImageInformation> imagesInfo, File outFile, boolean loop, boolean keepSize, int width) { try { if (imagesInfo == null || imagesInfo.isEmpty() || outFile == null) { return "InvalidParameters"; } System.gc(); ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (ImageInformation info : imagesInfo) { if (task != null && !task.isWorking()) { return null; } BufferedImage bufferedImage = ImageInformation.readBufferedImage(task, info); // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); if (bufferedImage != null) { if (!keepSize) { bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width); } getParaMeta(info.getDuration(), loop, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); gifWriter.dispose(); out.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } return FileTools.override(tmpFile, outFile) ? "" : "Failed"; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static String writeImageFiles(FxTask task, List<File> srcFiles, File outFile, int duration, boolean deleteSource) { try { if (srcFiles == null || srcFiles.isEmpty() || outFile == null) { return "InvalidParameters"; } ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (File file : srcFiles) { if (task != null && !task.isWorking()) { return null; } BufferedImage bufferedImage = ImageFileReaders.readImage(task, file); if (bufferedImage != null) { // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); getParaMeta(duration, true, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); out.flush(); } gifWriter.dispose(); if (!FileTools.override(tmpFile, outFile)) { return "Failed"; } if (deleteSource) { for (File file : srcFiles) { FileDeleteTools.delete(file); } srcFiles.clear(); } return ""; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static String writeImages(FxTask task, List<BufferedImage> images, File outFile, int duration) { try { if (images == null || images.isEmpty() || outFile == null) { return "InvalidParameters"; } ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (BufferedImage bufferedImage : images) { if (task != null && !task.isWorking()) { return null; } if (bufferedImage != null) { // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); getParaMeta(duration, true, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); out.flush(); } gifWriter.dispose(); return FileTools.override(tmpFile, outFile) ? "" : "Failed"; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static void explainGifMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation info) { try { String format = "javax_imageio_gif_stream_1.0"; if (metaData.containsKey(format)) { Map<String, List<Map<String, Object>>> javax_imageio_gif_stream = metaData.get(format); if (javax_imageio_gif_stream.containsKey("Version")) { Map<String, Object> Version = javax_imageio_gif_stream.get("Version").get(0); if (Version.containsKey("value")) { info.setNativeAttribute("Version", (String) Version.get("value")); } } if (javax_imageio_gif_stream.containsKey("LogicalScreenDescriptor")) { Map<String, Object> LogicalScreenDescriptor = javax_imageio_gif_stream.get("LogicalScreenDescriptor").get(0); if (LogicalScreenDescriptor.containsKey("logicalScreenWidth")) { info.setNativeAttribute("logicalScreenWidth", Integer.valueOf((String) LogicalScreenDescriptor.get("logicalScreenWidth"))); } if (LogicalScreenDescriptor.containsKey("logicalScreenHeight")) { info.setNativeAttribute("logicalScreenHeight", Integer.valueOf((String) LogicalScreenDescriptor.get("logicalScreenHeight"))); } if (LogicalScreenDescriptor.containsKey("colorResolution")) { info.setNativeAttribute("colorResolution", Integer.valueOf((String) LogicalScreenDescriptor.get("colorResolution"))); } if (LogicalScreenDescriptor.containsKey("pixelAspectRatio")) { int v = Integer.parseInt((String) LogicalScreenDescriptor.get("pixelAspectRatio")); if (v == 0) { info.setNativeAttribute("pixelAspectRatio", 1); } else { info.setNativeAttribute("pixelAspectRatio", (v + 15.f) / 64); } } } if (javax_imageio_gif_stream.containsKey("GlobalColorTable")) { Map<String, Object> GlobalColorTable = javax_imageio_gif_stream.get("GlobalColorTable").get(0); if (GlobalColorTable.containsKey("sizeOfGlobalColorTable")) { info.setNativeAttribute("sizeOfGlobalColorTable", Integer.valueOf((String) GlobalColorTable.get("sizeOfGlobalColorTable"))); } if (GlobalColorTable.containsKey("backgroundColorIndex")) { info.setNativeAttribute("backgroundColorIndex", Integer.valueOf((String) GlobalColorTable.get("backgroundColorIndex"))); } if (GlobalColorTable.containsKey("sortFlag")) { info.setNativeAttribute("sortFlag", (String) GlobalColorTable.get("sortFlag")); } } if (javax_imageio_gif_stream.containsKey("stream_ColorTableEntry")) { List<Map<String, Object>> ColorTableEntryList = javax_imageio_gif_stream.get("ColorTableEntry"); if (ColorTableEntryList != null) { info.setNativeAttribute("stream_ColorTableEntryList", ColorTableEntryList.size()); // Extract data if need in future } } } format = "javax_imageio_gif_image_1.0"; if (metaData.containsKey(format)) { Map<String, List<Map<String, Object>>> javax_imageio_gif_image = metaData.get(format); if (javax_imageio_gif_image.containsKey("Version")) { Map<String, Object> ImageDescriptor = javax_imageio_gif_image.get("ImageDescriptor").get(0); if (ImageDescriptor.containsKey("imageLeftPosition")) { info.setNativeAttribute("imageLeftPosition", (String) ImageDescriptor.get("imageLeftPosition")); } if (ImageDescriptor.containsKey("imageTopPosition")) { info.setNativeAttribute("imageTopPosition", (String) ImageDescriptor.get("imageTopPosition")); } if (ImageDescriptor.containsKey("imageWidth")) { info.setNativeAttribute("imageWidth", (String) ImageDescriptor.get("imageWidth")); } if (ImageDescriptor.containsKey("imageHeight")) { info.setNativeAttribute("imageHeight", (String) ImageDescriptor.get("imageHeight")); } if (ImageDescriptor.containsKey("interlaceFlag")) { info.setNativeAttribute("interlaceFlag", (String) ImageDescriptor.get("interlaceFlag")); } } if (javax_imageio_gif_image.containsKey("ColorTableEntry")) { List<Map<String, Object>> ColorTableEntryList = javax_imageio_gif_image.get("ColorTableEntry"); if (ColorTableEntryList != null) { info.setNativeAttribute("ColorTableEntryList", ColorTableEntryList.size()); // Extract data if need in future } } if (javax_imageio_gif_image.containsKey("GraphicControlExtension")) { Map<String, Object> GraphicControlExtension = javax_imageio_gif_image.get("GraphicControlExtension").get(0); if (GraphicControlExtension.containsKey("disposalMethod")) { info.setNativeAttribute("disposalMethod", (String) GraphicControlExtension.get("disposalMethod")); } if (GraphicControlExtension.containsKey("userInputFlag")) { info.setNativeAttribute("userInputFlag", (String) GraphicControlExtension.get("userInputFlag")); } if (GraphicControlExtension.containsKey("transparentColorFlag")) { info.setNativeAttribute("transparentColorFlag", (String) GraphicControlExtension.get("transparentColorFlag")); } if (GraphicControlExtension.containsKey("delayTime")) { // in hundredths of a second info.setNativeAttribute("delayTime", GraphicControlExtension.get("delayTime")); try { int v = Integer.parseInt((String) GraphicControlExtension.get("delayTime")); info.setDuration(v * 10); } catch (Exception e) { } } if (GraphicControlExtension.containsKey("transparentColorIndex")) { info.setNativeAttribute("transparentColorIndex", (String) GraphicControlExtension.get("transparentColorIndex")); } } if (javax_imageio_gif_image.containsKey("PlainTextExtension")) { Map<String, Object> PlainTextExtension = javax_imageio_gif_image.get("PlainTextExtension").get(0); if (PlainTextExtension.containsKey("textGridLeft")) { info.setNativeAttribute("textGridLeft", PlainTextExtension.get("textGridLeft")); } if (PlainTextExtension.containsKey("textGridTop")) { info.setNativeAttribute("textGridTop", PlainTextExtension.get("textGridTop")); } if (PlainTextExtension.containsKey("textGridWidth")) { info.setNativeAttribute("textGridWidth", PlainTextExtension.get("textGridWidth")); } if (PlainTextExtension.containsKey("textGridHeight")) { info.setNativeAttribute("textGridHeight", PlainTextExtension.get("textGridHeight")); } if (PlainTextExtension.containsKey("characterCellWidth")) { info.setNativeAttribute("characterCellWidth", PlainTextExtension.get("characterCellWidth")); } if (PlainTextExtension.containsKey("characterCellHeight")) { info.setNativeAttribute("characterCellHeight", PlainTextExtension.get("characterCellHeight")); } if (PlainTextExtension.containsKey("textForegroundColor")) { info.setNativeAttribute("textForegroundColor", PlainTextExtension.get("textForegroundColor")); } if (PlainTextExtension.containsKey("textBackgroundColor")) { info.setNativeAttribute("textBackgroundColor", PlainTextExtension.get("textBackgroundColor")); } } if (javax_imageio_gif_image.containsKey("ApplicationExtensions")) { Map<String, Object> ApplicationExtensions = javax_imageio_gif_image.get("ApplicationExtensions").get(0); if (ApplicationExtensions.containsKey("applicationID")) { info.setNativeAttribute("applicationID", ApplicationExtensions.get("applicationID")); } if (ApplicationExtensions.containsKey("authenticationCode")) { info.setNativeAttribute("authenticationCode", ApplicationExtensions.get("authenticationCode")); } } if (javax_imageio_gif_image.containsKey("CommentExtensions")) { Map<String, Object> CommentExtensions = javax_imageio_gif_image.get("CommentExtensions").get(0); if (CommentExtensions.containsKey("value")) { info.setNativeAttribute("CommentExtensions", CommentExtensions.get("value")); } } } } catch (Exception e) { } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageBmpFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageBmpFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.bmp.BMPImageReader; import com.github.jaiimageio.impl.plugins.bmp.BMPImageReaderSpi; import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriter; import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriterSpi; import com.github.jaiimageio.impl.plugins.bmp.BMPMetadata; import com.github.jaiimageio.plugins.bmp.BMPImageWriteParam; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.tools.ImageConvertTools; import static mara.mybox.image.tools.ImageConvertTools.dpi2dpm; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; /** * @Author Mara * @CreateDate 2018-6-19 * @Description * @License Apache License Version 2.0 */ // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/bmp_metadata.html public class ImageBmpFile { public static String[] getBmpCompressionTypes() { return new BMPImageWriteParam(null).getCompressionTypes(); } public static ImageWriter getWriter() { // BMP's meta data can not be modified and read correctly if standard classes are used. // So classes in plugins are used. BMPImageWriterSpi spi = new BMPImageWriterSpi(); BMPImageWriter writer = new BMPImageWriter(spi); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { BMPImageWriteParam param = (BMPImageWriteParam) writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { BMPMetadata metaData = (BMPMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metaData != null && !metaData.isReadOnly() && attributes != null && attributes.getDensity() > 0) { String format = metaData.getNativeMetadataFormatName(); // "com_sun_media_imageio_plugins_bmp_image_1.0" int dpm = dpi2dpm(attributes.getDensity()); // If set nodes' attributes in normal way, error will be popped about "Meta Data is read only" // By setting its fields, the class will write resolution data under standard format "javax_imageio_1.0" // but leave itself's section as empty~ Anyway, the data is record. metaData.xPixelsPerMeter = dpm; metaData.yPixelsPerMeter = dpm; metaData.palette = null; // Error will happen if not define this for Black-white bmp. IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(format); metaData.mergeTree(format, tree); } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writeBmpImageFile(FxTask task, BufferedImage srcimage, ImageAttributes attributes, File file) { BufferedImage image = AlphaTools.removeAlpha(task, srcimage); try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); return FileTools.override(tmpFile, file); } catch (Exception e) { try { return ImageIO.write(image, attributes.getImageFormat(), file); } catch (Exception e2) { return false; } } } public static BMPMetadata getBmpIIOMetadata(File file) { try { BMPImageReader reader = new BMPImageReader(new BMPImageReaderSpi()); try (ImageInputStream iis = ImageIO.createImageInputStream(file)) { reader.setInput(iis, false); BMPMetadata metadata = (BMPMetadata) reader.getImageMetadata(0); reader.dispose(); return metadata; } } catch (Exception e) { // MyBoxLog.error(e.toString()); return null; } } public static void explainBmpMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation info) { try { String format = "com_sun_media_imageio_plugins_bmp_image_1.0"; if (!metaData.containsKey(format)) { return; } Map<String, List<Map<String, Object>>> javax_imageio_bmp = metaData.get(format); if (javax_imageio_bmp.containsKey("Width")) { Map<String, Object> Width = javax_imageio_bmp.get("Width").get(0); if (Width.containsKey("value")) { info.setWidth(Integer.parseInt((String) Width.get("value"))); } } if (javax_imageio_bmp.containsKey("Height")) { Map<String, Object> Height = javax_imageio_bmp.get("Height").get(0); if (Height.containsKey("value")) { info.setHeight(Integer.parseInt((String) Height.get("value"))); } } if (javax_imageio_bmp.containsKey("X")) { // PixelsPerMeter Map<String, Object> X = javax_imageio_bmp.get("X").get(0); if (X.containsKey("value")) { info.setXDpi(ImageConvertTools.dpm2dpi(Integer.parseInt((String) X.get("value")))); } } if (javax_imageio_bmp.containsKey("Y")) { // PixelsPerMeter Map<String, Object> Y = javax_imageio_bmp.get("Y").get(0); if (Y.containsKey("value")) { info.setYDpi(ImageConvertTools.dpm2dpi(Integer.parseInt((String) Y.get("value")))); } } if (javax_imageio_bmp.containsKey("BitsPerPixel")) { Map<String, Object> BitsPerPixel = javax_imageio_bmp.get("BitsPerPixel").get(0); if (BitsPerPixel.containsKey("value")) { info.setBitDepth(Integer.parseInt((String) BitsPerPixel.get("value"))); } } if (javax_imageio_bmp.containsKey("Compression")) { Map<String, Object> Compression = javax_imageio_bmp.get("Compression").get(0); if (Compression.containsKey("value")) { info.setCompressionType((String) Compression.get("value")); } } } catch (Exception e) { } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageRawFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageRawFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.raw.RawImageReader; import com.github.jaiimageio.impl.plugins.raw.RawImageReaderSpi; import com.github.jaiimageio.impl.plugins.raw.RawImageWriteParam; import com.github.jaiimageio.impl.plugins.raw.RawImageWriter; import com.github.jaiimageio.impl.plugins.raw.RawImageWriterSpi; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.image.data.ImageAttributes; import mara.mybox.tools.FileTools; import mara.mybox.tools.FileTmpTools; /** * @Author Mara * @CreateDate 2018-6-19 * * @Description * @License Apache License Version 2.0 */ public class ImageRawFile { public static ImageWriter getWriter() { RawImageWriterSpi spi = new RawImageWriterSpi(); RawImageWriter writer = new RawImageWriter(spi); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { RawImageWriteParam param = (RawImageWriteParam) writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { return writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writeRawImageFile(BufferedImage image, ImageAttributes attributes, File file) { try { if (file == null) { return false; } ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); File tmpFile = FileTmpTools.getTempFile(); try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(null, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static BufferedImage readRawData(File file) { try { RawImageReaderSpi tiffspi = new RawImageReaderSpi(); RawImageReader reader = new RawImageReader(tiffspi); byte[] rawData; try ( BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file))) { rawData = new byte[fileInput.available()]; fileInput.read(rawData); fileInput.close(); // convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(rawData); reader.setInput(in); } return reader.read(0); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static File readRawData2(File file) { try { byte[] rawData; try ( BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file))) { rawData = new byte[fileInput.available()]; fileInput.read(rawData); } BufferedImage image; try ( InputStream in = new ByteArrayInputStream(rawData)) { image = ImageIO.read(in); } File newFile = new File(file.getPath() + ".png"); ImageIO.write(image, "png", newFile); return newFile; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageWbmpFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageWbmpFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.wbmp.WBMPImageReader; import com.github.jaiimageio.impl.plugins.wbmp.WBMPImageReaderSpi; import com.github.jaiimageio.impl.plugins.wbmp.WBMPMetadata; import java.io.File; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2018-6-24 * @Description * @License Apache License Version 2.0 */ public class ImageWbmpFile { public static WBMPMetadata getWbmpMetadata(File file) { try { WBMPMetadata metadata; WBMPImageReader reader = new WBMPImageReader(new WBMPImageReaderSpi()); try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { reader.setInput(iis, false); metadata = (WBMPMetadata) reader.getImageMetadata(0); reader.dispose(); } return metadata; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageFileWriters.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageFileWriters.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.gif.GIFImageMetadata; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataFormatImpl; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageBinary; import mara.mybox.image.data.ImageFileInformation; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.image.tools.ScaleTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import thridparty.image4j.ICOEncoder; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * * @Description * @License Apache License Version 2.0 */ // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html public class ImageFileWriters { public static boolean saveAs(FxTask task, File srcFile, String targetFile) { try { BufferedImage image = ImageFileReaders.readImage(task, srcFile); if (image == null) { return false; } return writeImageFile(task, image, targetFile); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean saveAs(FxTask task, File srcFile, File targetFile) { try { return saveAs(task, srcFile, targetFile.getAbsolutePath()); } catch (Exception e) { return false; } } public static boolean writeImageFile(FxTask task, BufferedImage image, File targetFile) { try { return writeImageFile(task, image, targetFile.getAbsolutePath()); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean writeImageFile(FxTask task, BufferedImage image, String targetFile) { try { return writeImageFile(task, image, FileNameTools.ext(targetFile), targetFile); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean writeImageFile(FxTask task, BufferedImage image, String format, String targetFile) { if (image == null || targetFile == null) { return false; } try { if (format == null || !FileExtensions.SupportedImages.contains(format)) { format = FileNameTools.ext(targetFile); } format = format.toLowerCase(); ImageAttributes attributes = new ImageAttributes(image, format); switch (format) { case "jpx": case "jpeg2000": case "jpeg 2000": case "jp2": case "jpm": return ImageIO.write(AlphaTools.removeAlpha(task, image), "JPEG2000", new File(targetFile)); case "wbmp": image = ImageBinary.byteBinary(task, image); break; } return writeImageFile(task, image, attributes, targetFile); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static ImageAttributes attributes(BufferedImage image, String format) { try { if (format == null || !FileExtensions.SupportedImages.contains(format)) { format = "png"; } format = format.toLowerCase(); ImageAttributes attributes = new ImageAttributes(); attributes.setImageFormat(format); switch (format) { case "jpg": case "jpeg": attributes.setCompressionType("JPEG"); break; case "gif": attributes.setCompressionType("LZW"); break; case "tif": case "tiff": if (image != null && image.getType() == BufferedImage.TYPE_BYTE_BINARY) { attributes.setCompressionType("CCITT T.6"); } else { attributes.setCompressionType("Deflate"); } break; case "bmp": attributes.setCompressionType("BI_RGB"); break; } attributes.setQuality(100); return attributes; } catch (Exception e) { MyBoxLog.debug(e); return null; } } // Not convert color space public static boolean writeImageFile(FxTask task, BufferedImage srcImage, ImageAttributes attributes, String targetFile) { if (srcImage == null || targetFile == null) { return false; } if (attributes == null) { return writeImageFile(task, srcImage, targetFile); } try { String targetFormat = attributes.getImageFormat().toLowerCase(); if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) { return writeIcon(task, srcImage, attributes.getWidth(), new File(targetFile)); } BufferedImage targetImage = AlphaTools.checkAlpha(task, srcImage, targetFormat); if (targetImage == null || (task != null && !task.isWorking())) { return false; } ImageWriter writer = getWriter(targetFormat); ImageWriteParam param = getWriterParam(attributes, writer); IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, targetImage, writer, param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(metaData, new IIOImage(targetImage, null, metaData), param); out.flush(); writer.dispose(); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } if (task != null && !task.isWorking()) { return false; } File file = new File(targetFile); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean writeIcon(FxTask task, BufferedImage image, int width, File targetFile) { try { if (image == null || targetFile == null) { return false; } int targetWidth = width; if (targetWidth <= 0) { targetWidth = Math.min(512, image.getWidth()); } BufferedImage scaled = ScaleTools.scaleImageWidthKeep(image, targetWidth); if (task != null && !task.isWorking()) { return false; } ICOEncoder.write(scaled, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static String writeFrame(FxTask task, File sourcefile, int frameIndex, BufferedImage frameImage) { return writeFrame(task, sourcefile, frameIndex, frameImage, sourcefile, null); } // Convert color space if inAttributes is not null public static String writeFrame(FxTask task, File sourcefile, int frameIndex, BufferedImage frameImage, File targetFile, ImageAttributes inAttributes) { try { if (frameImage == null || sourcefile == null || !sourcefile.exists() || targetFile == null || frameIndex < 0) { return "InvalidParameters"; } String targetFormat; ImageAttributes targetAttributes = inAttributes; if (targetAttributes == null) { targetFormat = FileNameTools.ext(targetFile.getName()).toLowerCase(); targetAttributes = attributes(frameImage, targetFormat); } else { targetFormat = inAttributes.getImageFormat().toLowerCase(); } if (!FileExtensions.MultiFramesImages.contains(targetFormat)) { return writeImageFile(task, frameImage, targetAttributes, targetFile.getAbsolutePath()) ? null : "Failed"; } List<ImageInformation> gifInfos = null; if ("gif".equals(targetFormat)) { ImageFileInformation imageFileInformation = ImageFileReaders.readImageFileMetaData(task, sourcefile); if (task != null && !task.isWorking()) { return message("Cancelled"); } if (imageFileInformation == null || imageFileInformation.getImagesInformation() == null) { return "InvalidData"; } gifInfos = imageFileInformation.getImagesInformation(); } File tmpFile = FileTmpTools.getTempFile(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(sourcefile)))) { ImageReader reader = ImageFileReaders.getReader(iis, FileNameTools.ext(sourcefile.getName())); if (reader == null) { return "InvalidData"; } reader.setInput(iis, false); int size = reader.getNumImages(true); try (ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)))) { int readIndex = 0, duration; ImageWriter writer = getWriter(targetFormat); if (writer == null) { return "InvalidData"; } writer.setOutput(out); ImageWriteParam param = getWriterParam(targetAttributes, writer); writer.prepareWriteSequence(null); ImageInformation info = new ImageInformation(sourcefile); while (readIndex < size) { if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return message("Cancelled"); } BufferedImage bufferedImage; if (readIndex == frameIndex) { bufferedImage = frameImage; } else { try { bufferedImage = reader.read(readIndex); } catch (Exception e) { if (e.toString().contains("java.lang.IndexOutOfBoundsException")) { break; } bufferedImage = ImageFileReaders.readBrokenImage(task, e, info.setIndex(readIndex)); } } if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return message("Cancelled"); } if (bufferedImage == null) { break; } BufferedImage targetFrame = bufferedImage; IIOMetadata metaData; if (inAttributes != null) { targetFrame = ImageConvertTools.convertColorSpace(task, targetFrame, inAttributes); } else { targetFrame = AlphaTools.checkAlpha(task, bufferedImage, targetFormat); } if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return message("Cancelled"); } if (targetFrame == null) { break; } metaData = getWriterMetaData(targetFormat, targetAttributes, targetFrame, writer, param); if (gifInfos != null) { duration = 500; try { Object d = gifInfos.get(readIndex).getNativeAttribute("delayTime"); if (d != null) { duration = Integer.parseInt((String) d) * 10; } } catch (Exception e) { } GIFImageMetadata gifMetaData = (GIFImageMetadata) metaData; ImageGifFile.getParaMeta(duration, true, param, gifMetaData); } writer.writeToSequence(new IIOImage(targetFrame, null, metaData), param); readIndex++; } writer.endWriteSequence(); out.flush(); writer.dispose(); } catch (Exception e) { MyBoxLog.error(e.toString()); } reader.dispose(); } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } if (task != null && !task.isWorking()) { return message("Cancelled"); } if (FileTools.override(tmpFile, targetFile)) { return null; } else { return "Failed"; } } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static ImageWriter getWriter(String targetFormat) { if (targetFormat == null) { return null; } try { ImageWriter writer; switch (targetFormat.toLowerCase()) { case "png": writer = ImagePngFile.getWriter(); break; case "jpg": case "jpeg": writer = ImageJpgFile.getWriter(); break; case "tif": case "tiff": writer = ImageTiffFile.getWriter(); break; case "raw": writer = ImageRawFile.getWriter(); break; case "bmp": writer = ImageBmpFile.getWriter(); break; case "gif": writer = ImageGifFile.getWriter(); break; default: return ImageIO.getImageWritersByFormatName(targetFormat).next(); } return writer; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static ImageWriteParam getWriterParam(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } else { String[] compressionTypes = param.getCompressionTypes(); if (compressionTypes != null) { param.setCompressionType(compressionTypes[0]); } } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMetaData(String targetFormat, ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData; switch (targetFormat) { case "png": metaData = ImagePngFile.getWriterMeta(attributes, image, writer, param); break; case "gif": metaData = ImageGifFile.getWriterMeta(attributes, image, writer, param); break; case "jpg": case "jpeg": metaData = ImageJpgFile.getWriterMeta(attributes, image, writer, param); break; case "tif": case "tiff": metaData = ImageTiffFile.getWriterMeta(attributes, image, writer, param); break; case "bmp": metaData = ImageBmpFile.getWriterMeta(attributes, image, writer, param); break; default: metaData = getWriterMetaData(attributes, image, writer, param); } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMetaData(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metaData == null || metaData.isReadOnly() || attributes == null || !metaData.isStandardMetadataFormatSupported()) { return metaData; } // This standard mothod does not write density into meta data of the image. // If density data need be written, then use methods defined for different image format but not this method. if (attributes.getDensity() > 0) { try { float pixelSizeMm = 25.4f / attributes.getDensity(); String metaFormat = IIOMetadataFormatImpl.standardMetadataFormatName; // "javax_imageio_1.0" IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(metaFormat); IIOMetadataNode Dimension = new IIOMetadataNode("Dimension"); IIOMetadataNode HorizontalPixelSize = new IIOMetadataNode("HorizontalPixelSize"); HorizontalPixelSize.setAttribute("value", pixelSizeMm + ""); Dimension.appendChild(HorizontalPixelSize); IIOMetadataNode VerticalPixelSize = new IIOMetadataNode("VerticalPixelSize"); VerticalPixelSize.setAttribute("value", pixelSizeMm + ""); Dimension.appendChild(VerticalPixelSize); tree.appendChild(Dimension); metaData.mergeTree(metaFormat, tree); } catch (Exception e) { // MyBoxLog.error(e.toString()); } } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageFileReaders.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageFileReaders.java
package mara.mybox.image.file; import java.awt.Rectangle; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageInputStream; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.image.data.ImageColor; import static mara.mybox.image.tools.ImageConvertTools.pixelSizeMm2dpi; import mara.mybox.image.data.ImageFileInformation; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.ScaleTools; import mara.mybox.color.ColorBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.AppVariables.ImageHints; import static mara.mybox.value.Languages.message; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import thridparty.image4j.ICODecoder; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html public class ImageFileReaders { public static ImageReader getReader(ImageInputStream iis, String format) { try { Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers == null || !readers.hasNext()) { return getReader(format); } return getReader(readers); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageReader getReader(String format) { try { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format.toLowerCase()); return getReader(readers); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageReader getReader(Iterator<ImageReader> readers) { try { if (readers == null || !readers.hasNext()) { return null; } ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (!reader.getClass().toString().contains("TIFFImageReader") || reader instanceof com.github.jaiimageio.impl.plugins.tiff.TIFFImageReader) { return reader; } } return reader; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static BufferedImage readImage(FxTask task, File file) { ImageInformation readInfo = new ImageInformation(file); return readFrame(task, readInfo); } public static BufferedImage readImage(FxTask task, File file, int width) { ImageInformation imageInfo = new ImageInformation(file); imageInfo.setRequiredWidth(width); return readFrame(task, imageInfo); } public static BufferedImage readFrame(FxTask task, File file, int index) { ImageInformation imageInfo = new ImageInformation(file); imageInfo.setIndex(index); return readFrame(task, imageInfo); } public static BufferedImage readFrame(FxTask task, ImageInformation imageInfo) { if (imageInfo == null) { return null; } File file = imageInfo.getFile(); if (file == null) { return null; } String format = imageInfo.getImageFormat(); if (task != null) { task.setInfo(message("File") + ": " + file); task.setInfo(message("FileSize") + ": " + FileTools.showFileSize(file.length())); task.setInfo(message("Format") + ": " + format); } if ("ico".equals(format) || "icon".equals(format)) { return readIcon(task, imageInfo); } BufferedImage bufferedImage = null; try (ImageInputStream iis = ImageIO.createImageInputStream( new BufferedInputStream(new FileInputStream(file)))) { ImageReader reader = getReader(iis, format); if (reader == null) { return null; } reader.setInput(iis, true, true); if (task != null && !task.isWorking()) { return null; } bufferedImage = readFrame(task, reader, imageInfo); reader.dispose(); } catch (Exception e) { imageInfo.setError(e.toString()); } return bufferedImage; } public static BufferedImage readFrame(FxTask task, ImageReader reader, ImageInformation imageInfo) { if (reader == null || imageInfo == null) { return null; } try { double infoWidth = imageInfo.getWidth(); double requiredWidth = imageInfo.getRequiredWidth(); ImageReadParam param = reader.getDefaultReadParam(); Rectangle region = imageInfo.getIntRegion(); int xscale = imageInfo.getXscale(); if (xscale < 1) { xscale = 1; } int yscale = imageInfo.getYscale(); if (yscale < 1) { yscale = 1; } if (region != null) { param.setSourceRegion(region); if (task != null) { task.setInfo(message("Region") + ": " + region.toString()); } } else if (requiredWidth > 0 && infoWidth > requiredWidth && xscale <= 1 && yscale <= 1) { xscale = (int) Math.ceil(infoWidth / requiredWidth); yscale = xscale; } if (xscale > 1 || yscale > 1) { param.setSourceSubsampling(xscale, yscale, 0, 0); if (task != null) { task.setInfo(message("Scale") + ": " + " xscale=" + xscale + " yscale= " + yscale); } } else if (region == null) { ImageInformation.checkMem(task, imageInfo); int sampleScale = imageInfo.getSampleScale(); if (sampleScale > 1) { if (task != null) { task.setInfo("sampleScale: " + sampleScale); } return null; } } BufferedImage bufferedImage; try { if (task != null) { task.setInfo(message("Reading") + ": " + message("Frame") + " " + imageInfo.getIndex()); } bufferedImage = reader.read(imageInfo.getIndex(), param); if (bufferedImage == null) { return null; } if (task != null && !task.isWorking()) { return null; } imageInfo.setImageType(bufferedImage.getType()); if (requiredWidth > 0 && bufferedImage.getWidth() != requiredWidth) { if (task != null) { task.setInfo(message("Scale") + ": " + message("Width") + " " + requiredWidth); } bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, (int) requiredWidth); } else if (ImageHints != null) { bufferedImage = BufferedImageTools.applyRenderHints(bufferedImage, ImageHints); } return bufferedImage; } catch (Exception e) { if (task != null) { task.setInfo(message("Error") + ": " + e.toString()); } return readBrokenImage(task, e, imageInfo); } } catch (Exception e) { imageInfo.setError(e.toString()); return null; } } public static ImageInformation makeInfo(FxTask task, File file, int width) { ImageInformation readInfo = new ImageInformation(file); readInfo.setRequiredWidth(width); return makeInfo(task, readInfo, false); } public static ImageInformation makeInfo(FxTask task, ImageInformation readInfo, boolean onlyInformation) { try { if (readInfo == null) { return null; } File file = readInfo.getFile(); if (file == null) { return null; } ImageFileInformation fileInfo = null; ImageInformation imageInfo = null; int index = readInfo.getIndex(); int requiredWidth = (int) readInfo.getRequiredWidth(); if (task != null) { task.setInfo(message("File") + ": " + file); task.setInfo(message("FileSize") + ": " + FileTools.showFileSize(file.length())); task.setInfo(message("Frame") + ": " + (index + 1)); if (requiredWidth > 0) { task.setInfo(message("LoadWidth") + ": " + requiredWidth); } } String format = readInfo.getImageFormat(); if ("ico".equals(format) || "icon".equals(format)) { if (fileInfo == null) { fileInfo = new ImageFileInformation(file); ImageFileReaders.readImageFileMetaData(task, null, fileInfo); } if (task != null && !task.isWorking()) { return null; } if (fileInfo.getImagesInformation() == null) { return null; } int framesNumber = fileInfo.getImagesInformation().size(); if (task != null) { task.setInfo(message("FramesNumber") + ": " + framesNumber); } if (framesNumber > 0 && index < framesNumber) { imageInfo = fileInfo.getImagesInformation().get(index); if (task != null) { task.setInfo(message("Pixels") + ": " + (int) imageInfo.getWidth() + "x" + (int) imageInfo.getHeight()); } if (!onlyInformation) { if (task != null) { task.setInfo(message("Reading") + ": " + message("Frame") + " " + index + "/" + framesNumber); } imageInfo.setRequiredWidth(requiredWidth); BufferedImage bufferedImage = readIcon(task, imageInfo); if (task != null && !task.isWorking()) { return null; } imageInfo.loadBufferedImage(bufferedImage); } } } else { try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) { ImageReader reader = getReader(iis, format); if (reader != null) { reader.setInput(iis, false, false); fileInfo = new ImageFileInformation(file); if (task != null) { task.setInfo(message("Reading") + ": " + message("MetaData")); } ImageFileReaders.readImageFileMetaData(task, reader, fileInfo); if (task != null && !task.isWorking()) { return null; } if (fileInfo.getImagesInformation() == null) { return null; } int framesNumber = fileInfo.getImagesInformation().size(); if (task != null) { task.setInfo(message("FramesNumber") + ": " + framesNumber); } if (framesNumber > 0 && index < framesNumber) { imageInfo = fileInfo.getImagesInformation().get(index); if (task != null) { task.setInfo(message("Pixels") + ": " + (int) imageInfo.getWidth() + "x" + (int) imageInfo.getHeight()); } if (!onlyInformation) { if (task != null) { task.setInfo(message("Reading") + ": " + message("Frame") + " " + index + "/" + framesNumber); } imageInfo.setRequiredWidth(requiredWidth); BufferedImage bufferedImage = readFrame(task, reader, imageInfo); if (task != null && !task.isWorking()) { return null; } imageInfo.loadBufferedImage(bufferedImage); } } reader.dispose(); } else { if (task != null) { task.setError("Fail to get reader"); } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } return imageInfo; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } public static BufferedImage readIcon(FxTask task, File srcFile) { return readIcon(task, srcFile, 0); } public static BufferedImage readIcon(FxTask task, File srcFile, int index) { try { if (srcFile == null || !srcFile.exists()) { return null; } List<BufferedImage> frames = ICODecoder.read(srcFile); if (frames == null || frames.isEmpty()) { return null; } return frames.get(index >= 0 && index < frames.size() ? index : 0); } catch (Exception e) { String ex = e.toString() + ": " + srcFile; if (task != null) { task.setError(ex); } else { MyBoxLog.error(ex); } return null; } } public static BufferedImage readIcon(FxTask task, ImageInformation imageInfo) { try { BufferedImage bufferedImage = readIcon(task, imageInfo.getFile(), imageInfo.getIndex()); if (task != null && !task.isWorking()) { return null; } return adjust(task, imageInfo, bufferedImage); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } // call this only when region and scale is not handled when create bufferedImage public static BufferedImage adjust(FxTask task, ImageInformation imageInfo, BufferedImage bufferedImage) { try { if (imageInfo == null || bufferedImage == null) { return bufferedImage; } int requiredWidth = (int) imageInfo.getRequiredWidth(); int bmWidth = bufferedImage.getWidth(); int xscale = imageInfo.getXscale(); int yscale = imageInfo.getYscale(); Rectangle region = imageInfo.getIntRegion(); if (region == null) { if (xscale != 1 || yscale != 1) { bufferedImage = ScaleTools.scaleImageByScale(bufferedImage, xscale, yscale); } else if (requiredWidth > 0 && bmWidth != requiredWidth) { bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, requiredWidth); } } else { if (xscale != 1 || yscale != 1) { bufferedImage = mara.mybox.image.data.CropTools.sample(task, bufferedImage, imageInfo.getRegion(), xscale, yscale); } else { bufferedImage = mara.mybox.image.data.CropTools.sample(task, bufferedImage, imageInfo.getRegion(), requiredWidth); } } return bufferedImage; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } /* Broken image */ public static BufferedImage readBrokenImage(FxTask task, Exception e, ImageInformation imageInfo) { BufferedImage image = null; try { File file = imageInfo.getFile(); if (e == null || file == null) { return null; } String format = FileNameTools.ext(file.getName()).toLowerCase(); if (task != null) { task.setInfo("Reading broken image: " + format); } switch (format) { case "gif": // Read Gif with JDK api normally. When broken, use DhyanB's API. // if (e.toString().contains("java.lang.ArrayIndexOutOfBoundsException: 4096")) { image = ImageGifFile.readBrokenGifFile(task, imageInfo); // if (e.toString().contains("java.lang.ArrayIndexOutOfBoundsException")) { // image = ImageGifFile.readBrokenGifFile(imageInfo); // } break; case "jpg": case "jpeg": image = ImageJpgFile.readBrokenJpgFile(task, imageInfo); // if (e.toString().contains("Unsupported Image Type")) { // image = ImageJpgFile.readBrokenJpgFile(imageInfo); // } break; default: if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } catch (Exception ex) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } return image; } /* Meta data */ public static ImageFileInformation readImageFileMetaData(FxTask task, String fileName) { return readImageFileMetaData(task, new File(fileName)); } public static ImageFileInformation readImageFileMetaData(FxTask task, File file) { if (file == null || !file.exists() || !file.isFile()) { return null; } if (task != null) { task.setInfo(message("ReadingMedia...") + ": " + file); } ImageFileInformation fileInfo = new ImageFileInformation(file); String format = fileInfo.getImageFormat(); if ("ico".equals(format) || "icon".equals(format)) { fileInfo = ImageFileInformation.readIconFile(task, file); } else { try (ImageInputStream iis = ImageIO.createImageInputStream( new BufferedInputStream(new FileInputStream(file)))) { ImageReader reader = getReader(iis, format); if (reader == null) { return null; } reader.setInput(iis, false, false); readImageFileMetaData(task, reader, fileInfo); reader.dispose(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } return fileInfo; } public static boolean readImageFileMetaData(FxTask task, ImageReader reader, ImageFileInformation fileInfo) { try { if (fileInfo == null) { return false; } String targetFormat = fileInfo.getImageFormat(); File file = fileInfo.getFile(); List<ImageInformation> imagesInfo = new ArrayList<>(); if (reader == null) { if (task != null) { task.setInfo("fail to get reader"); } fileInfo.setNumberOfImages(1); ImageInformation imageInfo = ImageInformation.create(targetFormat, file); imageInfo.setImageFileInformation(fileInfo); imageInfo.setImageFormat(targetFormat); imageInfo.setFile(file); imageInfo.setCreateTime(fileInfo.getCreateTime()); imageInfo.setModifyTime(fileInfo.getModifyTime()); imageInfo.setFileSize(fileInfo.getFileSize()); imageInfo.setIndex(0); ImageInformation.checkMem(task, imageInfo); imagesInfo.add(imageInfo); fileInfo.setImagesInformation(imagesInfo); fileInfo.setImageInformation(imageInfo); return true; } String format = reader.getFormatName().toLowerCase(); fileInfo.setImageFormat(format); int num = reader.getNumImages(true); fileInfo.setNumberOfImages(num); if (task != null) { task.setInfo("Number Of Images: " + num); } ImageInformation imageInfo; for (int i = 0; i < num; ++i) { if (task != null && !task.isWorking()) { return false; } if (task != null) { task.setInfo(message("Handle") + ": " + i + "/" + num); } imageInfo = ImageInformation.create(format, file); imageInfo.setImageFileInformation(fileInfo); imageInfo.setImageFormat(format); imageInfo.setFile(file); imageInfo.setCreateTime(fileInfo.getCreateTime()); imageInfo.setModifyTime(fileInfo.getModifyTime()); imageInfo.setFileSize(fileInfo.getFileSize()); imageInfo.setWidth(reader.getWidth(i)); imageInfo.setHeight(reader.getHeight(i)); imageInfo.setPixelAspectRatio(reader.getAspectRatio(i)); imageInfo.setIsMultipleFrames(num > 1); imageInfo.setIsTiled(reader.isImageTiled(i)); imageInfo.setIndex(i); Iterator<ImageTypeSpecifier> types = reader.getImageTypes(i); List<ImageTypeSpecifier> typesValue = new ArrayList<>(); if (types != null) { while (types.hasNext()) { if (task != null && !task.isWorking()) { return false; } ImageTypeSpecifier t = types.next(); typesValue.add(t); if (task != null) { task.setInfo("ImageTypeSpecifier : " + t.getClass()); } } ImageTypeSpecifier imageType = reader.getRawImageType(i); ColorModel colorModel = null; if (imageType != null) { imageInfo.setRawImageType(imageType); colorModel = imageType.getColorModel(); } if (colorModel == null) { if (!typesValue.isEmpty()) { colorModel = typesValue.get(0).getColorModel(); } } if (colorModel != null) { ColorSpace colorSpace = colorModel.getColorSpace(); imageInfo.setColorSpace(ColorBase.colorSpaceType(colorSpace.getType())); imageInfo.setColorChannels(colorModel.getNumComponents()); imageInfo.setBitDepth(colorModel.getPixelSize()); } } imageInfo.setImageTypeSpecifiers(typesValue); try { imageInfo.setPixelAspectRatio(reader.getAspectRatio(i)); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } try { imageInfo.setHasThumbnails(reader.hasThumbnails(i)); imageInfo.setNumberOfThumbnails(reader.getNumThumbnails(i)); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } try { readImageMetaData(task, format, imageInfo, reader.getImageMetadata(i)); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } ImageInformation.checkMem(task, imageInfo); imagesInfo.add(imageInfo); } fileInfo.setImagesInformation(imagesInfo); if (!imagesInfo.isEmpty()) { fileInfo.setImageInformation(imagesInfo.get(0)); } return task == null || task.isWorking(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } public static boolean readImageMetaData(FxTask task, String format, ImageInformation imageInfo, IIOMetadata iioMetaData) { try { if (imageInfo == null || iioMetaData == null) { return false; } if (task != null) { task.setInfo("read Image Meta Data : " + format); } StringBuilder metaDataXml = new StringBuilder(); String[] formatNames = iioMetaData.getMetadataFormatNames(); Map<String, Map<String, List<Map<String, Object>>>> metaData = new HashMap<>(); for (String formatName : formatNames) { if (task != null && !task.isWorking()) { return false; } Map<String, List<Map<String, Object>>> formatMetaData = new HashMap<>(); IIOMetadataNode tree = (IIOMetadataNode) iioMetaData.getAsTree(formatName); readImageMetaData(task, formatMetaData, metaDataXml, tree, 2); metaData.put(formatName, formatMetaData); } imageInfo.setMetaData(metaData); imageInfo.setMetaDataXml(metaDataXml.toString()); explainCommonMetaData(metaData, imageInfo); switch (format.toLowerCase()) { case "png": ImagePngFile.explainPngMetaData(metaData, imageInfo); break; case "jpg": case "jpeg": ImageJpgFile.explainJpegMetaData(metaData, imageInfo); break; case "gif": ImageGifFile.explainGifMetaData(metaData, imageInfo); break; case "bmp": ImageBmpFile.explainBmpMetaData(metaData, imageInfo); break; case "tif": case "tiff": ImageTiffFile.explainTiffMetaData(iioMetaData, imageInfo); break; default: } // MyBoxLog.debug(metaData); return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } public static boolean readImageMetaData(FxTask task, Map<String, List<Map<String, Object>>> formatMetaData, StringBuilder metaDataXml, IIOMetadataNode node, int level) { try { String lineSeparator = System.getProperty("line.separator"); for (int i = 0; i < level; ++i) { metaDataXml.append(" "); } metaDataXml.append("<").append(node.getNodeName()); Map<String, Object> nodeAttrs = new HashMap<>(); NamedNodeMap map = node.getAttributes(); boolean isTiff = "TIFFField".equals(node.getNodeName()); if (map != null && map.getLength() > 0) { int length = map.getLength(); for (int i = 0; i < length; ++i) { if (task != null && !task.isWorking()) { return false; } Node attr = map.item(i); String name = attr.getNodeName(); String value = attr.getNodeValue(); if (!isTiff) { nodeAttrs.put(name, value); } metaDataXml.append(" ").append(name).append("=\"").append(value).append("\""); if (isTiff && "ICC Profile".equals(value)) { metaDataXml.append(" value=\"skip...\"/>").append(lineSeparator); return true; } } } Object userObject = node.getUserObject(); if (userObject != null) { if (!isTiff) { nodeAttrs.put("UserObject", userObject); } metaDataXml.append(" ").append("UserObject=\"skip...\""); } if (!isTiff && !nodeAttrs.isEmpty()) { List<Map<String, Object>> nodeAttrsList = formatMetaData.get(node.getNodeName()); if (nodeAttrsList == null) { nodeAttrsList = new ArrayList<>(); } nodeAttrsList.add(nodeAttrs); formatMetaData.put(node.getNodeName(), nodeAttrsList); } IIOMetadataNode child = (IIOMetadataNode) node.getFirstChild(); if (child == null) { metaDataXml.append("/>").append(lineSeparator); return true; } metaDataXml.append(">").append(lineSeparator); while (child != null) { if (task != null && !task.isWorking()) { return false; } readImageMetaData(task, formatMetaData, metaDataXml, child, level + 1); child = (IIOMetadataNode) child.getNextSibling(); } for (int i = 0; i < level; ++i) { metaDataXml.append(" "); } metaDataXml.append("</").append(node.getNodeName()).append(">").append(lineSeparator); return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html public static void explainCommonMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation imageInfo) { try { if (!metaData.containsKey("javax_imageio_1.0")) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImagePngFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImagePngFile.java
package mara.mybox.image.file; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageOutputStream; import mara.mybox.color.CIEData; import mara.mybox.dev.MyBoxLog; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageColor; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.data.ImageInformationPng; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.tools.ByteTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2018-6-19 * * @Description * @License Apache License Version 2.0 */ public class ImagePngFile { // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image public static ImageWriter getWriter() { ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next(); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metaData == null || metaData.isReadOnly() || attributes == null) { return metaData; } String nativeFormat = metaData.getNativeMetadataFormatName(); // "javax_imageio_png_1.0" IIOMetadataNode nativeTree = (IIOMetadataNode) metaData.getAsTree(nativeFormat); if (attributes.getDensity() > 0) { NodeList pHYsNode = nativeTree.getElementsByTagName("pHYs"); IIOMetadataNode pHYs; if (pHYsNode != null && pHYsNode.getLength() > 0) { pHYs = (IIOMetadataNode) pHYsNode.item(0); } else { pHYs = new IIOMetadataNode("pHYs"); nativeTree.appendChild(pHYs); } String dpm = ImageConvertTools.dpi2dpm(attributes.getDensity()) + ""; pHYs.setAttribute("pixelsPerUnitXAxis", dpm); pHYs.setAttribute("pixelsPerUnitYAxis", dpm); pHYs.setAttribute("unitSpecifier", "meter"); // density is dots per !Meter! } if (attributes.isEmbedProfile() && attributes.getProfile() != null && attributes.getProfileName() != null) { NodeList iCCPsNode = nativeTree.getElementsByTagName("iCCP"); IIOMetadataNode iCCP; if (iCCPsNode != null && iCCPsNode.getLength() > 0) { iCCP = (IIOMetadataNode) iCCPsNode.item(0); } else { iCCP = new IIOMetadataNode("iCCP"); nativeTree.appendChild(iCCP); } iCCP.setUserObject(ByteTools.deflate(attributes.getProfile().getData())); iCCP.setAttribute("profileName", attributes.getProfileName()); iCCP.setAttribute("compressionMethod", "deflate"); } metaData.mergeTree(nativeFormat, nativeTree); return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writePNGImageFile(BufferedImage image, ImageAttributes attributes, File file) { try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image // http://www.libpng.org/pub/png/spec/iso/index-object.html // http://www.libpng.org/pub/png/spec/1.2/PNG-ColorAppendix.html // http://www.libpng.org/pub/png/spec/1.2/PNG-GammaAppendix.html public static void explainPngMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation info) { try { if (!metaData.containsKey("javax_imageio_png_1.0")) { return; } ImageInformationPng pngInfo = (ImageInformationPng) info; // MyBoxLog.debug("explainPngMetaData"); Map<String, List<Map<String, Object>>> javax_imageio_png = metaData.get("javax_imageio_png_1.0"); if (javax_imageio_png.containsKey("IHDR")) { Map<String, Object> IHDR = javax_imageio_png.get("IHDR").get(0); if (IHDR.containsKey("width")) { pngInfo.setWidth(Integer.parseInt((String) IHDR.get("width"))); } if (IHDR.containsKey("height")) { pngInfo.setHeight(Integer.parseInt((String) IHDR.get("height"))); } if (IHDR.containsKey("bitDepth")) { pngInfo.setBitDepth(Integer.parseInt((String) IHDR.get("bitDepth"))); } if (IHDR.containsKey("colorType")) { pngInfo.setColorType((String) IHDR.get("colorType")); } if (IHDR.containsKey("compressionMethod")) { pngInfo.setCompressionMethod((String) IHDR.get("compressionMethod")); } if (IHDR.containsKey("filterMethod")) { pngInfo.setFilterMethod((String) IHDR.get("filterMethod")); } if (IHDR.containsKey("interlaceMethod")) { pngInfo.setInterlaceMethod((String) IHDR.get("interlaceMethod")); } } if (javax_imageio_png.containsKey("PLTEEntry")) { List<Map<String, Object>> PaletteEntryList = javax_imageio_png.get("PLTEEntry"); pngInfo.setPngPaletteSize(PaletteEntryList.size()); // List<ImageColor> Palette = new ArrayList<>(); // for (Map<String, Object> PaletteEntry : PaletteEntryList) { // int index = Integer.parseInt(PaletteEntry.get("index")); // int red = Integer.parseInt(PaletteEntry.get("red")); // int green = Integer.parseInt(PaletteEntry.get("green")); // int blue = Integer.parseInt(PaletteEntry.get("blue")); // int alpha = 255; // Palette.add(new ImageColor(index, red, green, blue, alpha)); // } // pngInfo.setPngPalette(Palette); } if (javax_imageio_png.containsKey("bKGD_Grayscale")) { Map<String, Object> bKGD_Grayscale = javax_imageio_png.get("bKGD_Grayscale").get(0); pngInfo.setbKGD_Grayscale(Integer.parseInt((String) bKGD_Grayscale.get("gray"))); } if (javax_imageio_png.containsKey("bKGD_RGB")) { Map<String, Object> bKGD_RGB = javax_imageio_png.get("bKGD_RGB").get(0); int red = Integer.parseInt((String) bKGD_RGB.get("red")); int green = Integer.parseInt((String) bKGD_RGB.get("green")); int blue = Integer.parseInt((String) bKGD_RGB.get("blue")); int alpha = 255; pngInfo.setbKGD_RGB(new ImageColor(red, green, blue, alpha)); } if (javax_imageio_png.containsKey("bKGD_Palette")) { Map<String, Object> bKGD_Palette = javax_imageio_png.get("bKGD_Palette").get(0); pngInfo.setbKGD_Palette(Integer.parseInt((String) bKGD_Palette.get("index"))); } if (javax_imageio_png.containsKey("cHRM")) { Map<String, Object> cHRM = javax_imageio_png.get("cHRM").get(0); double x = 0.00001d * Integer.parseInt((String) cHRM.get("whitePointX")); double y = 0.00001d * Integer.parseInt((String) cHRM.get("whitePointY")); pngInfo.setWhite(new CIEData(x, y)); x = 0.00001d * Integer.parseInt((String) cHRM.get("redX")); y = 0.00001d * Integer.parseInt((String) cHRM.get("redY")); pngInfo.setRed(new CIEData(x, y)); x = 0.00001d * Integer.parseInt((String) cHRM.get("greenX")); y = 0.00001d * Integer.parseInt((String) cHRM.get("greenY")); pngInfo.setGreen(new CIEData(x, y)); x = 0.00001d * Integer.parseInt((String) cHRM.get("blueX")); y = 0.00001d * Integer.parseInt((String) cHRM.get("blueY")); pngInfo.setBlue(new CIEData(x, y)); } if (javax_imageio_png.containsKey("gAMA")) { Map<String, Object> gAMA = javax_imageio_png.get("gAMA").get(0); float g = 0.00001f * Integer.parseInt((String) gAMA.get("value")); pngInfo.setGamma(g); } if (javax_imageio_png.containsKey("iCCP")) { Map<String, Object> iCCP = javax_imageio_png.get("iCCP").get(0); pngInfo.setProfileName((String) iCCP.get("profileName")); pngInfo.setProfileCompressionMethod((String) iCCP.get("compressionMethod")); pngInfo.setIccProfile(ByteTools.inflate((byte[]) iCCP.get("UserObject"))); } if (javax_imageio_png.containsKey("pHYs")) { Map<String, Object> pHYs = javax_imageio_png.get("pHYs").get(0); if (pHYs.containsKey("unitSpecifier")) { pngInfo.setUnitSpecifier((String) pHYs.get("unitSpecifier")); boolean isMeter = "meter".equals(pHYs.get("unitSpecifier")); if (pHYs.containsKey("pixelsPerUnitXAxis")) { int v = Integer.parseInt((String) pHYs.get("pixelsPerUnitXAxis")); pngInfo.setPixelsPerUnitXAxis(v); if (isMeter) { pngInfo.setXDpi(ImageConvertTools.dpm2dpi(v)); // resolution value should be dpi } else { pngInfo.setXDpi(v); } // MyBoxLog.debug("pixelsPerUnitXAxis:" + pngInfo.gethResolution()); } if (pHYs.containsKey("pixelsPerUnitYAxis")) { int v = Integer.parseInt((String) pHYs.get("pixelsPerUnitYAxis")); pngInfo.setPixelsPerUnitYAxis(v); if (isMeter) { pngInfo.setYDpi(ImageConvertTools.dpm2dpi(v)); // resolution value should be dpi } else { pngInfo.setYDpi(v); } // MyBoxLog.debug("pixelsPerUnitYAxis:" + pngInfo.getvResolution()); } } } if (javax_imageio_png.containsKey("sBIT_Grayscale")) { Map<String, Object> sBIT_Grayscale = javax_imageio_png.get("sBIT_Grayscale").get(0); pngInfo.setsBIT_Grayscale(Integer.parseInt((String) sBIT_Grayscale.get("gray"))); } if (javax_imageio_png.containsKey("sBIT_GrayAlpha")) { Map<String, Object> sBIT_GrayAlpha = javax_imageio_png.get("sBIT_GrayAlpha").get(0); pngInfo.setsBIT_GrayAlpha_gray(Integer.parseInt((String) sBIT_GrayAlpha.get("gray"))); pngInfo.setsBIT_GrayAlpha_alpha(Integer.parseInt((String) sBIT_GrayAlpha.get("alpha"))); } if (javax_imageio_png.containsKey("sBIT_RGB")) { Map<String, Object> sBIT_RGB = javax_imageio_png.get("sBIT_RGB").get(0); pngInfo.setsBIT_RGB_red(Integer.parseInt((String) sBIT_RGB.get("red"))); pngInfo.setsBIT_RGB_green(Integer.parseInt((String) sBIT_RGB.get("green"))); pngInfo.setsBIT_RGB_blue(Integer.parseInt((String) sBIT_RGB.get("blue"))); } if (javax_imageio_png.containsKey("sBIT_RGBAlpha")) { Map<String, Object> sBIT_RGBAlpha = javax_imageio_png.get("sBIT_RGBAlpha").get(0); pngInfo.setsBIT_RGBAlpha_red(Integer.parseInt((String) sBIT_RGBAlpha.get("red"))); pngInfo.setsBIT_RGBAlpha_green(Integer.parseInt((String) sBIT_RGBAlpha.get("green"))); pngInfo.setsBIT_RGBAlpha_blue(Integer.parseInt((String) sBIT_RGBAlpha.get("blue"))); pngInfo.setsBIT_RGBAlpha_alpha(Integer.parseInt((String) sBIT_RGBAlpha.get("alpha"))); } if (javax_imageio_png.containsKey("sBIT_Palette")) { Map<String, Object> sBIT_Palette = javax_imageio_png.get("sBIT_Palette").get(0); pngInfo.setsBIT_Palette_red(Integer.parseInt((String) sBIT_Palette.get("red"))); pngInfo.setsBIT_Palette_green(Integer.parseInt((String) sBIT_Palette.get("green"))); pngInfo.setsBIT_Palette_blue(Integer.parseInt((String) sBIT_Palette.get("blue"))); } if (javax_imageio_png.containsKey("sPLTEntry")) { List<Map<String, Object>> sPLTEntryList = javax_imageio_png.get("sPLTEntry"); pngInfo.setSuggestedPaletteSize(sPLTEntryList.size()); // List<ImageColor> Palette = new ArrayList<>(); // for (Map<String, Object> PaletteEntry : sPLTEntryList) { // int index = Integer.parseInt(PaletteEntry.get("index")); // int red = Integer.parseInt(PaletteEntry.get("red")); // int green = Integer.parseInt(PaletteEntry.get("green")); // int blue = Integer.parseInt(PaletteEntry.get("blue")); // int alpha = 255; // Palette.add(new ImageColor(index, red, green, blue, alpha)); // } // pngInfo.setSuggestedPalette(Palette); } if (javax_imageio_png.containsKey("sRGB")) { Map<String, Object> sRGB = javax_imageio_png.get("sRGB").get(0); pngInfo.setRenderingIntent((String) sRGB.get("renderingIntent")); } if (javax_imageio_png.containsKey("tIME")) { Map<String, Object> ImageModificationTime = javax_imageio_png.get("tIME").get(0); String t = ImageModificationTime.get("year") + "-" + ImageModificationTime.get("month") + "-" + ImageModificationTime.get("day") + " " + ImageModificationTime.get("hour") + ":" + ImageModificationTime.get("minute") + ":" + ImageModificationTime.get("second"); pngInfo.setImageModificationTime(t); } if (javax_imageio_png.containsKey("tRNS_Grayscale")) { Map<String, Object> tRNS_Grayscale = javax_imageio_png.get("tRNS_Grayscale").get(0); pngInfo.settRNS_Grayscale(Integer.parseInt((String) tRNS_Grayscale.get("gray"))); } if (javax_imageio_png.containsKey("tRNS_RGB")) { Map<String, Object> tRNS_RGB = javax_imageio_png.get("tRNS_RGB").get(0); int red = Integer.parseInt((String) tRNS_RGB.get("red")); int green = Integer.parseInt((String) tRNS_RGB.get("green")); int blue = Integer.parseInt((String) tRNS_RGB.get("blue")); int alpha = 255; pngInfo.settRNS_RGB(new ImageColor(red, green, blue, alpha)); } if (javax_imageio_png.containsKey("tRNS_Palette")) { Map<String, Object> tRNS_Palette = javax_imageio_png.get("tRNS_Palette").get(0); pngInfo.settRNS_Palette_index(Integer.parseInt((String) tRNS_Palette.get("index"))); pngInfo.settRNS_Palette_alpha(Integer.parseInt((String) tRNS_Palette.get("alpha"))); } } catch (Exception e) { } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImagePnmFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImagePnmFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.pnm.PNMImageReader; import com.github.jaiimageio.impl.plugins.pnm.PNMImageReaderSpi; import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriter; import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriterSpi; import com.github.jaiimageio.impl.plugins.pnm.PNMMetadata; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.image.data.ImageAttributes; import mara.mybox.tools.FileTools; import mara.mybox.tools.FileTmpTools; /** * @Author Mara * @CreateDate 2018-6-19 * * @Description * @License Apache License Version 2.0 */ public class ImagePnmFile { public static ImageWriter getWriter() { PNMImageWriter writer = new PNMImageWriter(new PNMImageWriterSpi()); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { PNMMetadata metaData = (PNMMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writePnmImageFile(BufferedImage image, ImageAttributes attributes, String outFile) { try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); File tmpFile = FileTmpTools.getTempFile(); try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); File file = new File(outFile); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static PNMMetadata getPnmMetadata(File file) { try { PNMMetadata metadata; PNMImageReader reader = new PNMImageReader(new PNMImageReaderSpi()); try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { reader.setInput(iis, false); metadata = (PNMMetadata) reader.getImageMetadata(0); reader.dispose(); } return metadata; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageJpgFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageJpgFile.java
package mara.mybox.image.file; import java.awt.Rectangle; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.WritableRaster; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.image.data.ImageFileInformation; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.ScaleTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.value.Languages; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2018-6-19 * * @Description * @License Apache License Version 2.0 */ public class ImageJpgFile { public static String[] getJpegCompressionTypes() { return new JPEGImageWriteParam(null).getCompressionTypes(); } public static BufferedImage readBrokenJpgFile(FxTask task, ImageInformation imageInfo) { if (imageInfo == null) { return null; } File file = imageInfo.getFile(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) { Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (reader.canReadRaster()) { break; } } if (reader == null) { iis.close(); return null; } reader.setInput(iis); ImageFileInformation fileInfo = new ImageFileInformation(file); ImageFileReaders.readImageFileMetaData(task, reader, fileInfo); if (task != null && !task.isWorking()) { return null; } ImageInformation fileImageInfo = fileInfo.getImagesInformation().get(imageInfo.getIndex()); imageInfo.setWidth(fileImageInfo.getWidth()); imageInfo.setHeight(fileImageInfo.getHeight()); imageInfo.setColorSpace(fileImageInfo.getColorSpace()); imageInfo.setColorChannels(fileImageInfo.getColorChannels()); imageInfo.setNativeAttribute("Adobe", fileImageInfo.getNativeAttribute("Adobe")); BufferedImage bufferedImage = readBrokenJpgFile(task, reader, imageInfo); if (task != null && !task.isWorking()) { return null; } int requiredWidth = (int) imageInfo.getRequiredWidth(); if (requiredWidth > 0 && bufferedImage.getWidth() != requiredWidth) { bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, requiredWidth); } return bufferedImage; } catch (Exception ex) { imageInfo.setError(ex.toString()); return null; } } private static BufferedImage readBrokenJpgFile(FxTask task, ImageReader reader, ImageInformation imageInfo) { if (reader == null || imageInfo == null || imageInfo.getColorChannels() != 4) { return null; } BufferedImage bufferedImage = null; try { ImageReadParam param = reader.getDefaultReadParam(); Rectangle region = imageInfo.getIntRegion(); if (region != null) { param.setSourceRegion(region); } int xscale = imageInfo.getXscale(); int yscale = imageInfo.getYscale(); if (xscale != 1 || yscale != 1) { param.setSourceSubsampling(xscale, yscale, 0, 0); } else { ImageInformation.checkMem(task, imageInfo); int sampleScale = imageInfo.getSampleScale(); if (sampleScale > 1) { param.setSourceSubsampling(sampleScale, sampleScale, 0, 0); } } if (task != null && !task.isWorking()) { return null; } WritableRaster srcRaster = (WritableRaster) reader.readRaster(imageInfo.getIndex(), param); if (task != null && !task.isWorking()) { return null; } boolean isAdobe = (boolean) imageInfo.getNativeAttribute("Adobe"); if ("YCCK".equals(imageInfo.getColorSpace())) { ImageConvertTools.ycck2cmyk(task, srcRaster, isAdobe); } else if (isAdobe) { ImageConvertTools.invertPixelValue(task, srcRaster); } if (task != null && !task.isWorking()) { return null; } bufferedImage = new BufferedImage(srcRaster.getWidth(), srcRaster.getHeight(), BufferedImage.TYPE_INT_RGB); WritableRaster rgbRaster = bufferedImage.getRaster(); ColorSpace cmykCS; if (isAdobe) { cmykCS = ImageColorSpace.adobeCmykColorSpace(); } else { cmykCS = ImageColorSpace.eciCmykColorSpace(); } ColorSpace rgbCS = bufferedImage.getColorModel().getColorSpace(); ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null); if (task != null && !task.isWorking()) { return null; } cmykToRgb.filter(srcRaster, rgbRaster); } catch (Exception ex) { imageInfo.setError(ex.toString()); } return bufferedImage; } public static ImageWriter getWriter() { ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#image public static IIOMetadata getWriterMeta2(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metaData == null || metaData.isReadOnly() || attributes == null) { return metaData; } String nativeFormat = metaData.getNativeMetadataFormatName();// "javax_imageio_jpeg_image_1.0" IIOMetadataNode root = new IIOMetadataNode(nativeFormat); IIOMetadataNode jpegVariety = new IIOMetadataNode("JPEGvariety"); IIOMetadataNode markerSequence = new IIOMetadataNode("markerSequence"); IIOMetadataNode app0JFIF = new IIOMetadataNode("app0JFIF"); root.appendChild(jpegVariety); root.appendChild(markerSequence); jpegVariety.appendChild(app0JFIF); app0JFIF.setAttribute("majorVersion", "1"); app0JFIF.setAttribute("minorVersion", "2"); app0JFIF.setAttribute("thumbWidth", "0"); app0JFIF.setAttribute("thumbHeight", "0"); if (attributes.getDensity() > 0) { app0JFIF.setAttribute("Xdensity", attributes.getDensity() + ""); app0JFIF.setAttribute("Ydensity", attributes.getDensity() + ""); app0JFIF.setAttribute("resUnits", "1"); // density is dots per inch } if (attributes.isEmbedProfile() && attributes.getProfile() != null) { IIOMetadataNode app2ICC = new IIOMetadataNode("app2ICC"); app0JFIF.appendChild(app2ICC); app2ICC.setUserObject(attributes.getProfile()); } metaData.mergeTree(nativeFormat, root); return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metaData == null || metaData.isReadOnly() || attributes == null) { return metaData; } String nativeFormat = metaData.getNativeMetadataFormatName();// "javax_imageio_jpeg_image_1.0" IIOMetadataNode nativeTree = (IIOMetadataNode) metaData.getAsTree(nativeFormat); if (nativeTree == null) { return metaData; } IIOMetadataNode JPEGvariety, markerSequence; NodeList JPEGvarietyNode = nativeTree.getElementsByTagName("JPEGvariety"); if (JPEGvarietyNode != null && JPEGvarietyNode.getLength() > 0) { JPEGvariety = (IIOMetadataNode) JPEGvarietyNode.item(0); } else { JPEGvariety = new IIOMetadataNode("JPEGvariety"); nativeTree.appendChild(JPEGvariety); } NodeList markerSequenceNode = nativeTree.getElementsByTagName("markerSequence"); if (markerSequenceNode == null) { markerSequence = new IIOMetadataNode("markerSequence"); nativeTree.appendChild(markerSequence); } IIOMetadataNode app0JFIF; NodeList app0JFIFNode = nativeTree.getElementsByTagName("app0JFIF"); if (app0JFIFNode != null && app0JFIFNode.getLength() > 0) { app0JFIF = (IIOMetadataNode) app0JFIFNode.item(0); } else { app0JFIF = new IIOMetadataNode("app0JFIF"); JPEGvariety.appendChild(app0JFIF); } if (attributes.getDensity() > 0) { app0JFIF.setAttribute("Xdensity", attributes.getDensity() + ""); app0JFIF.setAttribute("Ydensity", attributes.getDensity() + ""); app0JFIF.setAttribute("resUnits", "1"); // density is dots per inch } if (attributes.isEmbedProfile() && attributes.getProfile() != null) { IIOMetadataNode app2ICC; NodeList app2ICCNode = nativeTree.getElementsByTagName("app2ICC"); if (app2ICCNode != null && app2ICCNode.getLength() > 0) { app2ICC = (IIOMetadataNode) app2ICCNode.item(0); } else { app2ICC = new IIOMetadataNode("app2ICC"); app0JFIF.appendChild(app2ICC); } app2ICC.setUserObject(attributes.getProfile()); } metaData.mergeTree(nativeFormat, nativeTree); return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writeJPEGImageFile(BufferedImage image, ImageAttributes attributes, File file) { try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void explainJpegMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation info) { try { if (!metaData.containsKey("javax_imageio_jpeg_image_1.0")) { return; } Map<String, List<Map<String, Object>>> javax_imageio_jpeg = metaData.get("javax_imageio_jpeg_image_1.0"); if (javax_imageio_jpeg.containsKey("app0JFIF")) { Map<String, Object> app0JFIF = javax_imageio_jpeg.get("app0JFIF").get(0); if (app0JFIF.containsKey("majorVersion")) { info.setNativeAttribute("majorVersion", Integer.parseInt((String) app0JFIF.get("majorVersion"))); } if (app0JFIF.containsKey("minorVersion")) { info.setNativeAttribute("minorVersion", Integer.parseInt((String) app0JFIF.get("minorVersion"))); } if (app0JFIF.containsKey("resUnits")) { int u = Integer.parseInt((String) app0JFIF.get("resUnits")); info.setNativeAttribute("resUnits", u); switch (u) { case 1: info.setNativeAttribute("resUnits", Languages.message("DotsPerInch")); break; case 2: info.setNativeAttribute("resUnits", Languages.message("DotsPerCentimeter")); break; case 0: info.setNativeAttribute("resUnits", Languages.message("None")); } if (app0JFIF.containsKey("Xdensity")) { int v = Integer.parseInt((String) app0JFIF.get("Xdensity")); info.setNativeAttribute("Xdensity", v); if (u == 2) { info.setXDpi(ImageConvertTools.dpi2dpcm(v)); // density value should be dpi } else if (u == 1) { info.setXDpi(v); } } if (app0JFIF.containsKey("Ydensity")) { int v = Integer.parseInt((String) app0JFIF.get("Ydensity")); info.setNativeAttribute("Ydensity", v); if (u == 2) { info.setYDpi(ImageConvertTools.dpi2dpcm(v)); // density value should be dpi } else if (u == 1) { info.setYDpi(v); } } } if (app0JFIF.containsKey("thumbWidth")) { info.setNativeAttribute("thumbWidth", Integer.parseInt((String) app0JFIF.get("thumbWidth"))); } if (app0JFIF.containsKey("thumbHeight")) { info.setNativeAttribute("thumbHeight", Integer.parseInt((String) app0JFIF.get("thumbHeight"))); } } if (javax_imageio_jpeg.containsKey("app0JFXX")) { Map<String, Object> app0JFXX = javax_imageio_jpeg.get("app0JFXX").get(0); if (app0JFXX.containsKey("extensionCode")) { info.setNativeAttribute("extensionCode", app0JFXX.get("extensionCode")); } } if (javax_imageio_jpeg.containsKey("JFIFthumbPalette")) { Map<String, Object> JFIFthumbPalette = javax_imageio_jpeg.get("JFIFthumbPalette").get(0); if (JFIFthumbPalette.containsKey("thumbWidth")) { info.setNativeAttribute("thumbWidth", JFIFthumbPalette.get("thumbWidth")); } if (JFIFthumbPalette.containsKey("thumbHeight")) { info.setNativeAttribute("thumbHeight", JFIFthumbPalette.get("thumbHeight")); } } if (javax_imageio_jpeg.containsKey("JFIFthumbRGB")) { Map<String, Object> JFIFthumbRGB = javax_imageio_jpeg.get("JFIFthumbRGB").get(0); if (JFIFthumbRGB.containsKey("thumbWidth")) { info.setNativeAttribute("thumbWidth", JFIFthumbRGB.get("thumbWidth")); } if (JFIFthumbRGB.containsKey("thumbHeight")) { info.setNativeAttribute("thumbHeight", JFIFthumbRGB.get("thumbHeight")); } } if (javax_imageio_jpeg.containsKey("app2ICC")) { Map<String, Object> app2ICC = javax_imageio_jpeg.get("app2ICC").get(0); ICC_Profile p = (ICC_Profile) app2ICC.get("UserObject"); info.setIccProfile(p.getData()); } if (javax_imageio_jpeg.containsKey("dqtable")) { Map<String, Object> dqtable = javax_imageio_jpeg.get("dqtable").get(0); if (dqtable.containsKey("elementPrecision")) { info.setNativeAttribute("dqtableElementPrecision", dqtable.get("elementPrecision")); } if (dqtable.containsKey("qtableId")) { info.setNativeAttribute("qtableId", dqtable.get("qtableId")); } } if (javax_imageio_jpeg.containsKey("dhtable")) { Map<String, Object> dhtable = javax_imageio_jpeg.get("dhtable").get(0); if (dhtable.containsKey("class")) { info.setNativeAttribute("dhtableClass", dhtable.get("class")); } if (dhtable.containsKey("htableId")) { info.setNativeAttribute("htableId", dhtable.get("htableId")); } } if (javax_imageio_jpeg.containsKey("dri")) { Map<String, Object> dri = javax_imageio_jpeg.get("dri").get(0); if (dri.containsKey("interval")) { info.setNativeAttribute("driInterval", dri.get("interval")); } } if (javax_imageio_jpeg.containsKey("com")) { Map<String, Object> com = javax_imageio_jpeg.get("com").get(0); if (com.containsKey("comment")) { info.setNativeAttribute("comment", com.get("comment")); } } if (javax_imageio_jpeg.containsKey("unknown")) { Map<String, Object> unknown = javax_imageio_jpeg.get("unknown").get(0); if (unknown.containsKey("MarkerTag")) { info.setNativeAttribute("unknownMarkerTag", unknown.get("MarkerTag")); } } if (javax_imageio_jpeg.containsKey("app14Adobe")) { info.setNativeAttribute("Adobe", true); Map<String, Object> app14Adobe = javax_imageio_jpeg.get("app14Adobe").get(0); if (app14Adobe.containsKey("version")) { info.setNativeAttribute("AdobeVersion", app14Adobe.get("version")); } if (app14Adobe.containsKey("flags0")) { info.setNativeAttribute("AdobeFlags0", app14Adobe.get("flags0")); } if (app14Adobe.containsKey("flags1")) { info.setNativeAttribute("AdobeFlags1", app14Adobe.get("flags1")); } /* https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#image 2 - The image is encoded as YCCK (implicitly converted from CMYK on encoding). 1 - The image is encoded as YCbCr (implicitly converted from RGB on encoding). 0 - Unknown. 3-channel images are assumed to be RGB, 4-channel images are assumed to be CMYK. */ if (app14Adobe.containsKey("transform")) { info.setNativeAttribute("AdobeTransform", app14Adobe.get("transform")); } } if (javax_imageio_jpeg.containsKey("sof")) { Map<String, Object> sof = javax_imageio_jpeg.get("sof").get(0); if (sof.containsKey("process")) { info.setNativeAttribute("FrameProcess", sof.get("process")); } if (sof.containsKey("samplePrecision")) { info.setNativeAttribute("FrameSamplePrecision", sof.get("samplePrecision")); } if (sof.containsKey("numLines")) { info.setNativeAttribute("FrameNumLines", sof.get("numLines")); } if (sof.containsKey("samplesPerLine")) { info.setNativeAttribute("FrameSamplesPerLine", sof.get("samplesPerLine")); } if (sof.containsKey("numFrameComponents")) { info.setNativeAttribute("FrameNumFrameComponents", sof.get("numFrameComponents")); } } if (javax_imageio_jpeg.containsKey("componentSpec")) { Map<String, Object> componentSpec = javax_imageio_jpeg.get("componentSpec").get(0); if (componentSpec.containsKey("componentId")) { info.setNativeAttribute("FrameComponentId", componentSpec.get("componentId")); } if (componentSpec.containsKey("HsamplingFactor")) { info.setNativeAttribute("FrameHsamplingFactor", componentSpec.get("HsamplingFactor")); } if (componentSpec.containsKey("VsamplingFactor")) { info.setNativeAttribute("FrameVsamplingFactor", componentSpec.get("VsamplingFactor")); } if (componentSpec.containsKey("QtableSelector")) { info.setNativeAttribute("FrameQtableSelector", componentSpec.get("QtableSelector")); } } if (javax_imageio_jpeg.containsKey("sos")) { Map<String, Object> sos = javax_imageio_jpeg.get("sos").get(0); if (sos.containsKey("numScanComponents")) { info.setNativeAttribute("NumScanComponents", sos.get("numScanComponents")); } if (sos.containsKey("startSpectralSelection")) { info.setNativeAttribute("ScanStartSpectralSelection", sos.get("startSpectralSelection")); } if (sos.containsKey("endSpectralSelection")) { info.setNativeAttribute("ScanEndSpectralSelection", sos.get("endSpectralSelection")); } if (sos.containsKey("approxHigh")) { info.setNativeAttribute("ScanApproxHigh", sos.get("approxHigh")); } if (sos.containsKey("approxLow")) { info.setNativeAttribute("ScanApproxLow", sos.get("approxLow")); } } if (javax_imageio_jpeg.containsKey("scanComponentSpec")) { Map<String, Object> scanComponentSpec = javax_imageio_jpeg.get("scanComponentSpec").get(0); if (scanComponentSpec.containsKey("componentSelector")) { info.setNativeAttribute("ScanComponentSelector", scanComponentSpec.get("componentSelector")); } if (scanComponentSpec.containsKey("dcHuffTable")) { info.setNativeAttribute("ScanDcHuffTable", scanComponentSpec.get("dcHuffTable")); } if (scanComponentSpec.containsKey("acHuffTable")) { info.setNativeAttribute("ScanAcHuffTable", scanComponentSpec.get("acHuffTable")); } } } catch (Exception e) { } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImagePcxFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImagePcxFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.pcx.PCXImageReader; import com.github.jaiimageio.impl.plugins.pcx.PCXImageReaderSpi; import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriter; import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriterSpi; import com.github.jaiimageio.impl.plugins.pcx.PCXMetadata; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.image.data.ImageAttributes; import mara.mybox.tools.FileTools; import mara.mybox.tools.FileTmpTools; /** * @Author Mara * @CreateDate 2018-6-19 * * @Description * @License Apache License Version 2.0 */ public class ImagePcxFile { public static ImageWriter getWriter() { PCXImageWriter writer = new PCXImageWriter(new PCXImageWriterSpi()); return writer; } public static boolean writePcxImageFile(BufferedImage image, ImageAttributes attributes, File file) { try { ImageWriter writer = getWriter(); File tmpFile = FileTmpTools.getTempFile(); try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); writer.write(null, new IIOImage(image, null, null), null); out.flush(); } writer.dispose(); return FileTools.override(tmpFile, file); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static PCXMetadata getPcxMetadata(File file) { try { PCXMetadata metadata = null; PCXImageReader reader = new PCXImageReader(new PCXImageReaderSpi()); try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { reader.setInput(iis, false); metadata = (PCXMetadata) reader.getImageMetadata(0); reader.dispose(); } return metadata; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/file/ImageTiffFile.java
released/MyBox/src/main/java/mara/mybox/image/file/ImageTiffFile.java
package mara.mybox.image.file; //import com.github.jaiimageio.impl.plugins.tiff.IIOMetadata; //import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReader; //import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReaderSpi; //import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriter; //import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriterSpi; //import com.github.jaiimageio.plugins.tiff.BaselineTIFFTagSet; //import com.github.jaiimageio.plugins.tiff.TIFFField; //import com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam; //import com.github.jaiimageio.plugins.tiff.TIFFTag; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.plugins.tiff.BaselineTIFFTagSet; import javax.imageio.plugins.tiff.TIFFField; import javax.imageio.plugins.tiff.TIFFTag; import javax.imageio.stream.ImageInputStream; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.FileNameTools; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2018-6-19 * @License Apache License Version 2.0 */ // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/tiff_metadata.html#image public class ImageTiffFile { public static IIOMetadata getTiffIIOMetadata(File file) { try { IIOMetadata metadata; try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { ImageReader reader = ImageFileReaders.getReader(iis, FileNameTools.ext(file.getName())); if (reader == null) { return null; } reader.setInput(iis, false); metadata = reader.getImageMetadata(0); reader.dispose(); } return metadata; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static ImageWriter getWriter() { ImageWriter writer = ImageIO.getImageWritersByFormatName("tif").next(); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } else { param.setCompressionType("LZW"); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { IIOMetadata metaData; if (attributes != null && attributes.getColorType() != null) { ImageTypeSpecifier imageTypeSpecifier; switch (attributes.getColorType()) { case ARGB: imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); break; case RGB: imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); break; case BINARY: imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); break; case GRAY: imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); break; default: imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); break; } metaData = writer.getDefaultImageMetadata(imageTypeSpecifier, param); } else if (image != null) { metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); } else { metaData = writer.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB), param); } if (metaData == null || metaData.isReadOnly() || attributes == null) { return metaData; } if (attributes.getDensity() > 0) { String nativeName = metaData.getNativeMetadataFormatName(); // javax_imageio_tiff_image_1.0 Node nativeTree = metaData.getAsTree(nativeName); long[] xRes = new long[]{attributes.getDensity(), 1}; long[] yRes = new long[]{attributes.getDensity(), 1}; TIFFField fieldXRes = new TIFFField( BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][]{xRes}); TIFFField fieldYRes = new TIFFField( BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION), TIFFTag.TIFF_RATIONAL, 1, new long[][]{yRes}); nativeTree.getFirstChild().appendChild(fieldXRes.getAsNativeNode()); nativeTree.getFirstChild().appendChild(fieldYRes.getAsNativeNode()); char[] fieldUnit = new char[]{ BaselineTIFFTagSet.RESOLUTION_UNIT_INCH}; TIFFField fieldResUnit = new TIFFField( BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT), TIFFTag.TIFF_SHORT, 1, fieldUnit); nativeTree.getFirstChild().appendChild(fieldResUnit.getAsNativeNode()); metaData.mergeTree(nativeName, nativeTree); } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static Node findNode(Node nativeTree, String name) { try { NodeList nodes = nativeTree.getFirstChild().getChildNodes(); for (int i = 0; i < nodes.getLength(); ++i) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); for (int j = 0; j < attrs.getLength(); ++j) { Node attr = attrs.item(j); if ("name".equals(attr.getNodeName()) && name.equals(attr.getNodeValue())) { return node; } } } return null; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } // Ignore list values, which can be anaylse if need in future. public static void explainTiffMetaData(IIOMetadata iioMetaData, ImageInformation info) { try { String nativeName = iioMetaData.getNativeMetadataFormatName(); // javax_imageio_tiff_image_1.0 Node nativeTree = iioMetaData.getAsTree(nativeName); NodeList nodes = nativeTree.getFirstChild().getChildNodes(); BaselineTIFFTagSet tagsSet = BaselineTIFFTagSet.getInstance(); int unit = -1, x = -1, y = -1; for (int i = 0; i < nodes.getLength(); ++i) { Node node = nodes.item(i); TIFFField field = TIFFField.createFromMetadataNode(tagsSet, node); String name = field.getTag().getName(); if ("ICC Profile".equals(name)) { info.setIccProfile(field.getAsBytes()); info.setNativeAttribute(name, "skip..."); } else { String des = null; try { des = node.getFirstChild().getFirstChild().getAttributes().item(1).getNodeValue(); } catch (Exception e) { } List<String> values = new ArrayList<>(); for (int j = 0; j < field.getCount(); ++j) { values.add(field.getValueAsString(j)); } if (values.isEmpty()) { continue; } else if (values.size() == 1) { if (des != null) { info.setNativeAttribute(name, des + "(" + values.get(0) + ")"); } else { info.setNativeAttribute(name, values.get(0)); } } else { info.setNativeAttribute(name, values); } switch (name) { case "ImageWidth": info.setWidth(Integer.parseInt(values.get(0))); break; case "ImageLength": info.setHeight(Integer.parseInt(values.get(0))); break; case "ResolutionUnit": unit = Integer.parseInt(values.get(0)); break; case "XResolution": x = getRationalValue(values.get(0)); break; case "YResolution": y = getRationalValue(values.get(0)); break; } } } if (x > 0 && y > 0) { if (BaselineTIFFTagSet.RESOLUTION_UNIT_CENTIMETER == unit) { info.setXDpi(ImageConvertTools.dpcm2dpi(x)); info.setYDpi(ImageConvertTools.dpcm2dpi(y)); } else if (BaselineTIFFTagSet.RESOLUTION_UNIT_INCH == unit) { info.setXDpi(x); info.setYDpi(y); } } } catch (Exception e) { MyBoxLog.debug(e); } } private static int getRationalValue(String v) { int pos = v.indexOf('/'); String vv = v; if (pos > 0) { vv = v.substring(0, pos); } return Integer.parseInt(vv); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/PixelsBlend.java
released/MyBox/src/main/java/mara/mybox/image/data/PixelsBlend.java
package mara.mybox.image.data; import java.awt.Color; import java.awt.image.BufferedImage; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.DoubleShape; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-3-24 11:24:03 * @License Apache License Version 2.0 */ public abstract class PixelsBlend { public enum ImagesBlendMode { KubelkaMunk, CMYK, CMYK_WEIGHTED, MULTIPLY, NORMAL, DISSOLVE, DARKEN, COLOR_BURN, LINEAR_BURN, LIGHTEN, SCREEN, COLOR_DODGE, LINEAR_DODGE, DIVIDE, VIVID_LIGHT, LINEAR_LIGHT, SUBTRACT, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DIFFERENCE, EXCLUSION, HUE, SATURATION, COLOR, LUMINOSITY } protected ImagesBlendMode blendMode; protected float weight; protected boolean baseAbove = false; protected Color foreColor, backColor; protected int red, green, blue, alpha; protected TransparentAs baseTransparentAs = TransparentAs.Transparent, overlayTransparentAs = TransparentAs.Another; public enum TransparentAs { Another, Transparent, Blend } public PixelsBlend() { } public int blend(int overlayPixel, int basePixel) { if (basePixel == 0) { if (baseTransparentAs == TransparentAs.Transparent) { return 0; } else if (baseTransparentAs == TransparentAs.Another) { return overlayPixel; } } if (overlayPixel == 0) { if (overlayTransparentAs == TransparentAs.Another) { return basePixel; } else if (overlayTransparentAs == TransparentAs.Transparent) { return 0; } } if (baseAbove) { foreColor = new Color(basePixel, true); backColor = new Color(overlayPixel, true); } else { foreColor = new Color(overlayPixel, true); backColor = new Color(basePixel, true); } makeRGB(); makeAlpha(); Color newColor = new Color( Math.min(Math.max(red, 0), 255), Math.min(Math.max(green, 0), 255), Math.min(Math.max(blue, 0), 255), Math.min(Math.max(alpha, 0), 255)); return newColor.getRGB(); } public Color blend(Color overlayColor, Color baseColor) { if (overlayColor == null) { return baseColor; } if (baseColor == null) { return overlayColor; } int b = blend(overlayColor.getRGB(), baseColor.getRGB()); return new Color(b, true); } // replace this in different blend mode. Refer to "PixelsBlendFactory" public void makeRGB() { red = blendValues(foreColor.getRed(), backColor.getRed(), weight); green = blendValues(foreColor.getGreen(), backColor.getGreen(), weight); blue = blendValues(foreColor.getBlue(), backColor.getBlue(), weight); } protected void makeAlpha() { alpha = blendValues(foreColor.getAlpha(), backColor.getAlpha(), weight); } public BufferedImage blend(FxTask task, BufferedImage overlay, BufferedImage baseImage, int x, int y) { try { if (overlay == null || baseImage == null) { return null; } int imageType = BufferedImage.TYPE_INT_ARGB; DoubleRectangle rect = DoubleRectangle.xywh(x, y, overlay.getWidth(), overlay.getHeight()); BufferedImage target = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(), imageType); int height = baseImage.getHeight(); int width = baseImage.getWidth(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int basePixel = baseImage.getRGB(i, j); if (DoubleShape.contains(rect, i, j)) { int overlayPixel = overlay.getRGB(i - x, j - y); target.setRGB(i, j, blend(overlayPixel, basePixel)); } else { target.setRGB(i, j, basePixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return overlay; } } public String modeName() { return blendMode != null ? PixelsBlendFactory.modeName(blendMode) : null; } /* static */ public static Color blend2(Color foreColor, Color backColor, float weight, boolean ignoreTransparency) { if (backColor.getRGB() == 0 && ignoreTransparency) { return backColor; } return blend(foreColor, backColor, weight); } public static Color blend(Color foreColor, Color backColor, float weight) { int red = blendValues(foreColor.getRed(), backColor.getRed(), weight); int green = blendValues(foreColor.getGreen(), backColor.getRed(), weight); int blue = blendValues(foreColor.getBlue(), backColor.getRed(), weight); int alpha = blendValues(foreColor.getAlpha(), backColor.getRed(), weight); Color newColor = new Color( Math.min(Math.max(red, 0), 255), Math.min(Math.max(green, 0), 255), Math.min(Math.max(blue, 0), 255), Math.min(Math.max(alpha, 0), 255)); return newColor; } public static float fixWeight(float v) { if (v > 1f) { return 1f; } else if (v < 0) { return 0f; } else { return v; } } public static int blendValues(int A, int B, float weight) { float w = fixWeight(weight); return (int) (A * w + B * (1.0f - w)); } public static BufferedImage blend(FxTask task, BufferedImage overlay, BufferedImage baseImage, int x, int y, PixelsBlend blender) { try { if (overlay == null || baseImage == null || blender == null) { return null; } int imageType = BufferedImage.TYPE_INT_ARGB; DoubleRectangle rect = DoubleRectangle.xywh(x, y, overlay.getWidth(), overlay.getHeight()); BufferedImage target = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(), imageType); for (int j = 0; j < baseImage.getHeight(); ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < baseImage.getWidth(); ++i) { if (task != null && !task.isWorking()) { return null; } int basePixel = baseImage.getRGB(i, j); if (DoubleShape.contains(rect, i, j)) { int overlayPixel = overlay.getRGB(i - x, j - y); target.setRGB(i, j, blender.blend(overlayPixel, basePixel)); } else { target.setRGB(i, j, basePixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return overlay; } } /* get/set */ public ImagesBlendMode getBlendMode() { return blendMode; } public PixelsBlend setBlendMode(ImagesBlendMode blendMode) { this.blendMode = blendMode; return this; } public float getWeight() { return weight; } public PixelsBlend setWeight(float weight) { this.weight = fixWeight(weight); return this; } public boolean isBaseAbove() { return baseAbove; } public PixelsBlend setBaseAbove(boolean orderReversed) { this.baseAbove = orderReversed; return this; } public TransparentAs getBaseTransparentAs() { return baseTransparentAs; } public PixelsBlend setBaseTransparentAs(TransparentAs baseTransparentAs) { this.baseTransparentAs = baseTransparentAs; return this; } public TransparentAs getOverlayTransparentAs() { return overlayTransparentAs; } public PixelsBlend setOverlayTransparentAs(TransparentAs overlayTransparentAs) { this.overlayTransparentAs = overlayTransparentAs; return this; } public Color getForeColor() { return foreColor; } public void setForeColor(Color foreColor) { this.foreColor = foreColor; } public Color getBackColor() { return backColor; } public void setBackColor(Color backColor) { this.backColor = backColor; } public int getRed() { return red; } public void setRed(int red) { this.red = red; } public int getGreen() { return green; } public void setGreen(int green) { this.green = green; } public int getBlue() { return blue; } public void setBlue(int blue) { this.blue = blue; } public int getAlpha() { return alpha; } public void setAlpha(int alpha) { this.alpha = alpha; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageBinary.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageBinary.java
package mara.mybox.image.data; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.image.tools.AlphaTools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2019-2-15 * @License Apache License Version 2.0 */ public class ImageBinary extends PixelsOperation { protected BinaryAlgorithm algorithm; private BufferedImage defaultBinary; private int threshold, blackInt; public static enum BinaryAlgorithm { OTSU, Threshold, Default } public ImageBinary() { init(); } final public void init() { intPara1 = -1; defaultBinary = null; operationType = OperationType.BlackOrWhite; algorithm = BinaryAlgorithm.Default; blackInt = Color.BLACK.getRGB(); } public ImageBinary(Image image) { init(); this.image = SwingFXUtils.fromFXImage(image, null); } @Override public BufferedImage start() { if (image == null || operationType == null || operationType != OperationType.BlackOrWhite) { return image; } threshold = -1; if (algorithm == BinaryAlgorithm.OTSU) { threshold = threshold(task, image); } else if (algorithm == BinaryAlgorithm.Threshold) { threshold = intPara1; } if (threshold <= 0) { algorithm = BinaryAlgorithm.Default; defaultBinary = byteBinary(task, image); } return operateImage(); } @Override protected Color operateColor(Color color) { Color newColor; if (algorithm == BinaryAlgorithm.Default) { if (blackInt == defaultBinary.getRGB(currentX, currentY)) { newColor = Color.BLACK; } else { newColor = Color.WHITE; } } else { if (ColorConvertTools.color2grayValue(color) < threshold) { newColor = Color.BLACK; } else { newColor = Color.WHITE; } } return newColor; } /* static */ public static BufferedImage byteBinary(FxTask task, BufferedImage srcImage) { try { int width = srcImage.getWidth(); int height = srcImage.getHeight(); BufferedImage naImage = AlphaTools.removeAlpha(task, srcImage, Color.WHITE); BufferedImage binImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = binImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.drawImage(naImage, 0, 0, null); g.dispose(); return binImage; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static BufferedImage intBinary(FxTask task, BufferedImage image) { try { int width = image.getWidth(); int height = image.getHeight(); int threshold = threshold(task, image); if (threshold < 0) { return null; } int WHITE = Color.WHITE.getRGB(); int BLACK = Color.BLACK.getRGB(); BufferedImage binImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { binImage.setRGB(x, y, 0); } else { int grey = ColorConvertTools.pixel2grayValue(p); if (grey > threshold) { binImage.setRGB(x, y, WHITE); } else { binImage.setRGB(x, y, BLACK); } } } } return binImage; } catch (Exception e) { MyBoxLog.error(e); return image; } } public static Image binary(FxTask task, Image image) { try { BufferedImage bm = SwingFXUtils.fromFXImage(image, null); bm = byteBinary(task, bm); return SwingFXUtils.toFXImage(bm, null); } catch (Exception e) { MyBoxLog.error(e); return image; } } // OTSU algorithm: ICV=PA∗(MA−M)2+PB∗(MB−M)2 // https://blog.csdn.net/taoyanbian1022/article/details/9030825 // https://blog.csdn.net/liyuanbhu/article/details/49387483 public static int threshold(FxTask task, BufferedImage image) { try { if (image == null) { return -1; } int width = image.getWidth(); int height = image.getHeight(); int[] grayNumber = new int[256]; float pixelTotal = 0; for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return -1; } for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return -1; } int p = image.getRGB(i, j); if (p == 0) { continue; } pixelTotal++; int gray = ColorConvertTools.pixel2grayValue(p); grayNumber[gray]++; } } float[] grayRadio = new float[256]; for (int i = 0; i < 256; ++i) { if (task != null && !task.isWorking()) { return -1; } grayRadio[i] = grayNumber[i] / pixelTotal; } float backgroundNumber, foregroundNumber, backgoundValue, foregroundValue; float backgoundAverage, foregroundAverage, imageAverage, delta, deltaMax = 0; int threshold = 0; for (int gray = 0; gray < 256; gray++) { if (task != null && !task.isWorking()) { return -1; } backgroundNumber = 0; foregroundNumber = 0; backgoundValue = 0; foregroundValue = 0; for (int i = 0; i < 256; ++i) { if (task != null && !task.isWorking()) { return -1; } if (i <= gray) { backgroundNumber += grayRadio[i]; backgoundValue += i * grayRadio[i]; } else { foregroundNumber += grayRadio[i]; foregroundValue += i * grayRadio[i]; } } backgoundAverage = backgoundValue / backgroundNumber; foregroundAverage = foregroundValue / foregroundNumber; imageAverage = backgoundValue + foregroundValue; delta = backgroundNumber * (backgoundAverage - imageAverage) * (backgoundAverage - imageAverage) + foregroundNumber * (foregroundAverage - imageAverage) * (foregroundAverage - imageAverage); if (delta > deltaMax) { deltaMax = delta; threshold = gray; } } // MyBoxLog.debug("threshold:" + threshold); return threshold; } catch (Exception e) { MyBoxLog.error(e); return -1; } } public static int threshold(FxTask task, File file) { try { BufferedImage bufferImage = ImageFileReaders.readImage(task, file); return threshold(task, bufferImage); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public static int threshold(FxTask task, Image image) { try { return threshold(task, SwingFXUtils.fromFXImage(image, null)); } catch (Exception e) { MyBoxLog.error(e); return -1; } } /* get/set */ public BinaryAlgorithm getAlgorithm() { return algorithm; } public ImageBinary setAlgorithm(BinaryAlgorithm algorithm) { this.algorithm = algorithm; return this; } public int getThreshold() { return threshold; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageCombine.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageCombine.java
package mara.mybox.image.data; import javafx.scene.paint.Color; /** * @Author Mara * @CreateDate 2018-9-6 9:08:16 * @License Apache License Version 2.0 */ public class ImageCombine { private int columnsValue, intervalValue, MarginsValue, arrayType, sizeType; private int eachWidthValue, eachHeightValue, totalWidthValue, totalHeightValue; private Color bgColor = Color.WHITE; public static class ArrayType { public static int SingleColumn = 0; public static int SingleRow = 1; public static int ColumnsNumber = 2; } public static class CombineSizeType { public static int KeepSize = 0; public static int AlignAsBigger = 1; public static int AlignAsSmaller = 2; public static int EachWidth = 3; public static int EachHeight = 4; public static int TotalWidth = 5; public static int TotalHeight = 6; } public ImageCombine() { } public int getColumnsValue() { return columnsValue; } public void setColumnsValue(int columnsValue) { this.columnsValue = columnsValue; } public int getIntervalValue() { return intervalValue; } public void setIntervalValue(int intervalValue) { this.intervalValue = intervalValue; } public int getMarginsValue() { return MarginsValue; } public void setMarginsValue(int MarginsValue) { this.MarginsValue = MarginsValue; } public int getArrayType() { return arrayType; } public void setArrayType(int arrayType) { this.arrayType = arrayType; } public int getSizeType() { return sizeType; } public void setSizeType(int sizeType) { this.sizeType = sizeType; } public int getEachWidthValue() { return eachWidthValue; } public void setEachWidthValue(int eachWidthValue) { this.eachWidthValue = eachWidthValue; } public int getEachHeightValue() { return eachHeightValue; } public void setEachHeightValue(int eachHeightValue) { this.eachHeightValue = eachHeightValue; } public int getTotalWidthValue() { return totalWidthValue; } public void setTotalWidthValue(int totalWidthValue) { this.totalWidthValue = totalWidthValue; } public int getTotalHeightValue() { return totalHeightValue; } public void setTotalHeightValue(int totalHeightValue) { this.totalHeightValue = totalHeightValue; } public Color getBgColor() { return bgColor; } public void setBgColor(Color bgColor) { this.bgColor = bgColor; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageKMeans.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageKMeans.java
package mara.mybox.image.data; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.List; import mara.mybox.color.ColorMatch; import mara.mybox.data.ListKMeans; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-2-20 * @License Apache License Version 2.0 */ public class ImageKMeans extends ListKMeans<Color> { protected ColorMatch colorMatch; protected Color[] colors; protected int dataSize; // can not handle big image public ImageKMeans() { } public static ImageKMeans create() { return new ImageKMeans(); } public ImageKMeans init(BufferedImage image, ColorMatch match) { try { int w = image.getWidth(); int h = image.getHeight(); if (1l * w * h >= Integer.MAX_VALUE) { if (task != null) { task.setError(message("TooLargeToHandle")); } else { MyBoxLog.error(message("TooLargeToHandle")); } return null; } colorMatch = match != null ? match : new ColorMatch(); dataSize = w * h; colors = new Color[dataSize]; int index = 0; for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { colors[index++] = new Color(image.getRGB(x, y)); } } return this; } catch (Exception e) { return null; } } @Override public boolean isDataEmpty() { return colors == null; } @Override public int dataSize() { return dataSize; } @Override public Color getData(int index) { try { return colors[index]; } catch (Exception e) { return null; } } @Override public List<Color> allData() { return Arrays.asList(colors); } @Override public boolean run() { if (colorMatch == null || isDataEmpty()) { return false; } return super.run(); } @Override public double distance(Color p1, Color p2) { try { if (p1 == null || p2 == null) { return Double.MAX_VALUE; } return colorMatch.distance(p1, p2); } catch (Exception e) { MyBoxLog.debug(e); return Double.MAX_VALUE; } } @Override public boolean equal(Color p1, Color p2) { try { if (p1 == null || p2 == null) { return false; } return colorMatch.isMatch(p1, p2); } catch (Exception e) { MyBoxLog.debug(e); return false; } } @Override public Color calculateCenters(List<Integer> cluster) { try { if (cluster == null || cluster.isEmpty()) { return null; } Color color; int r = 0, g = 0, b = 0; for (Integer index : cluster) { if (task != null && !task.isWorking()) { return null; } color = getData(index); if (color == null) { continue; } r += color.getRed(); g += color.getGreen(); b += color.getBlue(); } int size = cluster.size(); color = new Color(r / size, g / size, b / size); return color; } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* get/set */ public double getThreshold() { return colorMatch.getThreshold(); } public ImageKMeans setThreshold(double threshold) { colorMatch.setThreshold(threshold); return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageScopeFactory.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageScopeFactory.java
package mara.mybox.image.data; import javafx.scene.image.Image; import mara.mybox.data.DoubleCircle; import mara.mybox.data.DoublePolygon; import mara.mybox.image.data.ImageScope.ShapeType; import mara.mybox.image.tools.ImageScopeTools; /** * @Author Mara * @CreateDate 2018-8-1 16:22:41 * @License Apache License Version 2.0 */ public class ImageScopeFactory { public static ImageScope create(ImageScope sourceScope) { try { ImageScope newScope; Image image = sourceScope.getImage(); ShapeType shapeType = sourceScope.getShapeType(); if (shapeType == null) { shapeType = ShapeType.Whole; } switch (shapeType) { case Whole: newScope = new Whole(image); break; case Rectangle: newScope = new Rectangle(image); break; case Circle: newScope = new Circle(image); break; case Ellipse: newScope = new Ellipse(image); break; case Polygon: newScope = new Polygon(image); break; case Matting4: newScope = new Matting4(image); break; case Matting8: newScope = new Matting8(image); break; case Outline: newScope = new Outline(image); break; default: newScope = new Whole(image); } ImageScopeTools.cloneValues(newScope, sourceScope); return newScope; } catch (Exception e) { // MyBoxLog.debug(e); return sourceScope; } } static class Whole extends ImageScope { public Whole(Image image) { this.image = image; this.shapeType = ShapeType.Whole; } } static class Rectangle extends ImageScope { public Rectangle(Image image) { this.image = image; this.shapeType = ShapeType.Rectangle; } @Override public boolean inShape(int x, int y) { return ImageScopeTools.inShape(rectangle, shapeExcluded, x, y); } } static class Circle extends ImageScope { public Circle(Image image) { this.image = image; this.shapeType = ShapeType.Circle; if (image != null) { circle = new DoubleCircle(image.getWidth() / 2, image.getHeight() / 2, image.getHeight() / 4); } else { circle = new DoubleCircle(); } } @Override public boolean inShape(int x, int y) { return ImageScopeTools.inShape(circle, shapeExcluded, x, y); } } static class Ellipse extends ImageScope { public Ellipse(Image image) { this.image = image; this.shapeType = ShapeType.Ellipse; } @Override public boolean inShape(int x, int y) { return ImageScopeTools.inShape(ellipse, shapeExcluded, x, y); } } static class Polygon extends ImageScope { public Polygon(Image image) { this.image = image; this.shapeType = ShapeType.Polygon; if (image != null) { polygon = new DoublePolygon(); } } @Override public boolean inShape(int x, int y) { return ImageScopeTools.inShape(polygon, shapeExcluded, x, y); } } static class Outline extends ImageScope { public Outline(Image image) { this.image = image; this.shapeType = ShapeType.Outline; } @Override public boolean inShape(int x, int y) { boolean in = outline != null && outline.getRGB(x, y) > 0; return shapeExcluded ? !in : in; } } static class Matting4 extends ImageScope { public Matting4(Image image) { this.image = image; this.shapeType = ShapeType.Matting4; } } static class Matting8 extends ImageScope { public Matting8(Image image) { this.image = image; this.shapeType = ShapeType.Matting8; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageRegionKMeans.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageRegionKMeans.java
package mara.mybox.image.data; import java.awt.Color; import java.util.List; import mara.mybox.color.ColorMatch; import mara.mybox.data.ListKMeans; import mara.mybox.dev.MyBoxLog; import mara.mybox.image.data.ImageQuantizationFactory.KMeansRegion; /** * @Author Mara * @CreateDate 2019-10-7 * @Version 1.0 * @License Apache License Version 2.0 */ public class ImageRegionKMeans extends ListKMeans<Color> { protected KMeansRegion regionQuantization; protected ColorMatch colorMatch; protected List<Color> colors; public ImageRegionKMeans() { } public static ImageRegionKMeans create() { return new ImageRegionKMeans(); } public ImageRegionKMeans init(KMeansRegion quantization) { try { if (quantization == null) { return this; } regionQuantization = quantization; colorMatch = quantization.colorMatch; colors = regionQuantization.regionColors; } catch (Exception e) { MyBoxLog.debug(e); } return this; } @Override public boolean isDataEmpty() { return colors == null || colors.isEmpty(); } @Override public int dataSize() { return colors.size(); } @Override public Color getData(int index) { return colors.get(index); } @Override public List<Color> allData() { return regionQuantization.regionColors; } @Override public boolean run() { if (colorMatch == null || regionQuantization == null || isDataEmpty() || regionQuantization.rgbPalette.counts == null) { return false; } return super.run(); } @Override public double distance(Color p1, Color p2) { try { if (p1 == null || p2 == null) { return Double.MAX_VALUE; } return colorMatch.distance(p1, p2); } catch (Exception e) { MyBoxLog.debug(e); return Double.MAX_VALUE; } } @Override public boolean equal(Color p1, Color p2) { try { if (p1 == null || p2 == null) { return false; } return colorMatch.isMatch(p1, p2); } catch (Exception e) { MyBoxLog.debug(e); return false; } } @Override public Color calculateCenters(List<Integer> cluster) { try { if (cluster == null || cluster.isEmpty()) { return null; } long maxCount = 0; Color centerColor = null; for (Integer index : cluster) { if (task != null && !task.isWorking()) { return null; } Color regionColor = getData(index); Long colorCount = regionQuantization.rgbPalette.counts.get(regionColor); if (colorCount != null && colorCount > maxCount) { centerColor = regionColor; maxCount = colorCount; } } return centerColor; } catch (Exception e) { MyBoxLog.debug(e); return null; } } @Override public Color preProcess(Color color) { return regionQuantization.map(new Color(color.getRGB(), false)); } /* get/set */ public double getThreshold() { return colorMatch.getThreshold(); } public ImageRegionKMeans setThreshold(double threshold) { colorMatch.setThreshold(threshold); return this; } public KMeansRegion getRegionQuantization() { return regionQuantization; } public ImageRegionKMeans setRegionQuantization(KMeansRegion regionQuantization) { this.regionQuantization = regionQuantization; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageFileInformation.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageFileInformation.java
package mara.mybox.image.data; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.List; import mara.mybox.data.FileInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.tools.FileNameTools; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import thridparty.image4j.ICODecoder; /** * @Author Mara * @CreateDate 2018-6-19 * @License Apache License Version 2.0 */ public class ImageFileInformation extends FileInformation { protected String imageFormat, password; protected ImageInformation imageInformation; protected List<ImageInformation> imagesInformation; protected int numberOfImages; public ImageFileInformation() { } public ImageFileInformation(File file) { super(file); if (file != null) { imageFormat = FileNameTools.ext(file.getName()).toLowerCase(); } } /* static methods */ public static ImageFileInformation create(FxTask task, File file) { return create(task, file, null); } public static ImageFileInformation create(FxTask task, File file, String password) { try { if (file == null || !file.exists()) { return null; } String suffix = FileNameTools.ext(file.getName()); if (suffix != null && suffix.equalsIgnoreCase("pdf")) { return readPDF(task, file, password); } else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) { return readPPT(task, file); } else if (suffix != null && (suffix.equalsIgnoreCase("ico") || suffix.equalsIgnoreCase("icon"))) { return readIconFile(task, file); } else { return readImageFile(task, file); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static ImageFileInformation clone(ImageFileInformation sourceInfo, ImageFileInformation targetInfo) { if (sourceInfo == null || targetInfo == null) { return null; } FileInformation.clone(sourceInfo, targetInfo); targetInfo.imageFormat = sourceInfo.imageFormat; targetInfo.password = sourceInfo.password; targetInfo.imageInformation = sourceInfo.imageInformation; targetInfo.imagesInformation = sourceInfo.imagesInformation; targetInfo.createTime = sourceInfo.createTime; targetInfo.numberOfImages = sourceInfo.numberOfImages; return targetInfo; } public static ImageFileInformation readImageFile(FxTask task, File file) { return ImageFileReaders.readImageFileMetaData(task, file); } public static ImageFileInformation readIconFile(FxTask task, File file) { ImageFileInformation fileInfo = new ImageFileInformation(file); String format = "ico"; fileInfo.setImageFormat(format); try { List<BufferedImage> frames = ICODecoder.read(file); if (frames != null) { int num = frames.size(); fileInfo.setNumberOfImages(num); List<ImageInformation> imagesInfo = new ArrayList<>(); ImageInformation imageInfo; for (int i = 0; i < num; i++) { if (task != null && !task.isWorking()) { return null; } BufferedImage bufferedImage = frames.get(i); imageInfo = ImageInformation.create(format, file); imageInfo.setImageFileInformation(fileInfo); imageInfo.setImageFormat(format); imageInfo.setFile(file); imageInfo.setCreateTime(fileInfo.getCreateTime()); imageInfo.setModifyTime(fileInfo.getModifyTime()); imageInfo.setFileSize(fileInfo.getFileSize()); imageInfo.setWidth(bufferedImage.getWidth()); imageInfo.setHeight(bufferedImage.getHeight()); imageInfo.setIsMultipleFrames(num > 1); imageInfo.setIndex(i); imageInfo.setImageType(BufferedImage.TYPE_INT_ARGB); imageInfo.loadBufferedImage(bufferedImage); imagesInfo.add(imageInfo); } fileInfo.setImagesInformation(imagesInfo); if (!imagesInfo.isEmpty()) { fileInfo.setImageInformation(imagesInfo.get(0)); } } } catch (Exception e) { MyBoxLog.error(e); } return fileInfo; } public static ImageFileInformation readPDF(FxTask task, File file, String password) { ImageFileInformation fileInfo = new ImageFileInformation(file); String format = "png"; fileInfo.setImageFormat(format); fileInfo.setPassword(password); try (PDDocument doc = Loader.loadPDF(file, password)) { int num = doc.getNumberOfPages(); fileInfo.setNumberOfImages(num); List<ImageInformation> imagesInfo = new ArrayList<>(); ImageInformation imageInfo; for (int i = 0; i < num; ++i) { if (task != null && !task.isWorking()) { return null; } PDPage page = doc.getPage(i); PDRectangle rect = page.getBleedBox(); imageInfo = ImageInformation.create(format, file); imageInfo.setImageFileInformation(fileInfo); imageInfo.setImageFormat(format); imageInfo.setPassword(password); imageInfo.setFile(file); imageInfo.setCreateTime(fileInfo.getCreateTime()); imageInfo.setModifyTime(fileInfo.getModifyTime()); imageInfo.setFileSize(fileInfo.getFileSize()); imageInfo.setWidth(Math.round(rect.getWidth())); imageInfo.setHeight(Math.round(rect.getHeight())); imageInfo.setIsMultipleFrames(num > 1); imageInfo.setIndex(i); imageInfo.setImageType(BufferedImage.TYPE_INT_RGB); ImageInformation.checkMem(task, imageInfo); imagesInfo.add(imageInfo); } fileInfo.setImagesInformation(imagesInfo); if (!imagesInfo.isEmpty()) { fileInfo.setImageInformation(imagesInfo.get(0)); } doc.close(); } catch (Exception e) { MyBoxLog.error(e); } return fileInfo; } public static ImageFileInformation readPPT(FxTask task, File file) { ImageFileInformation fileInfo = new ImageFileInformation(file); String format = "png"; fileInfo.setImageFormat(format); try (SlideShow ppt = SlideShowFactory.create(file)) { List<Slide> slides = ppt.getSlides(); int num = slides.size(); slides = null; fileInfo.setNumberOfImages(num); List<ImageInformation> imagesInfo = new ArrayList<>(); ImageInformation imageInfo; int width = (int) Math.ceil(ppt.getPageSize().getWidth()); int height = (int) Math.ceil(ppt.getPageSize().getHeight()); for (int i = 0; i < num; ++i) { if (task != null && !task.isWorking()) { return null; } imageInfo = ImageInformation.create(format, file); imageInfo.setImageFileInformation(fileInfo); imageInfo.setImageFormat(format); imageInfo.setFile(file); imageInfo.setCreateTime(fileInfo.getCreateTime()); imageInfo.setModifyTime(fileInfo.getModifyTime()); imageInfo.setFileSize(fileInfo.getFileSize()); imageInfo.setWidth(width); imageInfo.setHeight(height); imageInfo.setIsMultipleFrames(num > 1); imageInfo.setIndex(i); imageInfo.setImageType(BufferedImage.TYPE_INT_ARGB); ImageInformation.checkMem(task, imageInfo); imagesInfo.add(imageInfo); } fileInfo.setImagesInformation(imagesInfo); if (!imagesInfo.isEmpty()) { fileInfo.setImageInformation(imagesInfo.get(0)); } } catch (Exception e) { MyBoxLog.error(e); } return fileInfo; } /* get/set */ public String getImageFormat() { return imageFormat; } public void setImageFormat(String imageFormat) { this.imageFormat = imageFormat; } public List<ImageInformation> getImagesInformation() { return imagesInformation; } public void setImagesInformation(List<ImageInformation> imagesInformation) { this.imagesInformation = imagesInformation; } public ImageInformation getImageInformation() { return imageInformation; } public void setImageInformation(ImageInformation imageInformation) { this.imageInformation = imageInformation; } public int getNumberOfImages() { return numberOfImages; } public void setNumberOfImages(int numberOfImages) { this.numberOfImages = numberOfImages; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageInformationPng.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageInformationPng.java
package mara.mybox.image.data; import java.io.File; import java.util.List; import mara.mybox.color.CIEData; /** * @Author Mara * @CreateDate 2018-6-19 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image public class ImageInformationPng extends ImageInformation { protected String colorType, compressionMethod, unitSpecifier, filterMethod, interlaceMethod, renderingIntent; protected int pixelsPerUnitXAxis = -1, pixelsPerUnitYAxis = -1, bKGD_Grayscale = -1, bKGD_Palette = -1, sBIT_Grayscale = -1, sBIT_GrayAlpha_gray = -1, sBIT_GrayAlpha_alpha = -1, sBIT_RGB_red = -1, sBIT_RGB_green = -1, sBIT_RGB_blue = -1, sBIT_RGBAlpha_red = -1, sBIT_RGBAlpha_green = -1, sBIT_RGBAlpha_blue = -1, sBIT_RGBAlpha_alpha = -1, sBIT_Palette_red = -1, sBIT_Palette_green = -1, sBIT_Palette_blue = -1, tRNS_Grayscale = -1, tRNS_Palette_index = -1, tRNS_Palette_alpha = -1; protected ImageColor bKGD_RGB, tRNS_RGB; protected List<ImageColor> pngPalette, suggestedPalette; protected int pngPaletteSize, suggestedPaletteSize; protected CIEData white, red, blue, green; public ImageInformationPng(File file) { super(file); } /* get/set */ public String getColorType() { return colorType; } public void setColorType(String colorType) { this.colorType = colorType; } public String getCompressionMethod() { return compressionMethod; } public void setCompressionMethod(String compressionMethod) { this.compressionMethod = compressionMethod; } public String getUnitSpecifier() { return unitSpecifier; } public void setUnitSpecifier(String unitSpecifier) { this.unitSpecifier = unitSpecifier; } public int getPixelsPerUnitXAxis() { return pixelsPerUnitXAxis; } public void setPixelsPerUnitXAxis(int pixelsPerUnitXAxis) { this.pixelsPerUnitXAxis = pixelsPerUnitXAxis; } public int getPixelsPerUnitYAxis() { return pixelsPerUnitYAxis; } public void setPixelsPerUnitYAxis(int pixelsPerUnitYAxis) { this.pixelsPerUnitYAxis = pixelsPerUnitYAxis; } public String getFilterMethod() { return filterMethod; } public void setFilterMethod(String filterMethod) { this.filterMethod = filterMethod; } public String getInterlaceMethod() { return interlaceMethod; } public void setInterlaceMethod(String interlaceMethod) { this.interlaceMethod = interlaceMethod; } public List<ImageColor> getPngPalette() { return pngPalette; } public void setPngPalette(List<ImageColor> pngPalette) { this.pngPalette = pngPalette; } public int getbKGD_Grayscale() { return bKGD_Grayscale; } public void setbKGD_Grayscale(int bKGD_Grayscale) { this.bKGD_Grayscale = bKGD_Grayscale; } public int getbKGD_Palette() { return bKGD_Palette; } public void setbKGD_Palette(int bKGD_Palette) { this.bKGD_Palette = bKGD_Palette; } public ImageColor getbKGD_RGB() { return bKGD_RGB; } public void setbKGD_RGB(ImageColor bKGD_RGB) { this.bKGD_RGB = bKGD_RGB; } public CIEData getWhite() { return white; } public void setWhite(CIEData white) { this.white = white; } public CIEData getRed() { return red; } public void setRed(CIEData red) { this.red = red; } public CIEData getBlue() { return blue; } public void setBlue(CIEData blue) { this.blue = blue; } public CIEData getGreen() { return green; } public void setGreen(CIEData green) { this.green = green; } public String getRenderingIntent() { return renderingIntent; } public void setRenderingIntent(String renderingIntent) { this.renderingIntent = renderingIntent; } public int getsBIT_Grayscale() { return sBIT_Grayscale; } public void setsBIT_Grayscale(int sBIT_Grayscale) { this.sBIT_Grayscale = sBIT_Grayscale; } public int getsBIT_GrayAlpha_gray() { return sBIT_GrayAlpha_gray; } public void setsBIT_GrayAlpha_gray(int sBIT_GrayAlpha_gray) { this.sBIT_GrayAlpha_gray = sBIT_GrayAlpha_gray; } public int getsBIT_GrayAlpha_alpha() { return sBIT_GrayAlpha_alpha; } public void setsBIT_GrayAlpha_alpha(int sBIT_GrayAlpha_alpha) { this.sBIT_GrayAlpha_alpha = sBIT_GrayAlpha_alpha; } public int getsBIT_RGB_red() { return sBIT_RGB_red; } public void setsBIT_RGB_red(int sBIT_RGB_red) { this.sBIT_RGB_red = sBIT_RGB_red; } public int getsBIT_RGB_green() { return sBIT_RGB_green; } public void setsBIT_RGB_green(int sBIT_RGB_green) { this.sBIT_RGB_green = sBIT_RGB_green; } public int getsBIT_RGB_blue() { return sBIT_RGB_blue; } public void setsBIT_RGB_blue(int sBIT_RGB_blue) { this.sBIT_RGB_blue = sBIT_RGB_blue; } public int getsBIT_RGBAlpha_red() { return sBIT_RGBAlpha_red; } public void setsBIT_RGBAlpha_red(int sBIT_RGBAlpha_red) { this.sBIT_RGBAlpha_red = sBIT_RGBAlpha_red; } public int getsBIT_RGBAlpha_green() { return sBIT_RGBAlpha_green; } public void setsBIT_RGBAlpha_green(int sBIT_RGBAlpha_green) { this.sBIT_RGBAlpha_green = sBIT_RGBAlpha_green; } public int getsBIT_RGBAlpha_blue() { return sBIT_RGBAlpha_blue; } public void setsBIT_RGBAlpha_blue(int sBIT_RGBAlpha_blue) { this.sBIT_RGBAlpha_blue = sBIT_RGBAlpha_blue; } public int getsBIT_RGBAlpha_alpha() { return sBIT_RGBAlpha_alpha; } public void setsBIT_RGBAlpha_alpha(int sBIT_RGBAlpha_alpha) { this.sBIT_RGBAlpha_alpha = sBIT_RGBAlpha_alpha; } public int getsBIT_Palette_red() { return sBIT_Palette_red; } public void setsBIT_Palette_red(int sBIT_Palette_red) { this.sBIT_Palette_red = sBIT_Palette_red; } public int getsBIT_Palette_green() { return sBIT_Palette_green; } public void setsBIT_Palette_green(int sBIT_Palette_green) { this.sBIT_Palette_green = sBIT_Palette_green; } public int getsBIT_Palette_blue() { return sBIT_Palette_blue; } public void setsBIT_Palette_blue(int sBIT_Palette_blue) { this.sBIT_Palette_blue = sBIT_Palette_blue; } public List<ImageColor> getSuggestedPalette() { return suggestedPalette; } public void setSuggestedPalette(List<ImageColor> suggestedPalette) { this.suggestedPalette = suggestedPalette; } public int gettRNS_Grayscale() { return tRNS_Grayscale; } public void settRNS_Grayscale(int tRNS_Grayscale) { this.tRNS_Grayscale = tRNS_Grayscale; } public int gettRNS_Palette_index() { return tRNS_Palette_index; } public void settRNS_Palette_index(int tRNS_Palette_index) { this.tRNS_Palette_index = tRNS_Palette_index; } public int gettRNS_Palette_alpha() { return tRNS_Palette_alpha; } public void settRNS_Palette_alpha(int tRNS_Palette_alpha) { this.tRNS_Palette_alpha = tRNS_Palette_alpha; } public ImageColor gettRNS_RGB() { return tRNS_RGB; } public void settRNS_RGB(ImageColor tRNS_RGB) { this.tRNS_RGB = tRNS_RGB; } public int getPngPaletteSize() { return pngPaletteSize; } public void setPngPaletteSize(int pngPaletteSize) { this.pngPaletteSize = pngPaletteSize; } public int getSuggestedPaletteSize() { return suggestedPaletteSize; } public void setSuggestedPaletteSize(int suggestedPaletteSize) { this.suggestedPaletteSize = suggestedPaletteSize; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageStatistic.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageStatistic.java
package mara.mybox.image.data; import mara.mybox.image.tools.ColorConvertTools; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import mara.mybox.image.tools.ColorComponentTools.ColorComponent; import mara.mybox.calculation.IntStatistic; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-2-8 19:26:01 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageStatistic { protected BufferedImage image; protected Map<ColorComponent, ComponentStatistic> data; protected long nonTransparent; public ImageStatistic analyze(FxTask task) { try { if (image == null) { return null; } Color color; long redSum, greenSum, blueSum, alphaSum, hueSum, saturationSum, brightnessSum, graySum; redSum = greenSum = blueSum = alphaSum = hueSum = saturationSum = brightnessSum = graySum = 0; int redMaximum, greenMaximum, blueMaximum, alphaMaximum, hueMaximum, saturationMaximum, brightnessMaximum, grayMaximum; redMaximum = greenMaximum = blueMaximum = alphaMaximum = hueMaximum = saturationMaximum = brightnessMaximum = grayMaximum = 0; int redMinimum, greenMinimum, blueMinimum, alphaMinimum, hueMinimum, saturationMinimum, brightnessMinimum, grayMinimum; redMinimum = greenMinimum = blueMinimum = alphaMinimum = hueMinimum = saturationMinimum = brightnessMinimum = grayMinimum = 255; int v; int[] grayHistogram = new int[256]; int[] redHistogram = new int[256]; int[] greenHistogram = new int[256]; int[] blueHistogram = new int[256]; int[] alphaHistogram = new int[256]; int[] hueHistogram = new int[361]; int[] saturationHistogram = new int[101]; int[] brightnessHistogram = new int[101]; nonTransparent = 0; for (int y = 0; y < image.getHeight(); y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < image.getWidth(); x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { continue; } nonTransparent++; color = new Color(p, true); v = color.getRed(); redHistogram[v]++; redSum += v; if (v > redMaximum) { redMaximum = v; } if (v < redMinimum) { redMinimum = v; } v = color.getGreen(); greenHistogram[v]++; greenSum += v; if (v > greenMaximum) { greenMaximum = v; } if (v < greenMinimum) { greenMinimum = v; } v = color.getBlue(); blueHistogram[v]++; blueSum += v; if (v > blueMaximum) { blueMaximum = v; } if (v < blueMinimum) { blueMinimum = v; } v = color.getAlpha(); alphaHistogram[v]++; alphaSum += v; if (v > alphaMaximum) { alphaMaximum = v; } if (v < alphaMinimum) { alphaMinimum = v; } v = (int) (ColorConvertTools.getHue(color) * 360); hueHistogram[v]++; hueSum += v; if (v > hueMaximum) { hueMaximum = v; } if (v < hueMinimum) { hueMinimum = v; } v = (int) (ColorConvertTools.getSaturation(color) * 100); saturationHistogram[v]++; saturationSum += v; if (v > saturationMaximum) { saturationMaximum = v; } if (v < saturationMinimum) { saturationMinimum = v; } v = (int) (ColorConvertTools.getBrightness(color) * 100); brightnessHistogram[v]++; brightnessSum += v; if (v > brightnessMaximum) { brightnessMaximum = v; } if (v < brightnessMinimum) { brightnessMinimum = v; } v = ColorConvertTools.color2grayValue(color); grayHistogram[v]++; graySum += v; if (v > grayMaximum) { grayMaximum = v; } if (v < grayMinimum) { grayMinimum = v; } } } if (nonTransparent == 0) { return null; } int redMean = (int) (redSum / nonTransparent); int greenMean = (int) (greenSum / nonTransparent); int blueMean = (int) (blueSum / nonTransparent); int alphaMean = (int) (alphaSum / nonTransparent); int hueMean = (int) (hueSum / nonTransparent); int saturationMean = (int) (saturationSum / nonTransparent); int brightnessMean = (int) (brightnessSum / nonTransparent); int grayMean = (int) (graySum / nonTransparent); double redVariable, greenVariable, blueVariable, alphaVariable, hueVariable, saturationVariable, brightnessVariable, grayVariable; redVariable = greenVariable = blueVariable = alphaVariable = hueVariable = saturationVariable = brightnessVariable = grayVariable = 0; double redSkewness, greenSkewness, blueSkewness, alphaSkewness, hueSkewness, saturationSkewness, brightnessSkewness, graySkewness; redSkewness = greenSkewness = blueSkewness = alphaSkewness = hueSkewness = saturationSkewness = brightnessSkewness = graySkewness = 0; double d; for (int y = 0; y < image.getHeight(); y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < image.getWidth(); x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { continue; } color = new Color(p, true); d = color.getRed(); redVariable += Math.pow(d - redMean, 2); redSkewness += Math.pow(d - redMean, 3); d = color.getGreen(); greenVariable += Math.pow(d - greenMean, 2); greenSkewness += Math.pow(d - greenMean, 3); d = color.getBlue(); blueVariable += Math.pow(d - blueMean, 2); blueSkewness += Math.pow(d - blueMean, 3); d = color.getAlpha(); alphaVariable += Math.pow(d - alphaMean, 2); alphaSkewness += Math.pow(d - alphaMean, 3); d = ColorConvertTools.getHue(color) * 100; hueVariable += Math.pow(d - hueMean, 2); hueSkewness += Math.pow(d - hueMean, 3); d = ColorConvertTools.getSaturation(color) * 100; saturationVariable += Math.pow(d - saturationMean, 2); saturationSkewness += Math.pow(d - saturationMean, 3); d = ColorConvertTools.getBrightness(color) * 100; brightnessVariable += Math.pow(d - brightnessMean, 2); brightnessSkewness += Math.pow(d - brightnessMean, 3); d = ColorConvertTools.color2grayValue(color); grayVariable += Math.pow(d - grayMean, 2); graySkewness += Math.pow(d - grayMean, 3); } } double p = 1d / nonTransparent; redVariable = Math.sqrt(redVariable * p); greenVariable = Math.sqrt(greenVariable * p); blueVariable = Math.sqrt(blueVariable * p); alphaVariable = Math.sqrt(alphaVariable * p); hueVariable = Math.sqrt(hueVariable * p); saturationVariable = Math.sqrt(saturationVariable * p); brightnessVariable = Math.sqrt(brightnessVariable * p); grayVariable = Math.sqrt(grayVariable * p); redSkewness = Math.abs(Math.cbrt(redSkewness * p)); greenSkewness = Math.abs(Math.cbrt(greenSkewness * p)); blueSkewness = Math.abs(Math.cbrt(blueSkewness * p)); alphaSkewness = Math.abs(Math.cbrt(alphaSkewness * p)); hueSkewness = Math.abs(Math.cbrt(hueSkewness * p)); saturationSkewness = Math.abs(Math.cbrt(saturationSkewness * p)); brightnessSkewness = Math.abs(Math.cbrt(brightnessSkewness * p)); graySkewness = Math.abs(Math.cbrt(graySkewness * p)); IntStatistic grayStatistic = new IntStatistic(ColorComponent.Gray.name(), graySum, grayMean, (int) grayVariable, (int) graySkewness, grayMinimum, grayMaximum, grayHistogram); ComponentStatistic grayData = ComponentStatistic.create().setComponent(ColorComponent.Gray). setHistogram(grayHistogram).setStatistic(grayStatistic); data.put(ColorComponent.Gray, grayData); IntStatistic redStatistic = new IntStatistic(ColorComponent.RedChannel.name(), redSum, redMean, (int) redVariable, (int) redSkewness, redMinimum, redMaximum, redHistogram); ComponentStatistic redData = ComponentStatistic.create().setComponent(ColorComponent.RedChannel). setHistogram(redHistogram).setStatistic(redStatistic); data.put(ColorComponent.RedChannel, redData); IntStatistic greenStatistic = new IntStatistic(ColorComponent.GreenChannel.name(), greenSum, greenMean, (int) greenVariable, (int) greenSkewness, greenMinimum, greenMaximum, greenHistogram); ComponentStatistic greenData = ComponentStatistic.create().setComponent(ColorComponent.GreenChannel). setHistogram(greenHistogram).setStatistic(greenStatistic); data.put(ColorComponent.GreenChannel, greenData); IntStatistic blueStatistic = new IntStatistic(ColorComponent.BlueChannel.name(), blueSum, blueMean, (int) blueVariable, (int) blueSkewness, blueMinimum, blueMaximum, blueHistogram); ComponentStatistic blueData = ComponentStatistic.create().setComponent(ColorComponent.BlueChannel). setHistogram(blueHistogram).setStatistic(blueStatistic); data.put(ColorComponent.BlueChannel, blueData); IntStatistic hueStatistic = new IntStatistic(ColorComponent.Hue.name(), hueSum, hueMean, (int) hueVariable, (int) hueSkewness, hueMinimum, hueMaximum, hueHistogram); ComponentStatistic hueData = ComponentStatistic.create().setComponent(ColorComponent.Hue). setHistogram(hueHistogram).setStatistic(hueStatistic); data.put(ColorComponent.Hue, hueData); IntStatistic saturationStatistic = new IntStatistic(ColorComponent.Saturation.name(), saturationSum, saturationMean, (int) saturationVariable, (int) saturationSkewness, saturationMinimum, saturationMaximum, saturationHistogram); ComponentStatistic saturationData = ComponentStatistic.create().setComponent(ColorComponent.Saturation). setHistogram(saturationHistogram).setStatistic(saturationStatistic); data.put(ColorComponent.Saturation, saturationData); IntStatistic brightnessStatistic = new IntStatistic(ColorComponent.Brightness.name(), brightnessSum, brightnessMean, (int) brightnessVariable, (int) brightnessSkewness, brightnessMinimum, brightnessMaximum, brightnessHistogram); ComponentStatistic brightnessData = ComponentStatistic.create().setComponent(ColorComponent.Brightness). setHistogram(brightnessHistogram).setStatistic(brightnessStatistic); data.put(ColorComponent.Brightness, brightnessData); IntStatistic alphaStatistic = new IntStatistic(ColorComponent.AlphaChannel.name(), alphaSum, alphaMean, (int) alphaVariable, (int) alphaSkewness, alphaMinimum, alphaMaximum, alphaHistogram); ComponentStatistic alphaData = ComponentStatistic.create().setComponent(ColorComponent.AlphaChannel). setHistogram(alphaHistogram).setStatistic(alphaStatistic); data.put(ColorComponent.AlphaChannel, alphaData); return this; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public ComponentStatistic data(ColorComponent component) { return data.get(component); } public int[] histogram(ColorComponent component) { ComponentStatistic s = data.get(component); return s.getHistogram(); } public IntStatistic statistic(ColorComponent component) { ComponentStatistic s = data.get(component); return s.getStatistic(); } public static int[] grayHistogram(FxTask task, BufferedImage image) { if (image == null) { return null; } BufferedImage grayImage = ImageGray.byteGray(task, image); int[] histogram = new int[256]; for (int y = 0; y < image.getHeight(); y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < image.getWidth(); x++) { int gray = new Color(grayImage.getRGB(x, y)).getRed(); histogram[gray]++; } } return histogram; } /* static */ public static ImageStatistic create(BufferedImage image) { return new ImageStatistic().setImage(image).setData(new HashMap<>()); } public static long nonTransparent(FxTask task, BufferedImage image) { if (image == null) { return 0; } long nonTransparent = 0; for (int y = 0; y < image.getHeight(); y++) { if (task != null && !task.isWorking()) { return -1; } for (int x = 0; x < image.getWidth(); x++) { if (task != null && !task.isWorking()) { return -1; } if (image.getRGB(x, y) == 0) { nonTransparent++; } } } return nonTransparent; } /* get/set */ public BufferedImage getImage() { return image; } public ImageStatistic setImage(BufferedImage image) { this.image = image; return this; } public Map<ColorComponent, ComponentStatistic> getData() { return data; } public ImageStatistic setData(Map<ColorComponent, ComponentStatistic> data) { this.data = data; return this; } public long getNonTransparent() { return nonTransparent; } public void setNonTransparent(long nonTransparent) { this.nonTransparent = nonTransparent; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImagePixel.java
released/MyBox/src/main/java/mara/mybox/image/data/ImagePixel.java
package mara.mybox.image.data; import java.awt.Color; /** * @Author Mara * @CreateDate 2019-10-19 * @Version 1.0 * @License Apache License Version 2.0 */ public class ImagePixel { protected int x, y; protected Color color; public static ImagePixel create(int x, int y, Color color) { return new ImagePixel().setX(x).setY(y).setColor(color); } public static ImagePixel create(Color color) { return new ImagePixel().setColor(color); } public int getX() { return x; } public ImagePixel setX(int x) { this.x = x; return this; } public int getY() { return y; } public ImagePixel setY(int y) { this.y = y; return this; } public Color getColor() { return color; } public ImagePixel setColor(Color color) { this.color = color; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageInformation.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageInformation.java
package mara.mybox.image.data; import mara.mybox.image.tools.ScaleTools; import mara.mybox.image.tools.BufferedImageTools; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.text.MessageFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import mara.mybox.data.DoubleRectangle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.CropTools; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTools; import mara.mybox.value.AppVariables; import static mara.mybox.value.AppVariables.ImageHints; import static mara.mybox.value.Languages.message; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; /** * @Author Mara * @CreateDate 2018-6-19 * @License Apache License Version 2.0 */ public class ImageInformation extends ImageFileInformation { protected ImageFileInformation imageFileInformation; protected ImageInformation self; protected int index, imageType, sampleScale, dpi, xscale, yscale; protected double width, height, requiredWidth, maxWidth, thumbnailRotation; protected String colorSpace, pixelsString, loadSizeString, fileSizeString, profileName, profileCompressionMethod, metaDataXml, error; protected boolean isMultipleFrames, isSampled, isScaled, needSample; protected List<ImageTypeSpecifier> imageTypes; protected ImageTypeSpecifier rawImageType; protected LinkedHashMap<String, Object> standardAttributes, nativeAttributes; protected Map<String, Map<String, List<Map<String, Object>>>> metaData; protected Image image, thumbnail, regionImage; protected long availableMem, bytesSize, requiredMem, totalRequiredMem; protected byte[] iccProfile; protected DoubleRectangle region; public ImageInformation() { initImage(); } public ImageInformation(File file) { super(file); initImage(); if (file != null) { imageFormat = FileNameTools.ext(file.getName()); } if (imageFormat != null) { imageFormat = imageFormat.toLowerCase(); } } public ImageInformation(Image image) { this.image = image; if (image != null) { width = (int) image.getWidth(); height = (int) image.getHeight(); } } public final void initImage() { standardAttributes = new LinkedHashMap(); nativeAttributes = new LinkedHashMap(); imageType = -1; index = 0; duration = 500; dpi = 72; requiredWidth = -1; sampleScale = xscale = yscale = 1; image = null; thumbnail = null; regionImage = null; self = this; } public ImageInformation cloneAttributes() { ImageInformation info = new ImageInformation(); return clone(this, info); } public static ImageInformation clone(ImageInformation sourceInfo, ImageInformation targetInfo) { if (sourceInfo == null || targetInfo == null) { return null; } ImageFileInformation.clone(sourceInfo, targetInfo); if (sourceInfo.imageFileInformation != null) { targetInfo.imageFileInformation = new ImageFileInformation(); ImageFileInformation.clone(sourceInfo.imageFileInformation, targetInfo.imageFileInformation); } targetInfo.self = targetInfo; targetInfo.index = sourceInfo.index; targetInfo.imageType = sourceInfo.imageType; targetInfo.sampleScale = sourceInfo.sampleScale; targetInfo.dpi = sourceInfo.dpi; targetInfo.xscale = sourceInfo.xscale; targetInfo.yscale = sourceInfo.yscale; targetInfo.width = sourceInfo.width; targetInfo.height = sourceInfo.height; targetInfo.requiredWidth = sourceInfo.requiredWidth; targetInfo.maxWidth = sourceInfo.maxWidth; targetInfo.thumbnailRotation = sourceInfo.thumbnailRotation; targetInfo.colorSpace = sourceInfo.colorSpace; targetInfo.pixelsString = sourceInfo.pixelsString; targetInfo.loadSizeString = sourceInfo.loadSizeString; targetInfo.pixelsString = sourceInfo.pixelsString; targetInfo.fileSizeString = sourceInfo.fileSizeString; targetInfo.profileName = sourceInfo.profileName; targetInfo.profileCompressionMethod = sourceInfo.profileCompressionMethod; targetInfo.metaDataXml = sourceInfo.metaDataXml; targetInfo.error = sourceInfo.error; targetInfo.isMultipleFrames = sourceInfo.isMultipleFrames; targetInfo.isSampled = sourceInfo.isSampled; targetInfo.isScaled = sourceInfo.isScaled; targetInfo.needSample = sourceInfo.needSample; targetInfo.region = sourceInfo.region; targetInfo.availableMem = sourceInfo.availableMem; targetInfo.bytesSize = sourceInfo.bytesSize; targetInfo.requiredMem = sourceInfo.requiredMem; targetInfo.totalRequiredMem = sourceInfo.totalRequiredMem; targetInfo.image = sourceInfo.image; targetInfo.thumbnail = sourceInfo.thumbnail; targetInfo.regionImage = sourceInfo.regionImage; targetInfo.metaData = sourceInfo.metaData; targetInfo.standardAttributes = sourceInfo.standardAttributes; targetInfo.nativeAttributes = sourceInfo.nativeAttributes; targetInfo.imageTypes = sourceInfo.imageTypes; targetInfo.rawImageType = sourceInfo.rawImageType; return targetInfo; } public ImageInformation as() { switch (imageFormat.toLowerCase()) { case "png": return (ImageInformationPng) this; default: return this; } } public Image loadImage(FxTask task) { if (region != null) { return readRegion(task, this, -1); } if (image == null || image.getWidth() != width) { image = readImage(task, this); } return image; } public Image loadThumbnail(FxTask task, int thumbWidth) { if (region != null) { thumbnail = readRegion(task, this, thumbWidth); } if (thumbnail == null || (int) (thumbnail.getWidth()) != thumbWidth) { thumbnail = readImage(task, this, thumbWidth); } if (image == null && thumbnail != null && (int) (thumbnail.getWidth()) == width) { image = thumbnail; } return thumbnail; } public Image loadThumbnail(FxTask task) { return loadThumbnail(task, AppVariables.thumbnailWidth); } public void loadBufferedImage(BufferedImage bufferedImage) { if (bufferedImage != null) { thumbnail = SwingFXUtils.toFXImage(bufferedImage, null); isScaled = width > 0 && bufferedImage.getWidth() != (int) width; if (imageType < 0) { imageType = bufferedImage.getType(); } if (width <= 0) { width = bufferedImage.getWidth(); height = bufferedImage.getHeight(); image = thumbnail; } else if (!isScaled) { image = thumbnail; } } else { thumbnail = null; isScaled = false; } } public String sampleInformation(FxTask task, Image image) { int sampledWidth, sampledHeight, sampledSize; if (image != null) { sampledWidth = (int) image.getWidth(); sampledHeight = (int) image.getHeight(); } else { if (width <= 0) { width = 512; } checkMem(task, this); sampledWidth = (int) maxWidth; sampledHeight = (int) (maxWidth * height / width); } int channels = getColorChannels(); int mb = 1024 * 1024; sampledSize = (int) (sampledWidth * sampledHeight * channels / mb); String msg = MessageFormat.format(message("ImageTooLarge"), width, height, channels, bytesSize / mb, requiredMem / mb, availableMem / mb, sampleScale, sampledWidth, sampledHeight, sampledSize); return msg; } @Override public void setFile(File file) { if (imageFileInformation != null) { imageFileInformation.setFile(file); } super.setFile(file); } /* static methods */ public static ImageInformation create(String format, File file) { switch (format.toLowerCase()) { case "png": return new ImageInformationPng(file); default: return new ImageInformation(file); } } public static Image readImage(FxTask task, ImageInformation imageInfo) { if (imageInfo == null) { return null; } return readImage(task, imageInfo, -1); } public static Image readImage(FxTask task, ImageInformation imageInfo, int requiredWidth) { if (imageInfo == null) { return null; } if (imageInfo.getRegion() != null) { return readRegion(task, imageInfo, requiredWidth); } imageInfo.setIsSampled(false); imageInfo.setIsScaled(false); Image targetImage = null; try { int infoWidth = (int) imageInfo.getWidth(); int targetWidth = requiredWidth <= 0 ? infoWidth : requiredWidth; Image image = imageInfo.getImage(); File file = imageInfo.getFile(); if (image != null) { int imageWidth = (int) image.getWidth(); if (imageWidth == targetWidth) { targetImage = image; } else if (file == null || (requiredWidth > 0 && imageWidth > targetWidth)) { targetImage = mara.mybox.fxml.image.ScaleTools.scaleImage(image, targetWidth); } } if (targetImage == null) { Image thumb = imageInfo.getThumbnail(); if (thumb != null) { int thumbWidth = (int) thumb.getWidth(); if (image == null && thumbWidth == infoWidth) { imageInfo.setImage(image); } if (thumbWidth == targetWidth) { targetImage = thumb; } else if (file == null || (requiredWidth > 0 && thumbWidth > targetWidth)) { targetImage = mara.mybox.fxml.image.ScaleTools.scaleImage(thumb, targetWidth); } } } if (targetImage == null && file != null) { BufferedImage bufferedImage; String suffix = FileNameTools.ext(file.getName()); if (suffix != null && suffix.equalsIgnoreCase("pdf")) { bufferedImage = readPDF(imageInfo, targetWidth); } else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) { bufferedImage = readPPT(imageInfo, targetWidth); } else { imageInfo.setRequiredWidth(requiredWidth); bufferedImage = ImageFileReaders.readFrame(task, imageInfo); } if (bufferedImage != null) { targetImage = SwingFXUtils.toFXImage(bufferedImage, null); if (imageInfo.getImageType() < 0) { imageInfo.setImageType(bufferedImage.getType()); } } } if (targetImage != null && infoWidth != (int) targetImage.getWidth()) { imageInfo.setIsScaled(true); if (imageInfo.isNeedSample()) { imageInfo.setIsSampled(true); } } } catch (Exception e) { MyBoxLog.error(e); } return targetImage; } public static BufferedImage readPDF(ImageInformation imageInfo, int width) { BufferedImage bufferedImage = null; try (PDDocument pdfDoc = Loader.loadPDF(imageInfo.getFile(), imageInfo.getPassword())) { bufferedImage = readPDF(null, new PDFRenderer(pdfDoc), ImageType.RGB, imageInfo, width); pdfDoc.close(); } catch (Exception e) { MyBoxLog.error(e); } return bufferedImage; } public static BufferedImage readPDF(FxTask task, PDFRenderer renderer, ImageType imageType, ImageInformation imageInfo, int targetWidth) { if (renderer == null || imageInfo == null) { return null; } BufferedImage bufferedImage = null; try { int dpi = imageInfo.getDpi(); if (dpi <= 0) { dpi = 72; } if (imageType == null) { imageType = ImageType.RGB; } bufferedImage = renderer.renderImageWithDPI(imageInfo.getIndex(), dpi, imageType); if (task != null && task.isCancelled()) { return null; } bufferedImage = scaleImage(task, bufferedImage, imageInfo, targetWidth); } catch (Exception e) { MyBoxLog.debug(e); if (task != null) { task.setError(e.toString()); } } return bufferedImage; } public static BufferedImage scaleImage(FxTask task, BufferedImage inImage, ImageInformation imageInfo, int targetWidth) { if (imageInfo == null) { return null; } try { imageInfo.setThumbnail(null); BufferedImage bufferedImage = inImage; int imageWidth = bufferedImage.getWidth(); imageInfo.setWidth(imageWidth); imageInfo.setHeight(bufferedImage.getHeight()); imageInfo.setImageType(bufferedImage.getType()); DoubleRectangle region = imageInfo.getRegion(); if (region != null) { bufferedImage = mara.mybox.image.data.CropTools.cropOutside(task, inImage, region); if (task != null && task.isCancelled()) { return null; } } if (targetWidth > 0 && imageWidth != targetWidth) { bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, targetWidth); if (task != null && task.isCancelled()) { return null; } } if (ImageHints != null) { bufferedImage = BufferedImageTools.applyRenderHints(bufferedImage, ImageHints); if (task != null && task.isCancelled()) { return null; } } imageInfo.setThumbnail(SwingFXUtils.toFXImage(bufferedImage, null)); return bufferedImage; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } return inImage; } } public static BufferedImage readPPT(ImageInformation imageInfo, int width) { BufferedImage bufferedImage = null; try (SlideShow ppt = SlideShowFactory.create(imageInfo.getFile())) { bufferedImage = readPPT(null, ppt, imageInfo, width); } catch (Exception e) { MyBoxLog.error(e); } return bufferedImage; } public static BufferedImage readPPT(FxTask task, SlideShow ppt, ImageInformation imageInfo, int targetWidth) { if (ppt == null || imageInfo == null) { return null; } BufferedImage bufferedImage = null; try { List<Slide> slides = ppt.getSlides(); int pptWidth = ppt.getPageSize().width; int pptHeight = ppt.getPageSize().height; Slide slide = slides.get(imageInfo.getIndex()); bufferedImage = new BufferedImage(pptWidth, pptHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bufferedImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } if (task != null && task.isCancelled()) { return null; } slide.draw(g); if (task != null && task.isCancelled()) { return null; } bufferedImage = scaleImage(task, bufferedImage, imageInfo, targetWidth); } catch (Exception e) { MyBoxLog.debug(e); if (task != null) { task.setError(e.toString()); } } return bufferedImage; } public static BufferedImage readImage(FxTask task, ImageReader reader, ImageInformation imageInfo, int targetWidth) { if (reader == null || imageInfo == null) { return null; } BufferedImage bufferedImage = null; try { imageInfo.setThumbnail(null); imageInfo.setRequiredWidth(targetWidth); bufferedImage = ImageFileReaders.readFrame(task, reader, imageInfo); if (bufferedImage != null) { imageInfo.setThumbnail(SwingFXUtils.toFXImage(bufferedImage, null)); } } catch (Exception e) { MyBoxLog.debug(e); if (task != null) { task.setError(e.toString()); } } return bufferedImage; } public static Image readRegion(FxTask task, ImageInformation imageInfo, int requireWidth) { if (imageInfo == null) { return null; } DoubleRectangle region = imageInfo.getRegion(); if (region == null) { return readImage(task, imageInfo, requireWidth); } Image regionImage = imageInfo.getRegionImage(); try { int infoWidth = (int) imageInfo.getWidth(); int targetWidth = requireWidth <= 0 ? (int) region.getWidth() : requireWidth; if (regionImage != null && (int) regionImage.getWidth() == targetWidth) { return regionImage; } regionImage = null; imageInfo.setRequiredWidth(targetWidth); Image image = imageInfo.getImage(); if (image != null && (int) image.getWidth() == infoWidth) { regionImage = CropTools.cropOutsideFx(task, image, region); regionImage = mara.mybox.fxml.image.ScaleTools.scaleImage(regionImage, targetWidth); } if (regionImage == null) { Image thumb = imageInfo.getThumbnail(); if (thumb != null && (int) thumb.getWidth() == infoWidth) { regionImage = CropTools.cropOutsideFx(task, thumb, region); regionImage = mara.mybox.fxml.image.ScaleTools.scaleImage(regionImage, targetWidth); } } if (regionImage == null) { File file = imageInfo.getFile(); if (file != null) { BufferedImage bufferedImage; String suffix = FileNameTools.ext(file.getName()); if (suffix != null && suffix.equalsIgnoreCase("pdf")) { bufferedImage = readPDF(imageInfo, targetWidth); } else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) { bufferedImage = readPPT(imageInfo, targetWidth); } else { bufferedImage = ImageFileReaders.readFrame(task, imageInfo); } if (bufferedImage != null) { regionImage = SwingFXUtils.toFXImage(bufferedImage, null); } } } imageInfo.setRegionImage(regionImage); } catch (Exception e) { MyBoxLog.error(e); } return regionImage; } public static BufferedImage readBufferedImage(FxTask task, ImageInformation info) { Image image = readImage(task, info); if (image != null) { return SwingFXUtils.fromFXImage(image, null); } else { return null; } } public static boolean checkMem(FxTask task, ImageInformation imageInfo) { if (imageInfo == null) { return false; } try { if (imageInfo.getWidth() > 0 && imageInfo.getHeight() > 0) { long channels = imageInfo.getColorChannels() > 0 ? imageInfo.getColorChannels() : 4; long bytesSize = (long) (channels * imageInfo.getHeight() * imageInfo.getWidth()); long requiredMem = bytesSize * 6L; Runtime r = Runtime.getRuntime(); long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); if (availableMem < requiredMem) { System.gc(); availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); } imageInfo.setAvailableMem(availableMem); imageInfo.setBytesSize(bytesSize); imageInfo.setRequiredMem(requiredMem); if (availableMem < requiredMem) { int scale = (int) Math.ceil(1d * requiredMem / availableMem); // int scale = (int) Math.sqrt(1d * requiredMem / availableMem); imageInfo.setNeedSample(true); imageInfo.setSampleScale(scale); imageInfo.setMaxWidth(imageInfo.getWidth() / scale); if (task != null) { int sampledWidth = (int) (imageInfo.getWidth() / scale); int sampledHeight = (int) (imageInfo.getHeight() / scale); int sampledSize = (int) (sampledWidth * sampledHeight * imageInfo.getColorChannels() / (1024 * 1024)); String msg = MessageFormat.format(message("ImageTooLarge"), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getColorChannels(), bytesSize / (1024 * 1024), requiredMem / (1024 * 1024), availableMem / (1024 * 1024), sampledWidth, sampledHeight, sampledSize); task.setInfo(msg); } } else { double ratio = Math.sqrt(1d * availableMem / requiredMem); imageInfo.setSampleScale(1); imageInfo.setNeedSample(false); imageInfo.setMaxWidth(imageInfo.getWidth() * ratio); if (task != null) { String msg = message("AvaliableMemory") + ": " + availableMem / (1024 * 1024) + "MB" + "\n" + message("RequireMemory") + ": " + requiredMem / (1024 * 1024) + "MB"; task.setInfo(msg); } } } return true; } catch (Exception e) { imageInfo.setError(e.toString()); MyBoxLog.debug(e); return false; } } /* customized get/set */ public double getWidth() { if (width <= 0 && image != null) { width = (int) image.getWidth(); } return width; } public double getPickedWidth() { return region != null ? region.getWidth() : getWidth(); } public double getHeight() { if (height <= 0 && image != null) { height = image.getHeight(); } return height; } public double getPickedHeight() { return region != null ? region.getHeight() : getHeight(); } public String getPixelsString() { if (region == null) { pixelsString = (int) width + "x" + (int) height; } else { pixelsString = message("Region") + " " + (int) region.getWidth() + "x" + (int) region.getHeight(); } return pixelsString; } public String getLoadSizeString() { if (thumbnail != null) { loadSizeString = (int) thumbnail.getWidth() + "x" + (int) thumbnail.getHeight(); } else { loadSizeString = ""; } return loadSizeString; } public String getFileSizeString() { if (imageFileInformation != null) { fileSizeString = FileTools.showFileSize(imageFileInformation.getFileSize()); } else { fileSizeString = ""; } return fileSizeString; } public ImageInformation setRegion(double x1, double y1, double x2, double y2) { region = DoubleRectangle.xy12(x1, y1, x2, y2); regionImage = null; return this; } /* get/set */ public ImageFileInformation getImageFileInformation() { return imageFileInformation; } public void setImageFileInformation(ImageFileInformation imageFileInformation) { this.imageFileInformation = imageFileInformation; } public int getIndex() { return index; } public ImageInformation setIndex(int index) { this.index = index; return this; } public int getImageType() { return imageType; } public void setImageType(int imageType) { this.imageType = imageType; } public ImageInformation setWidth(double width) { this.width = width; return this; } public void setHeight(double height) { this.height = height; } public String getMetaDataXml() { return metaDataXml; } public void setMetaDataXml(String metaDataXml) { this.metaDataXml = metaDataXml; } public void setImage(Image image) { this.image = image; } public Image getImage() { return image; } public Image getThumbnail() { return thumbnail; } public Map<String, Map<String, List<Map<String, Object>>>> getMetaData() { return metaData; } public void setMetaData( Map<String, Map<String, List<Map<String, Object>>>> metaData) { this.metaData = metaData; } public void setPixelsString(String pixelsString) { this.pixelsString = pixelsString; } public void setLoadSizeString(String loadSizeString) { this.loadSizeString = loadSizeString; } public void setFileSizeString(String fileSizeString) { this.fileSizeString = fileSizeString; } public boolean isIsMultipleFrames() { return isMultipleFrames; } public void setIsMultipleFrames(boolean isMultipleFrames) { this.isMultipleFrames = isMultipleFrames; } public boolean isIsSampled() { return isSampled; } public void setIsSampled(boolean isSampled) { this.isSampled = isSampled; } public boolean isIsScaled() { return isScaled; } public void setIsScaled(boolean isScaled) { this.isScaled = isScaled; } public ImageTypeSpecifier getRawImageType() { return rawImageType; } public void setRawImageType(ImageTypeSpecifier rawImageType) { this.rawImageType = rawImageType; } public List<ImageTypeSpecifier> getImageTypeSpecifiers() { return imageTypes; } public void setImageTypeSpecifiers(List<ImageTypeSpecifier> imageTypes) { this.imageTypes = imageTypes; } public boolean isNeedSample() { return needSample; } public void setNeedSample(boolean needSample) { this.needSample = needSample; } public void setThumbnail(Image thumbnail) { this.thumbnail = thumbnail; } public ImageInformation getSelf() { return self; } public void setSelf(ImageInformation self) { this.self = self; } public long getAvailableMem() { return availableMem; } public void setAvailableMem(long availableMem) { this.availableMem = availableMem; } public long getBytesSize() { return bytesSize; } public void setBytesSize(long bytesSize) { this.bytesSize = bytesSize; } public long getRequiredMem() { return requiredMem; } public void setRequiredMem(long requiredMem) { this.requiredMem = requiredMem; } public long getTotalRequiredMem() { return totalRequiredMem; } public void setTotalRequiredMem(long totalRequiredMem) { this.totalRequiredMem = totalRequiredMem; } public int getSampleScale() { return sampleScale; } public void setSampleScale(int sampleScale) { this.sampleScale = sampleScale; } public String getError() { return error; } public void setError(String error) { this.error = error; } public int getXscale() { return xscale; } public ImageInformation setXscale(int xscale) { this.xscale = xscale; return this; } public int getYscale() { return yscale; } public ImageInformation setYscale(int yscale) { this.yscale = yscale; return this; } public double getRequiredWidth() { return requiredWidth; } public ImageInformation setRequiredWidth(double requiredWidth) { this.requiredWidth = requiredWidth; return this; } public double getMaxWidth() { return maxWidth; } public void setMaxWidth(double maxWidth) { this.maxWidth = maxWidth; } /* attributes */ public LinkedHashMap<String, Object> getStandardAttributes() { return standardAttributes; } public void setStandardAttributes(LinkedHashMap<String, Object> attributes) { this.standardAttributes = attributes; } public Object getStandardAttribute(String key) { try { return standardAttributes.get(key); } catch (Exception e) { return null; } } public String getStandardStringAttribute(String key) { try { return (String) standardAttributes.get(key); } catch (Exception e) { return null; } } public int getStandardIntAttribute(String key) { try { return (int) standardAttributes.get(key); } catch (Exception e) { return -1; } } public float getStandardFloatAttribute(String key) { try { return (float) standardAttributes.get(key); } catch (Exception e) { return -1; } } public boolean getStandardBooleanAttribute(String key) { try { return (boolean) standardAttributes.get(key); } catch (Exception e) { return false; } } public void setStandardAttribute(String key, Object value) { standardAttributes.put(key, value); } public LinkedHashMap<String, Object> getNativeAttributes() { return nativeAttributes; } public void setNativeAttributes( LinkedHashMap<String, Object> nativeAttributes) { this.nativeAttributes = nativeAttributes; } public void setNativeAttribute(String key, Object value) { nativeAttributes.put(key, value); } public Object getNativeAttribute(String key) { try { return nativeAttributes.get(key); } catch (Exception e) { return null; } } public String getColorSpace() { try { return (String) standardAttributes.get("ColorSpace"); } catch (Exception e) { return null; } } public void setColorSpace(String colorSpace) { standardAttributes.put("ColorSpace", colorSpace); } public String getImageRotation() { try { return (String) standardAttributes.get("ImageRotation"); } catch (Exception e) { return null; } } public void setImageRotation(String imageRotation) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageGray.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageGray.java
package mara.mybox.image.data; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.image.tools.AlphaTools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2019-2-15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageGray extends PixelsOperation { public ImageGray() { operationType = OperationType.Gray; } public ImageGray(BufferedImage image) { this.image = image; this.operationType = OperationType.Gray; } public ImageGray(Image image) { this.image = SwingFXUtils.fromFXImage(image, null); this.operationType = OperationType.Gray; } public ImageGray(Image image, ImageScope scope) { this.image = SwingFXUtils.fromFXImage(image, null); this.operationType = OperationType.Gray; this.scope = scope; } public ImageGray(BufferedImage image, ImageScope scope) { this.image = image; this.operationType = OperationType.Gray; this.scope = scope; } @Override protected Color operateColor(Color color) { return ColorConvertTools.color2gray(color); } public static BufferedImage byteGray(FxTask task, BufferedImage srcImage) { try { int width = srcImage.getWidth(); int height = srcImage.getHeight(); BufferedImage naImage = AlphaTools.removeAlpha(task, srcImage, Color.WHITE); BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = grayImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.drawImage(naImage, 0, 0, null); g.dispose(); return grayImage; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static BufferedImage intGray(FxTask task, BufferedImage image) { try { int width = image.getWidth(); int height = image.getHeight(); BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { grayImage.setRGB(x, y, 0); } else { grayImage.setRGB(x, y, ColorConvertTools.pixel2GrayPixel(p)); } } } return grayImage; } catch (Exception e) { MyBoxLog.error(e); return image; } } public static Image gray(FxTask task, Image image) { try { BufferedImage bm = SwingFXUtils.fromFXImage(image, null); bm = intGray(task, bm); if (bm == null || (task != null && !task.isWorking())) { return null; } return SwingFXUtils.toFXImage(bm, null); } catch (Exception e) { MyBoxLog.error(e); return image; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/PixelsBlendFactory.java
released/MyBox/src/main/java/mara/mybox/image/data/PixelsBlendFactory.java
package mara.mybox.image.data; import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.Random; import mara.mybox.image.data.PixelsBlend.ImagesBlendMode; import static mara.mybox.image.data.PixelsBlend.ImagesBlendMode.MULTIPLY; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-3-24 11:24:03 * @License Apache License Version 2.0 */ // https://en.wikipedia.org/wiki/Blend_modes // https://blog.csdn.net/bravebean/article/details/51392440 // https://www.cnblogs.com/bigdream6/p/8385886.html // https://baike.baidu.com/item/%E6%B7%B7%E5%90%88%E6%A8%A1%E5%BC%8F/6700481?fr=aladdin public class PixelsBlendFactory { public static List<String> blendModes() { List<String> names = new ArrayList<>(); for (ImagesBlendMode mode : ImagesBlendMode.values()) { names.add(modeName(mode)); } return names; } public static ImagesBlendMode blendMode(String name) { if (name == null) { return ImagesBlendMode.MULTIPLY; } for (ImagesBlendMode mode : ImagesBlendMode.values()) { if (Languages.matchIgnoreCase(name, modeName(mode))) { return mode; } } return ImagesBlendMode.MULTIPLY; } public static String modeName(ImagesBlendMode mode) { if (mode == null) { return message("MultiplyMode"); } switch (mode) { case KubelkaMunk: return message("KubelkaMunkMode"); case CMYK: return message("CMYKMode"); case CMYK_WEIGHTED: return message("CMYKWeightedMode"); case MULTIPLY: return message("MultiplyMode"); case NORMAL: return message("NormalMode"); case DISSOLVE: return message("DissolveMode"); case DARKEN: return message("DarkenMode"); case COLOR_BURN: return message("ColorBurnMode"); case LINEAR_BURN: return message("LinearBurnMode"); case LIGHTEN: return message("LightenMode"); case SCREEN: return message("ScreenMode"); case COLOR_DODGE: return message("ColorDodgeMode"); case LINEAR_DODGE: return message("LinearDodgeMode"); case DIVIDE: return message("DivideMode"); case VIVID_LIGHT: return message("VividLightMode"); case LINEAR_LIGHT: return message("LinearLightMode"); case SUBTRACT: return message("SubtractMode"); case OVERLAY: return message("OverlayMode"); case HARD_LIGHT: return message("HardLightMode"); case SOFT_LIGHT: return message("SoftLightMode"); case DIFFERENCE: return message("DifferenceMode"); case EXCLUSION: return message("ExclusionMode"); case HUE: return message("HueMode"); case SATURATION: return message("SaturationMode"); case COLOR: return message("ColorMode"); case LUMINOSITY: return message("LuminosityMode"); } return message("MultiplyMode"); } public static PixelsBlend create(ImagesBlendMode blendMode) { if (blendMode == null) { return new MultiplyBlend(); } switch (blendMode) { case KubelkaMunk: return new KubelkaMunkBlend(); case CMYK: return new CMYKBlend(false); case CMYK_WEIGHTED: return new CMYKBlend(true); case NORMAL: return new NormalBlend(); case DISSOLVE: return new DissolveBlend(); case MULTIPLY: return new MultiplyBlend(); case SCREEN: return new ScreenBlend(); case OVERLAY: return new OverlayBlend(); case HARD_LIGHT: return new HardLightBlend(); case SOFT_LIGHT: return new SoftLightBlend(); case COLOR_DODGE: return new ColorDodgeBlend(); case LINEAR_DODGE: return new LinearDodgeBlend(); case DIVIDE: return new DivideBlend(); case COLOR_BURN: return new ColorBurnBlend(); case LINEAR_BURN: return new LinearBurnBlend(); case VIVID_LIGHT: return new VividLightBlend(); case LINEAR_LIGHT: return new LinearLightBlend(); case SUBTRACT: return new SubtractBlend(); case DIFFERENCE: return new DifferenceBlend(); case EXCLUSION: return new ExclusionBlend(); case DARKEN: return new DarkenBlend(); case LIGHTEN: return new LightenBlend(); case HUE: return new HueBlend(); case SATURATION: return new SaturationBlend(); case LUMINOSITY: return new LuminosityBlend(); case COLOR: return new ColorBlend(); default: return new MultiplyBlend(); } } public static class NormalBlend extends PixelsBlend { public NormalBlend() { this.blendMode = ImagesBlendMode.NORMAL; } } public static class DissolveBlend extends PixelsBlend { public DissolveBlend() { this.blendMode = ImagesBlendMode.DISSOLVE; } @Override public void makeRGB() { float random = new Random().nextInt(101) / 100.0f; red = (int) (foreColor.getRed() * random + backColor.getRed() * (1.0f - random)); green = (int) (foreColor.getGreen() * random + backColor.getGreen() * (1.0f - random)); blue = (int) (foreColor.getBlue() * random + backColor.getBlue() * (1.0f - random)); } } public static class KubelkaMunkBlend extends PixelsBlend { public KubelkaMunkBlend() { this.blendMode = ImagesBlendMode.KubelkaMunk; } @Override public void makeRGB() { Color blended = mixPigments(foreColor, backColor, weight); red = blended.getRed(); green = blended.getGreen(); blue = blended.getBlue(); } // Provided by deepseek. public static Color mixPigments(Color color1, Color color2, double ratio) { // 1. 将RGB转换为反射率(0-255 -> 0.0-1.0) double[] reflectance1 = toReflectance(color1); double[] reflectance2 = toReflectance(color2); // 2. 使用Kubelka-Munk公式计算混合后的吸收/散射 double[] mixed = new double[3]; for (int i = 0; i < 3; i++) { double k1 = kmTransform(reflectance1[i]); double k2 = kmTransform(reflectance2[i]); // 3. 按比例混合K值 double kmMixed = ratio * k1 + (1 - ratio) * k2; // 4. 反向转换回反射率 mixed[i] = inverseKmTransform(kmMixed); } // 5. 将反射率转回RGB return toColor(mixed); } // RGB转反射率(简单线性转换) private static double[] toReflectance(Color color) { return new double[]{ color.getRed() / 255.0, color.getGreen() / 255.0, color.getBlue() / 255.0 }; } // Kubelka-Munk变换:反射率 -> K/S值 private static double kmTransform(double reflectance) { return (1 - reflectance) * (1 - reflectance) / (2 * reflectance); } // 反向Kubelka-Munk变换 private static double inverseKmTransform(double km) { double r = 1 + km - Math.sqrt(km * km + 2 * km); // 限制在有效范围内 return Math.max(0, Math.min(1, r)); } // 反射率转RGB private static Color toColor(double[] reflectance) { int r = (int) Math.round(reflectance[0] * 255); int g = (int) Math.round(reflectance[1] * 255); int b = (int) Math.round(reflectance[2] * 255); return new Color( Math.max(0, Math.min(255, r)), Math.max(0, Math.min(255, g)), Math.max(0, Math.min(255, b)) ); } public static void main(String[] args) { // 测试颜料混合 Color cyan = new Color(0, 183, 235); // 青色颜料 Color magenta = new Color(213, 0, 143); // 品红颜料 Color yellow = new Color(252, 220, 0); // 黄色颜料 // 青 + 品红 = 蓝色 Color blue = mixPigments(cyan, magenta, 0.5); System.out.println("Cyan + Magenta = " + formatColor(blue)); // 品红 + 黄 = 红色 Color red = mixPigments(magenta, yellow, 0.5); System.out.println("Magenta + Yellow = " + formatColor(red)); // 青 + 黄 = 绿色 Color green = mixPigments(cyan, yellow, 0.5); System.out.println("Cyan + Yellow = " + formatColor(green)); // 三原色混合 = 黑色 Color black = mixPigments(blue, yellow, 0.5); System.out.println("Blue + Yellow = " + formatColor(black)); } private static String formatColor(Color color) { return String.format("[R=%d, G=%d, B=%d]", color.getRed(), color.getGreen(), color.getBlue()); } } public static class CMYKBlend extends PixelsBlend { private final boolean isWeighted; public CMYKBlend(boolean weighted) { isWeighted = weighted; this.blendMode = isWeighted ? ImagesBlendMode.CMYK_WEIGHTED : ImagesBlendMode.CMYK; } @Override public void makeRGB() { Color blended = isWeighted ? mix(foreColor, backColor, weight) : mix(foreColor, backColor); red = blended.getRed(); green = blended.getGreen(); blue = blended.getBlue(); } // Provided by deepseek. public static Color mix(Color color1, Color color2) { return cmyToRgb(mixColors(rgbToCmy(color1), rgbToCmy(color2))); } public static Color mix(Color color1, Color color2, double w) { return cmyToRgb(mixColors(rgbToCmy(color1), rgbToCmy(color2), w)); } // CMY颜色类(0.0-1.0范围) public static class CMYColor { public double c; // 青 public double m; // 品红 public double y; // 黄 public CMYColor(double c, double m, double y) { this.c = clamp(c); this.m = clamp(m); this.y = clamp(y); } private double clamp(double value) { return Math.max(0.0, Math.min(1.0, value)); } } // RGB转CMY(基于减色原理) public static CMYColor rgbToCmy(Color rgb) { double r = rgb.getRed() / 255.0; double g = rgb.getGreen() / 255.0; double b = rgb.getBlue() / 255.0; double c = 1.0 - r; double m = 1.0 - g; double y = 1.0 - b; return new CMYColor(c, m, y); } // CMY转RGB public static Color cmyToRgb(CMYColor cmy) { double r = (1.0 - cmy.c) * 255; double g = (1.0 - cmy.m) * 255; double b = (1.0 - cmy.y) * 255; return new Color((int) Math.round(r), (int) Math.round(g), (int) Math.round(b)); } // 减色混合核心算法(CMY混合) public static CMYColor mixColors(CMYColor color1, CMYColor color2) { // 减色混合公式:混合后吸收率 = 1 - (1 - c1) * (1 - c2) double c = 1 - (1 - color1.c) * (1 - color2.c); double m = 1 - (1 - color1.m) * (1 - color2.m); double y = 1 - (1 - color1.y) * (1 - color2.y); return new CMYColor(c, m, y); } public static CMYColor mixColors(CMYColor color1, CMYColor color2, double w) { // 减色混合公式:混合后吸收率 = 1 - (1 - c1) * (1 - c2) double w2 = 1 - w; double c = 1 - (1 - color1.c * w) * (1 - color2.c * w2); double m = 1 - (1 - color1.m * w) * (1 - color2.m * w2); double y = 1 - (1 - color1.y * w) * (1 - color2.y * w2); return new CMYColor(c, m, y); } // 调整颜色饱和度(添加补色) public static CMYColor adjustSaturation(CMYColor color, double percent) { // 计算补色(取反) double gray = (color.c + color.m + color.y) / 3.0; CMYColor complementary = new CMYColor( gray + (gray - color.c) * percent, gray + (gray - color.m) * percent, gray + (gray - color.y) * percent ); return mixColors(color, complementary); } // 调整明度(添加黑/白) public static CMYColor adjustBrightness(CMYColor color, double whiteAmount, double blackAmount) { // 添加白色 = 减少CMY值 double c = color.c * (1 - whiteAmount); double m = color.m * (1 - whiteAmount); double y = color.y * (1 - whiteAmount); // 添加黑色 = 增加CMY值 c = c + (1 - c) * blackAmount; m = m + (1 - m) * blackAmount; y = y + (1 - y) * blackAmount; return new CMYColor(c, m, y); } // 示例使用 public static void main(String[] args) { // 创建基础颜色(青、品红、黄) Color cyanRgb = new Color(0, 255, 255); Color magentaRgb = new Color(255, 0, 255); Color yellowRgb = new Color(255, 255, 0); // 转换为CMY CMYColor cyan = rgbToCmy(cyanRgb); CMYColor magenta = rgbToCmy(magentaRgb); CMYColor yellow = rgbToCmy(yellowRgb); // 示例1: 青 + 黄 = 绿 CMYColor green = mixColors(cyan, yellow); Color greenRgb = cmyToRgb(green); System.out.println("青 + 黄 = 绿: RGB(" + greenRgb.getRed() + ", " + greenRgb.getGreen() + ", " + greenRgb.getBlue() + ")"); // 示例2: 品红 + 青 = 蓝 CMYColor blue = mixColors(magenta, cyan); Color blueRgb = cmyToRgb(blue); System.out.println("品红 + 青 = 蓝: RGB(" + blueRgb.getRed() + ", " + blueRgb.getGreen() + ", " + blueRgb.getBlue() + ")"); // 示例3: 调整饱和度 CMYColor desaturated = adjustSaturation(green, -0.5); // 降低50%饱和度 Color desaturatedRgb = cmyToRgb(desaturated); System.out.println("降低饱和度: RGB(" + desaturatedRgb.getRed() + ", " + desaturatedRgb.getGreen() + ", " + desaturatedRgb.getBlue() + ")"); // 示例4: 调整明度 CMYColor darkened = adjustBrightness(green, 0.0, 0.3); // 添加30%黑色 Color darkenedRgb = cmyToRgb(darkened); System.out.println("变暗效果: RGB(" + darkenedRgb.getRed() + ", " + darkenedRgb.getGreen() + ", " + darkenedRgb.getBlue() + ")"); } } public static class MultiplyBlend extends PixelsBlend { public MultiplyBlend() { this.blendMode = ImagesBlendMode.MULTIPLY; } @Override public void makeRGB() { red = foreColor.getRed() * backColor.getRed() / 255; green = foreColor.getGreen() * backColor.getGreen() / 255; blue = foreColor.getBlue() * backColor.getBlue() / 255; } } public static class ScreenBlend extends PixelsBlend { public ScreenBlend() { this.blendMode = ImagesBlendMode.SCREEN; } @Override public void makeRGB() { red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 255; green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 255; blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 255; } } public static class OverlayBlend extends PixelsBlend { public OverlayBlend() { this.blendMode = ImagesBlendMode.OVERLAY; } @Override public void makeRGB() { if (backColor.getRed() < 128) { red = foreColor.getRed() * backColor.getRed() / 128; } else { red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 128; } if (backColor.getGreen() < 128) { green = foreColor.getGreen() * backColor.getGreen() / 128; } else { green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 128; } if (backColor.getBlue() < 128) { blue = foreColor.getBlue() * backColor.getBlue() / 128; } else { blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 128; } } } public static class HardLightBlend extends PixelsBlend { public HardLightBlend() { this.blendMode = ImagesBlendMode.HARD_LIGHT; } @Override public void makeRGB() { if (foreColor.getRed() < 128) { red = foreColor.getRed() * backColor.getRed() / 128; } else { red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 128; } if (foreColor.getGreen() < 128) { green = foreColor.getGreen() * backColor.getGreen() / 128; } else { green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 128; } if (foreColor.getBlue() < 128) { blue = foreColor.getBlue() * backColor.getBlue() / 128; } else { blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 128; } } } public static class SoftLightBlend extends PixelsBlend { public SoftLightBlend() { this.blendMode = ImagesBlendMode.SOFT_LIGHT; } @Override public void makeRGB() { if (foreColor.getRed() < 128) { red = backColor.getRed() + (2 * foreColor.getRed() - 255) * (backColor.getRed() - backColor.getRed() * backColor.getRed() / 255) / 255; } else { red = (int) (backColor.getRed() + (2 * foreColor.getRed() - 255) * (Math.sqrt(backColor.getRed() / 255.0f) * 255 - backColor.getRed()) / 255); } if (foreColor.getGreen() < 128) { green = backColor.getGreen() + (2 * foreColor.getGreen() - 255) * (backColor.getGreen() - backColor.getGreen() * backColor.getGreen() / 255) / 255; } else { green = (int) (backColor.getGreen() + (2 * foreColor.getGreen() - 255) * (Math.sqrt(backColor.getGreen() / 255.0f) * 255 - backColor.getGreen()) / 255); } if (foreColor.getBlue() < 128) { blue = backColor.getBlue() + (2 * foreColor.getBlue() - 255) * (backColor.getBlue() - backColor.getBlue() * backColor.getBlue() / 255) / 255; } else { blue = (int) (backColor.getBlue() + (2 * foreColor.getBlue() - 255) * (Math.sqrt(backColor.getBlue() / 255.0f) * 255 - backColor.getBlue()) / 255); } } } public static class ColorDodgeBlend extends PixelsBlend { public ColorDodgeBlend() { this.blendMode = ImagesBlendMode.COLOR_DODGE; } @Override public void makeRGB() { red = foreColor.getRed() == 255 ? 255 : (backColor.getRed() + (foreColor.getRed() * backColor.getRed()) / (255 - foreColor.getRed())); green = foreColor.getGreen() == 255 ? 255 : (backColor.getGreen() + (foreColor.getGreen() * backColor.getGreen()) / (255 - foreColor.getGreen())); blue = foreColor.getBlue() == 255 ? 255 : (backColor.getBlue() + (foreColor.getBlue() * backColor.getBlue()) / (255 - foreColor.getBlue())); } } public static class LinearDodgeBlend extends PixelsBlend { public LinearDodgeBlend() { this.blendMode = ImagesBlendMode.LINEAR_DODGE; } @Override public void makeRGB() { red = foreColor.getRed() + backColor.getRed(); green = foreColor.getGreen() + backColor.getGreen(); blue = foreColor.getBlue() + backColor.getBlue(); } } public static class DivideBlend extends PixelsBlend { public DivideBlend() { this.blendMode = ImagesBlendMode.DIVIDE; } @Override public void makeRGB() { red = foreColor.getRed() == 0 ? 255 : ((backColor.getRed() * 255) / foreColor.getRed()); green = foreColor.getGreen() == 0 ? 255 : ((backColor.getGreen() * 255) / foreColor.getGreen()); blue = foreColor.getBlue() == 0 ? 255 : ((backColor.getBlue() * 255) / foreColor.getBlue()); } } public static class ColorBurnBlend extends PixelsBlend { public ColorBurnBlend() { this.blendMode = ImagesBlendMode.COLOR_BURN; } @Override public void makeRGB() { red = foreColor.getRed() == 0 ? 0 : (backColor.getRed() - (255 - foreColor.getRed()) * 255 / foreColor.getRed()); green = foreColor.getGreen() == 0 ? 0 : (backColor.getGreen() - (255 - foreColor.getGreen()) * 255 / foreColor.getGreen()); blue = foreColor.getBlue() == 0 ? 0 : (backColor.getBlue() - (255 - foreColor.getBlue()) * 255 / foreColor.getBlue()); } } public static class LinearBurnBlend extends PixelsBlend { public LinearBurnBlend() { this.blendMode = ImagesBlendMode.LINEAR_BURN; } @Override public void makeRGB() { red = backColor.getRed() == 0 ? 0 : foreColor.getRed() + backColor.getRed() - 255; green = backColor.getGreen() == 0 ? 0 : foreColor.getGreen() + backColor.getGreen() - 255; blue = backColor.getBlue() == 0 ? 0 : foreColor.getBlue() + backColor.getBlue() - 255; } } public static class VividLightBlend extends PixelsBlend { public VividLightBlend() { this.blendMode = ImagesBlendMode.VIVID_LIGHT; } @Override public void makeRGB() { if (foreColor.getRed() < 128) { red = foreColor.getRed() == 0 ? backColor.getRed() : (backColor.getRed() - (255 - backColor.getRed()) * (255 - 2 * foreColor.getRed()) / (2 * foreColor.getRed())); } else { red = foreColor.getRed() == 255 ? backColor.getRed() : (backColor.getRed() + backColor.getRed() * (2 * foreColor.getRed() - 255) / (2 * (255 - foreColor.getRed()))); } if (foreColor.getGreen() < 128) { green = foreColor.getGreen() == 0 ? backColor.getGreen() : (backColor.getGreen() - (255 - backColor.getGreen()) * (255 - 2 * foreColor.getGreen()) / (2 * foreColor.getGreen())); } else { green = foreColor.getGreen() == 255 ? backColor.getGreen() : (backColor.getGreen() + backColor.getGreen() * (2 * foreColor.getGreen() - 255) / (2 * (255 - foreColor.getGreen()))); } if (foreColor.getBlue() < 128) { blue = foreColor.getBlue() == 0 ? backColor.getBlue() : (backColor.getBlue() - (255 - backColor.getBlue()) * (255 - 2 * foreColor.getBlue()) / (2 * foreColor.getBlue())); } else { blue = foreColor.getBlue() == 255 ? backColor.getBlue() : (backColor.getBlue() + backColor.getBlue() * (2 * foreColor.getBlue() - 255) / (2 * (255 - foreColor.getBlue()))); } } } public static class LinearLightBlend extends PixelsBlend { public LinearLightBlend() { this.blendMode = ImagesBlendMode.LINEAR_LIGHT; } @Override public void makeRGB() { red = 2 * foreColor.getRed() + backColor.getRed() - 255; green = 2 * foreColor.getGreen() + backColor.getGreen() - 255; blue = 2 * foreColor.getBlue() + backColor.getBlue() - 255; } } public static class SubtractBlend extends PixelsBlend { public SubtractBlend() { this.blendMode = ImagesBlendMode.SUBTRACT; } @Override public void makeRGB() { red = backColor.getRed() - foreColor.getRed(); green = backColor.getGreen() - foreColor.getGreen(); blue = backColor.getBlue() - foreColor.getBlue(); } } public static class DifferenceBlend extends PixelsBlend { public DifferenceBlend() { this.blendMode = ImagesBlendMode.DIFFERENCE; } @Override public void makeRGB() { red = Math.abs(backColor.getRed() - foreColor.getRed()); green = Math.abs(backColor.getGreen() - foreColor.getGreen()); blue = Math.abs(backColor.getBlue() - foreColor.getBlue()); } } public static class ExclusionBlend extends PixelsBlend { public ExclusionBlend() { this.blendMode = ImagesBlendMode.EXCLUSION; } @Override public void makeRGB() { red = backColor.getRed() + foreColor.getRed() - backColor.getRed() * foreColor.getRed() / 128; green = backColor.getGreen() + foreColor.getGreen() - backColor.getGreen() * foreColor.getGreen() / 128; blue = backColor.getBlue() + foreColor.getBlue() - backColor.getBlue() * foreColor.getBlue() / 128; } } public static class DarkenBlend extends PixelsBlend { public DarkenBlend() { this.blendMode = ImagesBlendMode.DARKEN; } @Override public void makeRGB() { red = Math.min(backColor.getRed(), foreColor.getRed()); green = Math.min(backColor.getGreen(), foreColor.getGreen()); blue = Math.min(backColor.getBlue(), foreColor.getBlue()); } } public static class LightenBlend extends PixelsBlend { public LightenBlend() { this.blendMode = ImagesBlendMode.LIGHTEN; } @Override public void makeRGB() { red = Math.max(backColor.getRed(), foreColor.getRed()); green = Math.max(backColor.getGreen(), foreColor.getGreen()); blue = Math.max(backColor.getBlue(), foreColor.getBlue()); } } public static class HueBlend extends PixelsBlend { public HueBlend() { this.blendMode = ImagesBlendMode.HUE; } @Override public int blend(int forePixel, int backPixel) { if (forePixel == 0) { // Pass transparency return backPixel; } if (backPixel == 0) { // Pass transparency return forePixel; } float[] hA = ColorConvertTools.pixel2hsb(forePixel); float[] hB = ColorConvertTools.pixel2hsb(backPixel); Color hColor = Color.getHSBColor(hA[0], hB[1], hB[2]); return hColor.getRGB(); } } public static class SaturationBlend extends PixelsBlend { public SaturationBlend() { this.blendMode = ImagesBlendMode.SATURATION; } @Override public int blend(int forePixel, int backPixel) { if (forePixel == 0) { // Pass transparency return backPixel; } if (backPixel == 0) { // Pass transparency return forePixel; } float[] sA = ColorConvertTools.pixel2hsb(forePixel); float[] sB = ColorConvertTools.pixel2hsb(backPixel); Color sColor = Color.getHSBColor(sB[0], sA[1], sB[2]); return sColor.getRGB(); } } public static class LuminosityBlend extends PixelsBlend { public LuminosityBlend() { this.blendMode = ImagesBlendMode.LUMINOSITY; } @Override public int blend(int forePixel, int backPixel) { if (forePixel == 0) { // Pass transparency return backPixel; } if (backPixel == 0) { // Pass transparency return forePixel; } float[] bA = ColorConvertTools.pixel2hsb(forePixel); float[] bB = ColorConvertTools.pixel2hsb(backPixel); Color newColor = Color.getHSBColor(bB[0], bB[1], bA[2]); return newColor.getRGB(); } } public static class ColorBlend extends PixelsBlend { public ColorBlend() { this.blendMode = ImagesBlendMode.COLOR; } @Override public int blend(int forePixel, int backPixel) { if (forePixel == 0) { // Pass transparency return backPixel; } if (backPixel == 0) { // Pass transparency return forePixel; } float[] cA = ColorConvertTools.pixel2hsb(forePixel); float[] cB = ColorConvertTools.pixel2hsb(backPixel); Color cColor = Color.getHSBColor(cA[0], cA[1], cB[2]); return cColor.getRGB(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/PixelsOperation.java
released/MyBox/src/main/java/mara/mybox/image/data/PixelsOperation.java
package mara.mybox.image.data; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.LinkedList; import java.util.List; import java.util.Queue; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.data.IntPoint; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2019-2-13 14:44:03 * @Description Pixel operations here only involve pixel itself. Pixel * operations which involve other pixels need be defined separately. * @License Apache License Version 2.0 */ public abstract class PixelsOperation { protected BufferedImage srcImage, image; protected boolean isDithering, skipTransparent, excludeScope, boolPara1, boolPara2, boolPara3; protected int intPara1, intPara2, intPara3, scopeColor = 0; protected float floatPara1, floatPara2; protected Color colorPara1, colorPara2; protected ImageScope scope; protected OperationType operationType; protected ColorActionType colorActionType; protected int currentX, currentY; protected Color[] thisLine, nextLine; protected int thisLineY; protected int imageWidth, imageHeight; protected FxTask task; public enum OperationType { Smooth, Denoise, Blur, Sharpen, Clarity, Emboss, EdgeDetect, Thresholding, Quantization, Gray, BlackOrWhite, Sepia, ReplaceColor, Invert, Red, Green, Blue, Yellow, Cyan, Magenta, Mosaic, FrostedGlass, Brightness, Saturation, Hue, Opacity, PreOpacity, RGB, Color, Blend, ShowScope, SelectPixels, Convolution, Contrast } public enum ColorActionType { Set, Increase, Decrease, Filter, Invert } public PixelsOperation() { excludeScope = false; skipTransparent = true; } public PixelsOperation(BufferedImage image, ImageScope scope, OperationType operationType) { srcImage = image; this.image = image; this.operationType = operationType; this.scope = scope; } public BufferedImage start() { return operateImage(); } public Image startFx() { BufferedImage target = start(); if (target == null || taskInvalid()) { return null; } return SwingFXUtils.toFXImage(target, null); } // do not refer this directly protected BufferedImage operateImage() { if (image == null || operationType == null) { return image; } try { imageWidth = image.getWidth(); imageHeight = image.getHeight(); if (operationType != OperationType.BlackOrWhite && operationType != OperationType.Quantization) { isDithering = false; } if (scope != null) { scope = ImageScopeFactory.create(scope); } if (scope != null && (scope.getShapeType() == ImageScope.ShapeType.Matting4 || scope.getShapeType() == ImageScope.ShapeType.Matting8)) { isDithering = false; return operateMatting(); } else { return operateScope(); } } catch (Exception e) { MyBoxLog.error(e); return image; } } private BufferedImage operateScope() { if (image == null) { return image; } try { int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(imageWidth, imageHeight, imageType); boolean inScope; if (isDithering) { thisLine = new Color[imageWidth]; nextLine = new Color[imageWidth]; thisLineY = 0; thisLine[0] = new Color(image.getRGB(0, 0), true); } Color newColor; int pixel; for (int y = 0; y < image.getHeight(); y++) { if (taskInvalid()) { return null; } for (int x = 0; x < image.getWidth(); x++) { if (taskInvalid()) { return null; } pixel = image.getRGB(x, y); Color color = new Color(pixel, true); if (pixel == 0 && skipTransparent) { // transparency need write dithering lines while they affect nothing newColor = skipTransparent(target, x, y); } else { inScope = inScope(x, y, color); if (isDithering && y == thisLineY) { color = thisLine[x]; } if (inScope) { newColor = operatePixel(target, color, x, y); } else { newColor = color; target.setRGB(x, y, color.getRGB()); } } if (isDithering) { dithering(color, newColor, x, y); } } if (isDithering) { thisLine = nextLine; thisLineY = y + 1; nextLine = new Color[imageWidth]; } } thisLine = nextLine = null; return target; } catch (Exception e) { MyBoxLog.error(e); return image; } } // https://en.wikipedia.org/wiki/Flood_fill // https://www.codeproject.com/Articles/6017/QuickFill-An-Efficient-Flood-Fill-Algorithm private BufferedImage operateMatting() { try { if (image == null || scope == null) { return image; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(imageWidth, imageHeight, imageType); boolean excluded = scope.isColorExcluded(); if (excludeScope) { excluded = !excluded; } if (operationType == OperationType.ShowScope) { excluded = !excluded; } if (excluded) { for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { if (taskInvalid()) { return null; } operatePixel(target, x, y); } } } else { target = image.getSubimage(0, 0, imageWidth, imageHeight); } if (taskInvalid()) { return null; } List<IntPoint> points = scope.getPoints(); if (points == null || points.isEmpty()) { return target; } boolean[][] visited = new boolean[imageHeight][imageWidth]; Queue<IntPoint> queue = new LinkedList<>(); boolean eightNeighbor = scope.getShapeType() == ImageScope.ShapeType.Matting8; int x, y; for (IntPoint point : points) { if (taskInvalid()) { return null; } x = point.getX(); y = point.getY(); if (x < 0 || x >= imageWidth || y < 0 || y >= imageHeight) { continue; } Color startColor = new Color(image.getRGB(x, y), true); queue.add(point); while (!queue.isEmpty()) { if (taskInvalid()) { return null; } IntPoint p = queue.remove(); x = p.getX(); y = p.getY(); if (x < 0 || x >= imageWidth || y < 0 || y >= imageHeight || visited[y][x]) { continue; } visited[y][x] = true; int pixel = image.getRGB(x, y); Color color = new Color(pixel, true); if (pixel == 0 && skipTransparent) { skipTransparent(target, x, y); } else if (scope.isMatchColor(startColor, color)) { if (scope.isMatchColors(color)) { if (excluded) { target.setRGB(x, y, pixel); } else { operatePixel(target, color, x, y); } } queue.add(new IntPoint(x + 1, y)); queue.add(new IntPoint(x - 1, y)); queue.add(new IntPoint(x, y + 1)); queue.add(new IntPoint(x, y - 1)); if (eightNeighbor) { queue.add(new IntPoint(x + 1, y + 1)); queue.add(new IntPoint(x + 1, y - 1)); queue.add(new IntPoint(x - 1, y + 1)); queue.add(new IntPoint(x - 1, y - 1)); } } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } protected boolean inScope(int x, int y, Color color) { try { boolean inScope = scope == null || scope.inScope(x, y, color); if (excludeScope) { inScope = !inScope; } return inScope; } catch (Exception e) { return false; } } protected Color skipTransparent(BufferedImage target, int x, int y) { try { target.setRGB(x, y, 0); return Colors.TRANSPARENT; } catch (Exception e) { return null; } } protected Color operatePixel(BufferedImage target, int x, int y) { try { int pixel = image.getRGB(x, y); Color color = new Color(pixel, true); if (pixel == 0 && skipTransparent) { return color; } else { return operatePixel(target, color, x, y); } } catch (Exception e) { return null; } } protected Color operatePixel(BufferedImage target, Color color, int x, int y) { currentX = x; currentY = y; Color newColor = operateColor(color); if (newColor == null) { newColor = color; } target.setRGB(x, y, newColor.getRGB()); return newColor; } // https://en.wikipedia.org/wiki/Dither // https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering protected void dithering(Color color, Color newColor, int x, int y) { if (y != thisLineY) { return; } int red_error, green_error, blue_error; int new_red, new_green, new_blue; red_error = color.getRed() - newColor.getRed(); green_error = color.getGreen() - newColor.getGreen(); blue_error = color.getBlue() - newColor.getBlue(); if (x + 1 < imageWidth) { color = new Color(image.getRGB(x + 1, y), true); new_red = Math.max(Math.min(color.getRed() + red_error * 7 / 16, 255), 0); new_green = Math.max(Math.min(color.getGreen() + green_error * 7 / 16, 255), 0); new_blue = Math.max(Math.min(color.getBlue() + blue_error * 7 / 16, 255), 0); newColor = new Color(new_red, new_green, new_blue, color.getAlpha()); thisLine[x + 1] = newColor; } if (x - 1 >= 0 && y + 1 < imageHeight) { color = new Color(image.getRGB(x - 1, y + 1), true); new_red = Math.max(Math.min(color.getRed() + red_error * 3 / 16, 255), 0); new_green = Math.max(Math.min(color.getGreen() + green_error * 3 / 16, 255), 0); new_blue = Math.max(Math.min(color.getBlue() + blue_error * 3 / 16, 255), 0); newColor = new Color(new_red, new_green, new_blue, color.getAlpha()); nextLine[x - 1] = newColor; } if (y + 1 < imageHeight) { color = new Color(image.getRGB(x, y + 1), true); new_red = Math.max(Math.min(color.getRed() + red_error * 5 / 16, 255), 0); new_green = Math.max(Math.min(color.getGreen() + green_error * 5 / 16, 255), 0); new_blue = Math.max(Math.min(color.getBlue() + blue_error * 5 / 16, 255), 0); newColor = new Color(new_red, new_green, new_blue, color.getAlpha()); nextLine[x] = newColor; } if (x + 1 < imageWidth && y + 1 < imageHeight) { color = new Color(image.getRGB(x + 1, y + 1), true); new_red = Math.max(Math.min(color.getRed() + red_error * 1 / 16, 255), 0); new_green = Math.max(Math.min(color.getGreen() + green_error * 1 / 16, 255), 0); new_blue = Math.max(Math.min(color.getBlue() + blue_error * 1 / 16, 255), 0); newColor = new Color(new_red, new_green, new_blue, color.getAlpha()); nextLine[x + 1] = newColor; } } // SubClass should implement this protected Color operateColor(Color color) { return color; } public boolean taskInvalid() { return task != null && !task.isWorking(); } /* get/set */ public OperationType getOperationType() { return operationType; } public PixelsOperation setOperationType(OperationType operationType) { this.operationType = operationType; return this; } public BufferedImage getImage() { return image; } public PixelsOperation setImage(BufferedImage image) { this.image = image; srcImage = image; return this; } public PixelsOperation setImage(Image image) { this.image = SwingFXUtils.fromFXImage(image, null); return this; } public boolean isIsDithering() { return isDithering; } public PixelsOperation setIsDithering(boolean isDithering) { this.isDithering = isDithering; return this; } public ImageScope getScope() { return scope; } public PixelsOperation setScope(ImageScope scope) { this.scope = scope; return this; } public boolean isBoolPara1() { return boolPara1; } public PixelsOperation setBoolPara1(boolean boolPara1) { this.boolPara1 = boolPara1; return this; } public boolean isBoolPara2() { return boolPara2; } public PixelsOperation setBoolPara2(boolean boolPara2) { this.boolPara2 = boolPara2; return this; } public boolean isBoolPara3() { return boolPara3; } public PixelsOperation setBoolPara3(boolean boolPara3) { this.boolPara3 = boolPara3; return this; } public int getIntPara1() { return intPara1; } public PixelsOperation setIntPara1(int intPara1) { this.intPara1 = intPara1; return this; } public int getIntPara2() { return intPara2; } public PixelsOperation setIntPara2(int intPara2) { this.intPara2 = intPara2; return this; } public int getIntPara3() { return intPara3; } public PixelsOperation setIntPara3(int intPara3) { this.intPara3 = intPara3; return this; } public float getFloatPara1() { return floatPara1; } public PixelsOperation setFloatPara1(float floatPara1) { this.floatPara1 = floatPara1; return this; } public float getFloatPara2() { return floatPara2; } public PixelsOperation setFloatPara2(float floatPara2) { this.floatPara2 = floatPara2; return this; } public Color[] getThisLine() { return thisLine; } public PixelsOperation setThisLine(Color[] thisLine) { this.thisLine = thisLine; return this; } public Color[] getNextLine() { return nextLine; } public PixelsOperation setNextLine(Color[] nextLine) { this.nextLine = nextLine; return this; } public int getThisLineY() { return thisLineY; } public PixelsOperation setThisLineY(int thisLineY) { this.thisLineY = thisLineY; return this; } public int getImageWidth() { return imageWidth; } public void setImageWidth(int imageWidth) { this.imageWidth = imageWidth; } public int getImageHeight() { return imageHeight; } public void setImageHeight(int imageHeight) { this.imageHeight = imageHeight; } public Color getColorPara1() { return colorPara1; } public PixelsOperation setColorPara1(Color colorPara1) { this.colorPara1 = colorPara1; return this; } public Color getColorPara2() { return colorPara2; } public PixelsOperation setColorPara2(Color colorPara2) { this.colorPara2 = colorPara2; return this; } public ColorActionType getColorActionType() { return colorActionType; } public PixelsOperation setColorActionType(ColorActionType colorActionType) { this.colorActionType = colorActionType; return this; } public int getScopeColor() { return scopeColor; } public PixelsOperation setScopeColor(int scopeColor) { this.scopeColor = scopeColor; return this; } public boolean isSkipTransparent() { return skipTransparent; } public PixelsOperation setSkipTransparent(boolean skipTransparent) { this.skipTransparent = skipTransparent; return this; } public boolean isExcludeScope() { return excludeScope; } public PixelsOperation setExcludeScope(boolean excludeScope) { this.excludeScope = excludeScope; return this; } public FxTask getTask() { return task; } public PixelsOperation setTask(FxTask task) { this.task = task; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageQuantization.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageQuantization.java
package mara.mybox.image.data; import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import mara.mybox.color.ColorMatch; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.tools.FloatTools; import mara.mybox.tools.StringTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-2-13 14:44:03 * @License Apache License Version 2.0 */ // http://web.cs.wpi.edu/~matt/courses/cs563/talks/color_quant/CQindex.html public class ImageQuantization extends PixelsOperation { protected ColorMatch colorMatch; protected int maxLoop; public static enum QuantizationAlgorithm { RGBUniformQuantization, HSBUniformQuantization, RegionPopularityQuantization, RegionKMeansClustering, KMeansClustering // MedianCutQuantization, ANN } protected QuantizationAlgorithm algorithm; protected int quantizationSize, regionSize, weight1, weight2, weight3, intValue; protected boolean recordCount, firstColor; protected Map<Color, Long> counts; protected List<ColorCount> sortedCounts; protected long totalCount; protected Color[][][] palette; public ImageQuantization() { operationType = PixelsOperation.OperationType.Quantization; } public ImageQuantization buildPalette() { return this; } public void countColor(Color mappedColor) { if (recordCount) { if (counts == null) { counts = new HashMap<>(); } if (counts.containsKey(mappedColor)) { counts.put(mappedColor, counts.get(mappedColor) + 1); } else { counts.put(mappedColor, Long.valueOf(1)); } } } public static class ColorCount { public Color color; public long count; public ColorCount(Color color, long count) { this.color = color; this.count = count; } } public List<ColorCount> sortCounts(FxTask currentTask) { totalCount = 0; if (counts == null) { return null; } sortedCounts = new ArrayList<>(); for (Color color : counts.keySet()) { if (currentTask != null && !currentTask.isWorking()) { return null; } sortedCounts.add(new ColorCount(color, counts.get(color))); totalCount += counts.get(color); } Collections.sort(sortedCounts, new Comparator<ColorCount>() { @Override public int compare(ColorCount v1, ColorCount v2) { long diff = v2.count - v1.count; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); return sortedCounts; } public StringTable countTable(FxTask currentTask, String name) { try { sortedCounts = sortCounts(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } if (sortedCounts == null || totalCount == 0) { return null; } List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("ID"), message("PixelsNumber"), message("Percentage"), message("Color"), message("Red"), message("Green"), message("Blue"), message("Opacity"), message("Hue"), message("Brightness"), message("Saturation") )); String title = message(algorithm.name()); if (name != null) { title += "_" + name; } StringTable table = new StringTable(names, title); int id = 1; for (ColorCount count : sortedCounts) { if (currentTask != null && !currentTask.isWorking()) { return null; } List<String> row = new ArrayList<>(); javafx.scene.paint.Color color = ColorConvertTools.converColor(count.color); int red = (int) Math.round(color.getRed() * 255); int green = (int) Math.round(color.getGreen() * 255); int blue = (int) Math.round(color.getBlue() * 255); row.addAll(Arrays.asList((id++) + "", StringTools.format(count.count), FloatTools.percentage(count.count, totalCount) + "%", "<DIV style=\"width: 50px; background-color:" + FxColorTools.color2rgb(color) + "; \">&nbsp;&nbsp;&nbsp;</DIV>", red + " ", green + " ", blue + " ", (int) Math.round(color.getOpacity() * 100) + "%", Math.round(color.getHue()) + " ", Math.round(color.getSaturation() * 100) + "%", Math.round(color.getBrightness() * 100) + "%" )); table.add(row); } return table; } catch (Exception e) { MyBoxLog.error(e); return null; } } public String resultInfo() { return null; } @Override public Color operateColor(Color color) { return color; } public ImageRegionKMeans imageRegionKMeans() { try { ImageQuantizationFactory.KMeansRegion regionQuantization = ImageQuantizationFactory.KMeansRegion.create(); regionQuantization.setQuantizationSize(regionSize) .setRegionSize(regionSize) .setFirstColor(firstColor) .setWeight1(weight1).setWeight2(weight2).setWeight3(weight3) .setRecordCount(true) .setColorMatch(colorMatch) .setImage(image).setScope(scope) .setOperationType(PixelsOperation.OperationType.Quantization) .setIsDithering(isDithering) .setTask(task); regionQuantization.buildPalette().start(); ImageRegionKMeans kmeans = ImageRegionKMeans.create(); kmeans.setK(quantizationSize) .setMaxIteration(maxLoop) .setTask(task); if (kmeans.init(regionQuantization).run()) { kmeans.makeMap(); return kmeans; } } catch (Exception e) { MyBoxLog.error(e); } return null; } public ImageKMeans imageKMeans() { try { ImageKMeans kmeans = ImageKMeans.create(); kmeans.setK(quantizationSize) .setMaxIteration(maxLoop) .setTask(task); if (kmeans.init(image, colorMatch).run()) { kmeans.makeMap(); return kmeans; } } catch (Exception e) { MyBoxLog.error(e); } return null; } public class PopularityRegionValue { protected long redAccum, greenAccum, blueAccum, pixelsCount; protected Color regionColor, averageColor; } /* get/set */ public QuantizationAlgorithm getAlgorithm() { return algorithm; } public ImageQuantization setAlgorithm(QuantizationAlgorithm algorithm) { this.algorithm = algorithm; return this; } public int getQuantizationSize() { return quantizationSize; } public ImageQuantization setQuantizationSize(int quantizationSize) { this.quantizationSize = quantizationSize; return this; } public int getWeight1() { return weight1; } public ImageQuantization setWeight1(int weight1) { this.weight1 = weight1; return this; } public int getWeight2() { return weight2; } public ImageQuantization setWeight2(int weight2) { this.weight2 = weight2; return this; } public int getWeight3() { return weight3; } public ImageQuantization setWeight3(int weight3) { this.weight3 = weight3; return this; } public boolean isRecordCount() { return recordCount; } public ImageQuantization setRecordCount(boolean recordCount) { this.recordCount = recordCount; return this; } public Map<Color, Long> getCounts() { return counts; } public ImageQuantization setCounts(Map<Color, Long> counts) { this.counts = counts; return this; } public List<ColorCount> getSortedCounts() { return sortedCounts; } public ImageQuantization setSortedCounts(List<ColorCount> sortedCounts) { this.sortedCounts = sortedCounts; return this; } public long getTotalCount() { return totalCount; } public ImageQuantization setTotalCount(long totalCount) { this.totalCount = totalCount; return this; } public int getIntValue() { return intValue; } public ImageQuantization setIntValue(int intValue) { this.intValue = intValue; return this; } public int getRegionSize() { return regionSize; } public ImageQuantization setRegionSize(int regionSize) { this.regionSize = regionSize; return this; } public boolean isFirstColor() { return firstColor; } public ImageQuantization setFirstColor(boolean firstColor) { this.firstColor = firstColor; return this; } public Color[][][] getPalette() { return palette; } public ImageQuantization setPalette(Color[][][] palette) { this.palette = palette; return this; } public ColorMatch getColorMatch() { return colorMatch; } public ImageQuantization setColorMatch(ColorMatch colorMatch) { this.colorMatch = colorMatch; return this; } public int getMaxLoop() { return maxLoop; } public ImageQuantization setMaxLoop(int maxLoop) { this.maxLoop = maxLoop; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageColor.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageColor.java
package mara.mybox.image.data; import static mara.mybox.value.Languages.message; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ImageColor { private int index, red, green, blue, alpha = 255; public ImageColor(int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; } public ImageColor(int red, int green, int blue, int alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } public ImageColor(int index, int red, int green, int blue, int alpha) { this.index = index; this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } @Override public String toString() { return Languages.message("Red") + ": " + red + Languages.message("Green") + ": " + green + Languages.message("Blue") + ": " + blue + Languages.message("Alpha") + ": " + alpha; } /* get/set */ public int getRed() { return red; } public void setRed(int red) { this.red = red; } public int getGreen() { return green; } public void setGreen(int green) { this.green = green; } public int getBlue() { return blue; } public void setBlue(int blue) { this.blue = blue; } public int getAlpha() { return alpha; } public void setAlpha(int alpha) { this.alpha = alpha; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ComponentStatistic.java
released/MyBox/src/main/java/mara/mybox/image/data/ComponentStatistic.java
package mara.mybox.image.data; import mara.mybox.calculation.IntStatistic; import mara.mybox.image.tools.ColorComponentTools.ColorComponent; /** * @Author Mara * @CreateDate 2019-10-26 * @License Apache License Version 2.0 */ public class ComponentStatistic { protected ColorComponent component; protected IntStatistic statistic; protected int[] histogram; public static ComponentStatistic create() { return new ComponentStatistic(); } /* get/set */ public ColorComponent getComponent() { return component; } public ComponentStatistic setComponent(ColorComponent component) { this.component = component; return this; } public IntStatistic getStatistic() { return statistic; } public ComponentStatistic setStatistic(IntStatistic statistic) { this.statistic = statistic; return this; } public int[] getHistogram() { return histogram; } public ComponentStatistic setHistogram(int[] histogram) { this.histogram = histogram; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageMosaic.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageMosaic.java
package mara.mybox.image.data; import mara.mybox.image.tools.ShapeTools; import java.awt.Color; import java.awt.image.BufferedImage; /** * @Author Mara * @CreateDate 2019-2-15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageMosaic extends PixelsOperation { protected MosaicType type; protected int intensity; public enum MosaicType { Mosaic, FrostedGlass }; public ImageMosaic() { this.operationType = OperationType.Mosaic; this.type = MosaicType.Mosaic; intensity = 20; } public static ImageMosaic create() { return new ImageMosaic(); } @Override protected Color operatePixel(BufferedImage target, Color color, int x, int y) { int newColor = ShapeTools.mosaic(image, imageWidth, imageHeight, x, y, type, intensity); target.setRGB(x, y, newColor); return new Color(newColor, true); } /* set */ public ImageMosaic setType(MosaicType type) { this.type = type; return this; } public ImageMosaic setIntensity(int intensity) { this.intensity = intensity; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageContrast.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageContrast.java
package mara.mybox.image.data; import mara.mybox.image.tools.ColorConvertTools; import java.awt.Color; import java.awt.image.BufferedImage; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-2-17 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageContrast extends PixelsOperation { protected ContrastAlgorithm algorithm; protected long threshold; protected int offset, percentage; public static enum ContrastAlgorithm { GrayHistogramEqualization, GrayHistogramStretching, GrayHistogramShifting, SaturationHistogramEqualization, SaturationHistogramStretching, SaturationHistogramShifting, BrightnessHistogramEqualization, BrightnessHistogramStretching, BrightnessHistogramShifting, SaturationBrightnessHistogramEqualization, SaturationBrightnessHistogramStretching, SaturationBrightnessHistogramShifting } public ImageContrast() { this.operationType = OperationType.Contrast; threshold = 0; percentage = 0; offset = 0; } @Override public BufferedImage operateImage() { if (image == null || operationType != OperationType.Contrast || null == algorithm) { return image; } switch (algorithm) { case GrayHistogramEqualization: return grayHistogramEqualization(task, image); case GrayHistogramStretching: return grayHistogramStretching(task, image, threshold, percentage); case GrayHistogramShifting: return grayHistogramShifting(task, image, offset); case SaturationHistogramEqualization: return saturationHistogramEqualization(task, image); case SaturationHistogramStretching: return saturationHistogramStretching(task, image, threshold, percentage); case SaturationHistogramShifting: return saturationHistogramShifting(task, image, offset); case BrightnessHistogramEqualization: return brightnessHistogramEqualization(task, image); case BrightnessHistogramStretching: return brightnessHistogramStretching(task, image, threshold, percentage); case BrightnessHistogramShifting: return brightnessHistogramShifting(task, image, offset); case SaturationBrightnessHistogramEqualization: return saturationBrightnessHistogramEqualization(task, image); case SaturationBrightnessHistogramStretching: return saturationBrightnessHistogramStretching(task, image, threshold, percentage); case SaturationBrightnessHistogramShifting: return saturationBrightnessHistogramShifting(task, image, offset); default: return image; } } // https://en.wikipedia.org/wiki/Histogram_equalization public static BufferedImage grayHistogramEqualization(FxTask task, BufferedImage image) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] greyHistogram = new long[256]; int pixel, grey; long count = 0; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { continue; } grey = ColorConvertTools.pixel2grayValue(pixel); greyHistogram[grey]++; count++; } } if (count == 0) { return image; } float nf = 255.0f / count; long cumulative = 0; int[] lookUpTable = new int[256]; for (int i = 0; i < 256; ++i) { if (task != null && !task.isWorking()) { return null; } cumulative += greyHistogram[i]; lookUpTable[i] = Math.round(cumulative * nf); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { grey = ColorConvertTools.pixel2grayValue(pixel); grey = lookUpTable[grey]; target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey)); } } } return target; } // https://blog.csdn.net/fang20277/article/details/51801093 public static BufferedImage grayHistogramStretching(FxTask task, BufferedImage image, long threshold, int percentage) { if (image == null || threshold < 0 || percentage < 0) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] greyHistogram = new long[256]; int pixel, grey; long count = 0; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { continue; } grey = ColorConvertTools.pixel2grayValue(pixel); greyHistogram[grey]++; count++; } } if (count == 0) { return image; } int min = 0, max = 0; long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100; for (int i = 0; i < 256; ++i) { if (task != null && !task.isWorking()) { return null; } v = greyHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { min = i; break; } } cumulative = 0; for (int i = 255; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } v = greyHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { max = i; break; } } if (min == max) { return null; } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); float scale = 255.0f / (max - min) + 0.5f; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { grey = ColorConvertTools.pixel2grayValue(pixel); grey = (int) ((grey - min) * scale); if (grey < 0) { grey = 0; } else if (grey > 255) { grey = 255; } target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey)); } } } return target; } public static BufferedImage grayHistogramShifting(FxTask task, BufferedImage image, int offset) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int pixel, grey; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { grey = ColorConvertTools.pixel2grayValue(pixel); grey = Math.max(Math.min(grey + offset, 255), 0); target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey)); } } } return target; } public static BufferedImage saturationHistogramEqualization(FxTask task, BufferedImage image) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] saturationHistogram = new long[101]; long nonTransparent = 0; int saturation; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { continue; } nonTransparent++; saturation = Math.round(ColorConvertTools.getSaturation(new Color(p)) * 100); saturationHistogram[saturation]++; } } if (nonTransparent == 0) { return image; } float nf = 100.0f / nonTransparent; long cumulative = 0; int[] lookUpTable = new int[101]; for (int i = 0; i < 101; ++i) { cumulative += saturationHistogram[i]; lookUpTable[i] = Math.round(cumulative * nf); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int pixel; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturation = lookUpTable[saturation]; target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2])); } } } return target; } public static BufferedImage saturationHistogramStretching(FxTask task, BufferedImage image, long threshold, int percentage) { if (image == null || threshold < 0 || percentage < 0) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] saturationHistogram = new long[101]; long nonTransparent = 0; int saturation, pixel; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { continue; } nonTransparent++; saturation = Math.round(ColorConvertTools.getSaturation(new Color(pixel)) * 100); saturationHistogram[saturation]++; } } if (nonTransparent == 0) { return image; } int min = 0, max = 0; long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100; for (int i = 0; i < 101; ++i) { if (task != null && !task.isWorking()) { return null; } v = saturationHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { min = i; break; } } cumulative = 0; for (int i = 100; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } v = saturationHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { max = i; break; } } if (min == max) { return null; } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); float scale = 100.0f / (max - min); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); if (saturation <= min) { saturation = 0; } else if (saturation >= max) { saturation = 100; } else { saturation = (int) ((saturation - min) * scale); } target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2])); } } } return target; } public static BufferedImage saturationHistogramShifting(FxTask task, BufferedImage image, int offset) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int pixel, saturation; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturation = Math.max(Math.min(saturation + offset, 100), 0); target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2])); } } } return target; } public static BufferedImage brightnessHistogramEqualization(FxTask task, BufferedImage colorImage) { if (colorImage == null) { return null; } int width = colorImage.getWidth(); int height = colorImage.getHeight(); long[] brightnessHistogram = new long[101]; long nonTransparent = 0; int brightness; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = colorImage.getRGB(x, y); if (p == 0) { // ignore transparent continue; } nonTransparent++; brightness = Math.round(ColorConvertTools.getBrightness(new Color(p)) * 100); brightnessHistogram[brightness]++; } } float nf = 100.0f / nonTransparent; long cumulative = 0; int[] lookUpTable = new int[101]; for (int i = 0; i < 101; ++i) { cumulative += brightnessHistogram[i]; lookUpTable[i] = Math.round(cumulative * nf); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = colorImage.getRGB(x, y); if (p == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(p)); brightness = Math.round(hsb[2] * 100); brightness = lookUpTable[brightness]; target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f)); } } } return target; } public static BufferedImage brightnessHistogramStretching(FxTask task, BufferedImage image, long threshold, int percentage) { if (image == null || threshold < 0 || percentage < 0) { return null; } int brightness; int width = image.getWidth(); int height = image.getHeight(); long[] brightnessHistogram = new long[101]; long nonTransparent = 0; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } int p = image.getRGB(x, y); if (p == 0) { continue; } nonTransparent++; brightness = Math.round(ColorConvertTools.getBrightness(new Color(p)) * 100); brightnessHistogram[brightness]++; } } if (nonTransparent == 0) { return image; } int min = 0, max = 0; long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100; for (int i = 0; i < 101; ++i) { if (task != null && !task.isWorking()) { return null; } v = brightnessHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { min = i; break; } } cumulative = 0; for (int i = 100; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } v = brightnessHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { max = i; break; } } if (min == max) { return null; } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); float scale = 100.0f / (max - min); int pixel; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); brightness = Math.round(hsb[2] * 100); if (brightness <= min) { brightness = 0; } else if (brightness >= max) { brightness = 100; } else { brightness = (int) ((brightness - min) * scale); } target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f)); } } } return target; } public static BufferedImage brightnessHistogramShifting(FxTask task, BufferedImage image, int offset) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int pixel, brightness; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); brightness = Math.round(hsb[2] * 100); brightness = Math.max(Math.min(brightness + offset, 100), 0); target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f)); } } } return target; } public static BufferedImage saturationBrightnessHistogramEqualization(FxTask task, BufferedImage image) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] saturationHistogram = new long[101]; long[] brightnessHistogram = new long[101]; long nonTransparent = 0; int pixel, saturation, brightness; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { continue; } nonTransparent++; float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturationHistogram[saturation]++; brightness = Math.round(hsb[2] * 100); brightnessHistogram[brightness]++; } } if (nonTransparent == 0) { return image; } float nf = 100.0f / nonTransparent; long sCumulative = 0, bCumulative = 0; int[] sLlookUpTable = new int[101], bLlookUpTable = new int[101]; for (int i = 0; i < 101; ++i) { sCumulative += saturationHistogram[i]; sLlookUpTable[i] = Math.round(sCumulative * nf); bCumulative += brightnessHistogram[i]; bLlookUpTable[i] = Math.round(bCumulative * nf); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturation = sLlookUpTable[saturation]; brightness = Math.round(hsb[2] * 100); brightness = bLlookUpTable[brightness]; target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f)); } } } return target; } public static BufferedImage saturationBrightnessHistogramStretching(FxTask task, BufferedImage image, long threshold, int percentage) { if (image == null || threshold < 0 || percentage < 0) { return null; } int width = image.getWidth(); int height = image.getHeight(); long[] saturationHistogram = new long[101]; long[] brightnessHistogram = new long[101]; long nonTransparent = 0; int pixel, saturation, brightness; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { continue; } nonTransparent++; float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturationHistogram[saturation]++; brightness = Math.round(hsb[2] * 100); brightnessHistogram[brightness]++; } } if (nonTransparent == 0) { return image; } int sMin = 0, sMax = 0, bMin = 0, bMax = 0; long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100; for (int i = 0; i < 101; ++i) { if (task != null && !task.isWorking()) { return null; } v = saturationHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { sMin = i; break; } } cumulative = 0; for (int i = 100; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } v = saturationHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { sMax = i; break; } } cumulative = 0; for (int i = 0; i < 101; ++i) { if (task != null && !task.isWorking()) { return null; } v = brightnessHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { bMin = i; break; } } cumulative = 0; for (int i = 100; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } v = brightnessHistogram[i]; cumulative += v; if (v > threshold || cumulative > cumulativeThreshold) { bMax = i; break; } } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); float sScale = sMin == sMax ? -1 : (100.0f / (sMax - sMin)); float bScale = bMin == bMax ? -1 : (100.0f / (bMax - bMin)); for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); if (sScale > 0) { if (saturation <= sMin) { saturation = 0; } else if (saturation >= sMax) { saturation = 100; } else { saturation = (int) ((saturation - sMin) * sScale); } } brightness = Math.round(hsb[2] * 100); if (bScale > 0) { if (brightness <= bMin) { brightness = 0; } else if (brightness >= bMax) { brightness = 100; } else { brightness = (int) ((brightness - bMin) * bScale); } } target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f)); } } } return target; } public static BufferedImage saturationBrightnessHistogramShifting(FxTask task, BufferedImage image, int offset) { if (image == null) { return null; } int width = image.getWidth(); int height = image.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int pixel, saturation, brightness; for (int y = 0; y < height; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < width; x++) { if (task != null && !task.isWorking()) { return null; } pixel = image.getRGB(x, y); if (pixel == 0) { target.setRGB(x, y, 0); } else { float[] hsb = ColorConvertTools.color2hsb(new Color(pixel)); saturation = Math.round(hsb[1] * 100); saturation = Math.max(Math.min(saturation + offset, 100), 0); brightness = Math.round(hsb[2] * 100); brightness = Math.max(Math.min(brightness + offset, 100), 0); target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f)); } } } return target; } /* get/set */ public ContrastAlgorithm getAlgorithm() { return algorithm; } public ImageContrast setAlgorithm(ContrastAlgorithm algorithm) { this.algorithm = algorithm; return this; } public long getThreshold() { return threshold; } public ImageContrast setThreshold(long thresholdValue) { this.threshold = thresholdValue; return this; } public int getPercentage() { return percentage; } public ImageContrast setPercentage(int percentage) { this.percentage = percentage; return this; } public int getOffset() { return offset; } public ImageContrast setOffset(int offset) { this.offset = offset; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageConvolution.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageConvolution.java
package mara.mybox.image.data; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.tools.AlphaTools; import mara.mybox.tools.FloatMatrixTools; /** * @Author Mara * @CreateDate 2018-11-10 19:35:49 * @License Apache License Version 2.0 */ public class ImageConvolution extends PixelsOperation { protected ConvolutionKernel kernel; protected int matrixWidth, matrixHeight, edge_op, color_op, radiusX, radiusY, maxX, maxY; protected boolean keepOpacity, isEmboss, isInvert; protected float[][] matrix; protected int[][] intMatrix; protected int intScale; public static enum SmoothAlgorithm { GaussianBlur, AverageBlur, MotionBlur } public static enum SharpenAlgorithm { UnsharpMasking, EightNeighborLaplace, FourNeighborLaplace } public ImageConvolution() { this.operationType = OperationType.Convolution; } public static ImageConvolution create() { return new ImageConvolution(); } public ImageConvolution setKernel(ConvolutionKernel kernel) { this.kernel = kernel; matrix = kernel.getMatrix(); matrixWidth = matrix[0].length; matrixHeight = matrix.length; intMatrix = new int[matrixHeight][matrixWidth]; intScale = 10000; // Run integer calcualation instead of float/double calculation for (int matrixY = 0; matrixY < matrixHeight; matrixY++) { for (int matrixX = 0; matrixX < matrixWidth; matrixX++) { intMatrix[matrixY][matrixX] = Math.round(matrix[matrixY][matrixX] * intScale); } } edge_op = kernel.getEdge(); radiusX = matrixWidth / 2; radiusY = matrixHeight / 2; maxX = image.getWidth() - 1; maxY = image.getHeight() - 1; isEmboss = (kernel.getType() == ConvolutionKernel.Convolution_Type.EMBOSS); color_op = kernel.getColor(); keepOpacity = (kernel.getType() != ConvolutionKernel.Convolution_Type.EMBOSS && kernel.getType() != ConvolutionKernel.Convolution_Type.EDGE_DETECTION); isInvert = kernel.isInvert(); return this; } @Override public BufferedImage start() { if (image == null || kernel == null || kernel.getMatrix() == null) { return image; } return super.start(); } @Override protected BufferedImage operateImage() { if (image == null || operationType == null) { return image; } if (scope == null || scope.isWhole()) { return applyConvolution(task, image, kernel); } BufferedImage target = super.operateImage(); if (kernel.isGrey()) { target = ImageGray.byteGray(task, target); } else if (kernel.isBW()) { target = ImageBinary.byteBinary(task, target); } return target; } @Override protected Color operatePixel(BufferedImage target, Color color, int x, int y) { Color newColor = applyConvolution(x, y); if (isEmboss) { int v = 128, red, blue, green; red = Math.min(Math.max(newColor.getRed() + v, 0), 255); green = Math.min(Math.max(newColor.getGreen() + v, 0), 255); blue = Math.min(Math.max(newColor.getBlue() + v, 0), 255); newColor = new Color(red, green, blue, newColor.getAlpha()); } target.setRGB(x, y, newColor.getRGB()); return newColor; } public Color applyConvolution(int x, int y) { try { int red = 0, green = 0, blue = 0, opacity = 0; int convolveX, convolveY; matrix: for (int matrixY = 0; matrixY < matrixHeight; matrixY++) { if (taskInvalid()) { return null; } for (int matrixX = 0; matrixX < matrixWidth; matrixX++) { if (taskInvalid()) { return null; } convolveX = x - radiusX + matrixX; convolveY = y - radiusY + matrixY; if (convolveX < 0 || convolveX > maxX || convolveY < 0 || convolveY > maxY) { if (edge_op == ConvolutionKernel.Edge_Op.COPY) { Color color = new Color(image.getRGB(x, y), true); red = color.getRed(); green = color.getGreen(); blue = color.getBlue(); opacity = color.getAlpha(); break matrix; } else { /* fill zero */ continue; } } Color color = new Color(image.getRGB(convolveX, convolveY), true); red += color.getRed() * intMatrix[matrixY][matrixX]; green += color.getGreen() * intMatrix[matrixY][matrixX]; blue += color.getBlue() * intMatrix[matrixY][matrixX]; if (keepOpacity) { opacity += color.getAlpha() * intMatrix[matrixY][matrixX]; } } } red = Math.min(Math.max(red / intScale, 0), 255); green = Math.min(Math.max(green / intScale, 0), 255); blue = Math.min(Math.max(blue / intScale, 0), 255); if (keepOpacity) { opacity = Math.min(Math.max(opacity / intScale, 0), 255); } else { opacity = 255; } Color color; if (isInvert) { color = new Color(255 - red, 255 - green, 255 - blue, opacity); } else { color = new Color(red, green, blue, opacity); } return color; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* static */ public static BufferedImage applyConvolution(FxTask task, BufferedImage inSource, ConvolutionKernel convolutionKernel) { BufferedImage source; int type = convolutionKernel.getType(); if (type == ConvolutionKernel.Convolution_Type.EDGE_DETECTION || type == ConvolutionKernel.Convolution_Type.EMBOSS) { source = AlphaTools.removeAlpha(task, inSource); } else { source = inSource; } if (task != null && !task.isWorking()) { return null; } float[] k = FloatMatrixTools.matrix2Array(task, convolutionKernel.getMatrix()); if (task != null && !task.isWorking()) { return null; } if (k == null) { return source; } int w = convolutionKernel.getWidth(); int h = convolutionKernel.getHeight(); Kernel kernel = new Kernel(w, h, k); ConvolveOp imageOp; if (convolutionKernel.getEdge() == ConvolutionKernel.Edge_Op.COPY) { imageOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); } else { imageOp = new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL, null); } BufferedImage target = applyConvolveOp(source, imageOp); if (task != null && !task.isWorking()) { return null; } if (type == ConvolutionKernel.Convolution_Type.EMBOSS) { PixelsOperation pixelsOperation = PixelsOperationFactory.create(target, null, OperationType.RGB, ColorActionType.Increase); pixelsOperation.setIntPara1(128).setTask(task); target = pixelsOperation.start(); if (task != null && !task.isWorking()) { return null; } } if (convolutionKernel.isInvert()) { PixelsOperation pixelsOperation = PixelsOperationFactory.create(target, null, OperationType.RGB, ColorActionType.Invert).setTask(task); target = pixelsOperation.start(); if (task != null && !task.isWorking()) { return null; } } if (convolutionKernel.isGrey()) { target = ImageGray.byteGray(task, target); } else if (convolutionKernel.isBW()) { target = ImageBinary.byteBinary(task, target); } if (task != null && !task.isWorking()) { return null; } return target; } // source should have no alpha public static BufferedImage applyConvolveOp(BufferedImage source, ConvolveOp imageOp) { if (source == null || imageOp == null) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = source.getType(); if (imageType == BufferedImage.TYPE_CUSTOM) { imageType = BufferedImage.TYPE_INT_RGB; } BufferedImage target = new BufferedImage(width, height, imageType); imageOp.filter(source, target); return target; } /* get/set */ @Override public ImageConvolution setImage(BufferedImage image) { this.image = image; return this; } @Override public ImageConvolution setImage(Image image) { this.image = SwingFXUtils.fromFXImage(image, null); return this; } @Override public ImageConvolution setScope(ImageScope scope) { this.scope = scope; return this; } public ConvolutionKernel getKernel() { return kernel; } public int[][] getIntMatrix() { return intMatrix; } public ImageConvolution setIntMatrix(int[][] intMatrix) { this.intMatrix = intMatrix; return this; } public int getIntScale() { return intScale; } public ImageConvolution setSum(int sum) { this.intScale = sum; return this; } public int getMatrixWidth() { return matrixWidth; } public ImageConvolution setMatrixWidth(int matrixWidth) { this.matrixWidth = matrixWidth; return this; } public int getMatrixHeight() { return matrixHeight; } public ImageConvolution setMatrixHeight(int matrixHeight) { this.matrixHeight = matrixHeight; return this; } public int getEdge_op() { return edge_op; } public ImageConvolution setEdge_op(int edge_op) { this.edge_op = edge_op; return this; } public int getRadiusX() { return radiusX; } public ImageConvolution setRadiusX(int radiusX) { this.radiusX = radiusX; return this; } public int getRadiusY() { return radiusY; } public ImageConvolution setRadiusY(int radiusY) { this.radiusY = radiusY; return this; } public int getMaxX() { return maxX; } public ImageConvolution setMaxX(int maxX) { this.maxX = maxX; return this; } public int getMaxY() { return maxY; } public ImageConvolution setMaxY(int maxY) { this.maxY = maxY; return this; } public boolean isKeepOpacity() { return keepOpacity; } public ImageConvolution setKeepOpacity(boolean keepOpacity) { this.keepOpacity = keepOpacity; return this; } public boolean isIsEmboss() { return isEmboss; } public ImageConvolution setIsEmboss(boolean isEmboss) { this.isEmboss = isEmboss; return this; } public int getColor() { return color_op; } public ImageConvolution setColor(int color_op) { this.color_op = color_op; return this; } public boolean isIsInvert() { return isInvert; } public ImageConvolution setIsInvert(boolean isInvert) { this.isInvert = isInvert; return this; } public float[][] getMatrix() { return matrix; } public ImageConvolution setMatrix(float[][] matrix) { this.matrix = matrix; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageAttributes.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageAttributes.java
package mara.mybox.image.data; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import mara.mybox.value.FileExtensions; import org.apache.pdfbox.rendering.ImageType; /** * @Author Mara * @CreateDate 2018-6-18 6:53:00 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageAttributes { public static enum Alpha { Keep, Remove, PremultipliedAndKeep, PremultipliedAndRemove } protected String imageFormat, compressionType, colorSpaceName; protected ImageType colorType; protected int density, quality, ratioAdjustion, width; protected Alpha alpha; protected ImageBinary imageBinary; protected boolean embedProfile, keepRatio; protected int sourceWidth, sourceHeight, targetWidth, targetHeight; protected ICC_Profile profile; protected String profileName; public ImageAttributes() { init(null, null); } public ImageAttributes(String format, ImageType colorSpace, int density) { init(null, format); this.colorType = colorSpace; this.density = density; this.quality = 100; imageBinary = null; } public ImageAttributes(BufferedImage image, String format) { init(image, format); } public ImageAttributes(String format) { init(null, format); } private void init(BufferedImage image, String format) { if (format == null || !FileExtensions.SupportedImages.contains(format)) { format = "png"; } imageFormat = format.toLowerCase(); switch (imageFormat) { case "jpg": case "jpeg": compressionType = "JPEG"; alpha = Alpha.Remove; break; case "gif": compressionType = "LZW"; break; case "tif": case "tiff": if (image != null && image.getType() == BufferedImage.TYPE_BYTE_BINARY) { compressionType = "CCITT T.6"; } else { compressionType = "Deflate"; } break; case "bmp": compressionType = "BI_RGB"; alpha = Alpha.Remove; break; } density = 96; quality = 100; } /* get/set */ public String getImageFormat() { return imageFormat; } public ImageAttributes setImageFormat(String imageFormat) { this.imageFormat = imageFormat; return this; } public int getDensity() { return density; } public ImageAttributes setDensity(int density) { this.density = density; return this; } public String getCompressionType() { return compressionType; } public ImageAttributes setCompressionType(String compressionType) { this.compressionType = compressionType; return this; } public int getTargetWidth() { return targetWidth; } public ImageAttributes setTargetWidth(int targetWidth) { this.targetWidth = targetWidth; return this; } public int getTargetHeight() { return targetHeight; } public ImageAttributes setTargetHeight(int targetHeight) { this.targetHeight = targetHeight; return this; } public ImageType getColorType() { return colorType; } public ImageAttributes setColorType(ImageType colorType) { this.colorType = colorType; return this; } public int getQuality() { return quality; } public ImageAttributes setQuality(int quality) { this.quality = quality; return this; } public int getRatioAdjustion() { return ratioAdjustion; } public ImageAttributes setRatioAdjustion(int ratioAdjustion) { this.ratioAdjustion = ratioAdjustion; return this; } public boolean isKeepRatio() { return keepRatio; } public ImageAttributes setKeepRatio(boolean keepRatio) { this.keepRatio = keepRatio; return this; } public int getSourceWidth() { return sourceWidth; } public ImageAttributes setSourceWidth(int sourceWidth) { this.sourceWidth = sourceWidth; return this; } public int getSourceHeight() { return sourceHeight; } public ImageAttributes setSourceHeight(int sourceHeight) { this.sourceHeight = sourceHeight; return this; } public ImageBinary getImageBinary() { return imageBinary; } public ImageAttributes setImageBinary(ImageBinary imageBinary) { this.imageBinary = imageBinary; return this; } public ICC_Profile getProfile() { return profile; } public ImageAttributes setProfile(ICC_Profile profile) { this.profile = profile; return this; } public String getProfileName() { return profileName; } public ImageAttributes setProfileName(String profileName) { this.profileName = profileName; return this; } public String getColorSpaceName() { return colorSpaceName; } public ImageAttributes setColorSpaceName(String colorSpaceName) { this.colorSpaceName = colorSpaceName; return this; } public Alpha getAlpha() { return alpha; } public ImageAttributes setAlpha(Alpha alpha) { this.alpha = alpha; return this; } public boolean isEmbedProfile() { return embedProfile; } public ImageAttributes setEmbedProfile(boolean embedProfile) { this.embedProfile = embedProfile; return this; } public int getWidth() { return width; } public ImageAttributes setWidth(int width) { this.width = width; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/CropTools.java
released/MyBox/src/main/java/mara/mybox/image/data/CropTools.java
package mara.mybox.image.data; import mara.mybox.image.tools.ScaleTools; import java.awt.Color; import java.awt.image.BufferedImage; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.DoubleShape; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class CropTools { public static BufferedImage cropInside(FxTask task, BufferedImage source, DoubleRectangle rect, Color bgColor) { try { if (rect == null || rect.isEmpty()) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); int bgPixel = bgColor.getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (DoubleShape.contains(rect, i, j)) { target.setRGB(i, j, bgPixel); } else { target.setRGB(i, j, source.getRGB(i, j)); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage cropOutside(FxTask task, BufferedImage source, DoubleRectangle rect, Color bgColor) { try { if (source == null || rect == null || rect.isEmpty()) { return source; } int width = source.getWidth(); int height = source.getHeight(); int x1 = Math.max(0, (int) Math.ceil(rect.getX())); int y1 = Math.max(0, (int) Math.ceil(rect.getY())); if (x1 > width || y1 > height) { return null; } int x2 = Math.min(width, (int) Math.floor(rect.getMaxX())); int y2 = Math.min(height, (int) Math.floor(rect.getMaxY())); int w = x2 - x1; int h = y2 - y1; int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(w, h, imageType); int bgPixel = bgColor.getRGB(); for (int y = 0; y < h; y++) { if (task != null && !task.isWorking()) { return null; } for (int x = 0; x < w; x++) { if (task != null && !task.isWorking()) { return null; } if (rect.contains(x1 + x, y1 + y)) { target.setRGB(x, y, source.getRGB(x1 + x, y1 + y)); } else { target.setRGB(x, y, bgPixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage cropOutside(FxTask task, BufferedImage source, DoubleRectangle rect) { return cropOutside(task, source, rect, Colors.TRANSPARENT); } public static BufferedImage cropOutside(FxTask task, BufferedImage source, double x1, double y1, double x2, double y2) { return cropOutside(task, source, DoubleRectangle.xy12(x1, y1, x2, y2), Colors.TRANSPARENT); } public static BufferedImage sample(FxTask task, BufferedImage source, DoubleRectangle rectangle, int xscale, int yscale) { try { if (rectangle == null) { return ScaleTools.scaleImageByScale(source, xscale, yscale); } int realXScale = xscale > 0 ? xscale : 1; int realYScale = yscale > 0 ? yscale : 1; BufferedImage bufferedImage = cropOutside(task, source, rectangle); if (bufferedImage == null) { return null; } int width = bufferedImage.getWidth() / realXScale; int height = bufferedImage.getHeight() / realYScale; bufferedImage = ScaleTools.scaleImageBySize(bufferedImage, width, height); return bufferedImage; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage sample(FxTask task, BufferedImage source, DoubleRectangle rectangle, int width) { try { if (rectangle == null) { return ScaleTools.scaleImageWidthKeep(source, width); } BufferedImage bufferedImage = cropOutside(task, source, rectangle); if (bufferedImage == null) { return null; } bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width); return bufferedImage; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage sample(FxTask task, BufferedImage source, int x1, int y1, int x2, int y2, int xscale, int yscale) { if (x1 >= x2 || y1 >= y2 || x1 < 0 || x2 < 0 || y1 < 0 || y2 < 0) { return null; } return sample(task, source, DoubleRectangle.xy12(x1, y1, x2, y2), xscale, yscale); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageQuantizationFactory.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageQuantizationFactory.java
package mara.mybox.image.data; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.color.ColorMatch; import mara.mybox.controller.ControlImageQuantization; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm; import static mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm.RegionKMeansClustering; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-2-13 14:44:03 * @License Apache License Version 2.0 */ public class ImageQuantizationFactory { public static ImageQuantization createFX(FxTask task, Image image, ImageScope scope, ControlImageQuantization quantizationController, boolean recordCount) { return create(task, image != null ? SwingFXUtils.fromFXImage(image, null) : null, scope, quantizationController, recordCount); } public static ImageQuantization create(FxTask task, BufferedImage image, ImageScope scope, ControlImageQuantization quantizationController, boolean recordCount) { return create(task, image, scope, quantizationController.getAlgorithm(), quantizationController.getQuanColors(), quantizationController.getRegionSize(), quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization ? quantizationController.getHsbWeight1() : quantizationController.getRgbWeight1(), quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization ? quantizationController.getHsbWeight2() : quantizationController.getRgbWeight2(), quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization ? quantizationController.getHsbWeight3() : quantizationController.getRgbWeight3(), recordCount, quantizationController.getQuanDitherCheck().isSelected(), quantizationController.getFirstColorCheck().isSelected(), quantizationController.colorMatch(), quantizationController.getMaxLoop()); } public static ImageQuantization create(FxTask task, BufferedImage image, ImageScope scope, QuantizationAlgorithm algorithm, int quantizationSize, int regionSize, int weight1, int weight2, int weight3, boolean recordCount, boolean dithering, boolean firstColor, ColorMatch colorMatch, int maxLoop) { try { ImageQuantization quantization; switch (algorithm) { case RGBUniformQuantization: quantization = RGBUniformQuantization.create(); break; case HSBUniformQuantization: quantization = HSBUniformQuantization.create(); break; case RegionPopularityQuantization: quantization = RegionPopularityQuantization.create(); break; case RegionKMeansClustering: quantization = RegionKMeansClusteringQuantization.create(); break; case KMeansClustering: quantization = KMeansClusteringQuantization.create(); break; // case ANN: // return new RGBUniform(image, quantizationSize); default: quantization = RegionKMeansClusteringQuantization.create(); break; } quantization.setAlgorithm(algorithm). setQuantizationSize(quantizationSize) .setRegionSize(regionSize) .setWeight1(weight1).setWeight2(weight2).setWeight3(weight3) .setRecordCount(recordCount) .setFirstColor(firstColor) .setColorMatch(colorMatch) .setMaxLoop(maxLoop) .setOperationType(PixelsOperation.OperationType.Quantization) .setImage(image).setScope(scope).setIsDithering(dithering) .setTask(task); return quantization.buildPalette(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static class RGBUniformQuantization extends ImageQuantization { protected int redMod, redOffset, greenMod, greenOffset, blueMod, blueOffset; protected int redSize, greenSize, blueSize; public static RGBUniformQuantization create() { return new RGBUniformQuantization(); } @Override public RGBUniformQuantization buildPalette() { try { regionSize = quantizationSize; algorithm = QuantizationAlgorithm.RGBUniformQuantization; float redWegiht = weight1 < 1 ? 1 : weight1; float greenWegiht = weight2 < 1 ? 1 : weight2; float blueWegiht = weight3 < 1 ? 1 : weight3; float sum = weight1 + weight2 + weight3; redWegiht = redWegiht / sum; greenWegiht = greenWegiht / sum; blueWegiht = blueWegiht / sum; float x = (float) Math.cbrt(quantizationSize / (redWegiht * greenWegiht * blueWegiht)); float redValue = redWegiht * x; redMod = (int) (256 / redValue); redSize = (int) (256 / redMod) + 1; float greenValue = greenWegiht * x; greenMod = (int) (256 / greenValue); greenSize = (int) (256 / greenMod) + 1; float blueValue = blueWegiht * x; blueMod = (int) (256 / blueValue); blueSize = (int) (256 / blueMod) + 1; // MyBoxLog.console("quantizationSize:" + quantizationSize + " x:" + x); // MyBoxLog.console("redMod:" + redMod + " greenMod:" + greenMod + " blueMod:" + blueMod); // MyBoxLog.console("redSize:" + redSize + " greenSize:" + greenSize + " blueSize:" + blueSize); if (redSize <= 0 || greenSize <= 0 || blueSize <= 0 || redMod <= 0 || greenMod <= 0 || blueMod <= 0) { MyBoxLog.error(message("InvalidParameters")); return this; } if (firstColor) { palette = new Color[redSize][greenSize][blueSize]; } else { redOffset = redMod / 2; greenOffset = greenMod / 2; blueOffset = blueMod / 2; } if (recordCount) { counts = new HashMap<>(); } } catch (Exception e) { MyBoxLog.error(e); } return this; } @Override public String resultInfo() { return message(algorithm.name()) + "\n" + message("ColorsRegionSize") + ": " + redSize * greenSize * blueSize + "\n" + "redMod: " + redMod + " greenMod: " + greenMod + " blueMod: " + blueMod + "\n" + "redSize: " + redSize + " greenSize: " + greenSize + " blueSize: " + blueSize; } @Override public Color operateColor(Color color) { try { if (color.getRGB() == 0) { return color; } int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); Color mappedColor; if (firstColor) { int indexRed = red / redMod; int indexGreen = green / greenMod; int indexBlue = blue / blueMod; if (palette[indexRed][indexGreen][indexBlue] == null) { palette[indexRed][indexGreen][indexBlue] = color; mappedColor = color; } else { mappedColor = palette[indexRed][indexGreen][indexBlue]; } } else { red = red - (red % redMod) + redOffset; red = Math.min(Math.max(red, 0), 255); green = green - (green % greenMod) + greenOffset; green = Math.min(Math.max(green, 0), 255); blue = blue - (blue % blueMod) + blueOffset; blue = Math.min(Math.max(blue, 0), 255); mappedColor = new Color(red, green, blue); } countColor(mappedColor); return mappedColor; } catch (Exception e) { // MyBoxLog.error(e); return color; } } } public static class HSBUniformQuantization extends ImageQuantization { protected int hueMod, saturationMod, brightnessMod, hueOffset, saturationOffset, brightnessOffset; protected int hueSize, saturationSize, brightnessSize; public static HSBUniformQuantization create() throws Exception { return new HSBUniformQuantization(); } @Override public HSBUniformQuantization buildPalette() { try { regionSize = quantizationSize; algorithm = QuantizationAlgorithm.HSBUniformQuantization; float hueWegiht = weight1 < 1 ? 1 : weight1; float saturationWegiht = weight2 < 1 ? 1 : weight2; float brightnessWegiht = weight3 < 1 ? 1 : weight3; float sum = hueWegiht + saturationWegiht + brightnessWegiht; hueWegiht = hueWegiht / sum; saturationWegiht = saturationWegiht / sum; brightnessWegiht = brightnessWegiht / sum; float x = (float) Math.cbrt(quantizationSize / (hueWegiht * saturationWegiht * brightnessWegiht)); float hueValue = hueWegiht * x; hueMod = (int) (360 / hueValue); hueSize = (int) (360 / hueMod) + 1; float saturationValue = saturationWegiht * x; saturationMod = (int) (100 / saturationValue); saturationSize = (int) (100 / saturationMod) + 1; float brightnessValue = brightnessWegiht * x; brightnessMod = (int) (100 / brightnessValue); brightnessSize = (int) (100 / brightnessMod) + 1; // MyBoxLog.console("regionSize:" + regionSize + " x:" + x); // MyBoxLog.console("hueMod:" + hueMod + " saturationMod:" + saturationMod + " brightnessMod:" + brightnessMod); // MyBoxLog.console("hueSize:" + hueSize + " saturationSize:" + saturationSize + " brightnessSize:" + brightnessSize); if (hueSize <= 0 || saturationSize <= 0 || saturationSize <= 0 || hueMod <= 0 || saturationMod <= 0 || brightnessMod <= 0) { MyBoxLog.error(message("InvalidParameters")); return this; } if (firstColor) { palette = new Color[hueSize][saturationSize][brightnessSize]; } else { hueOffset = hueMod / 2; saturationOffset = saturationMod / 2; brightnessOffset = brightnessMod / 2; } if (recordCount) { counts = new HashMap<>(); } } catch (Exception e) { MyBoxLog.error(e); } return this; } @Override public String resultInfo() { return message(algorithm.name()) + "\n" + message("ColorsRegionSize") + ": " + hueSize * saturationSize * brightnessSize + "\n" + "hueMod: " + hueMod + " saturationMod: " + saturationMod + " brightnessMod: " + brightnessMod + "\n" + "hueSize: " + hueSize + " saturationSize: " + saturationSize + " brightnessSize: " + brightnessSize; } @Override public Color operateColor(Color color) { try { if (color.getRGB() == 0) { return color; } Color mappedColor; float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); float h, s, b; int hue = (int) (hsb[0] * 360); int saturation = (int) (hsb[1] * 100); int brightness = (int) (hsb[2] * 100); if (firstColor) { int indexHue = hue / hueMod; int indexSaturation = saturation / saturationMod; int indexBrightness = brightness / brightnessMod; if (palette[indexHue][indexSaturation][indexBrightness] == null) { palette[indexHue][indexSaturation][indexBrightness] = color; mappedColor = color; } else { mappedColor = palette[indexHue][indexSaturation][indexBrightness]; } } else { hue = hue - (hue % hueMod) + hueOffset; h = Math.min(Math.max(hue / 360.0f, 0.0f), 1.0f); saturation = saturation - (saturation % saturationMod) + saturationOffset; s = Math.min(Math.max(saturation / 100.0f, 0.0f), 1.0f); brightness = brightness - (brightness % brightnessMod) + brightnessOffset; b = Math.min(Math.max(brightness / 100.0f, 0.0f), 1.0f); mappedColor = Color.getHSBColor(h, s, b); } countColor(mappedColor); return mappedColor; } catch (Exception e) { // MyBoxLog.error(e); return color; } } } public static class RegionQuantization extends ImageQuantization { protected RGBUniformQuantization rgbPalette; protected boolean large; @Override public RegionQuantization buildPalette() { try { large = image.getWidth() * image.getHeight() > regionSize; if (large) { rgbPalette = RGBUniformQuantization.create(); rgbPalette.setQuantizationSize(regionSize) .setFirstColor(firstColor) .setRecordCount(recordCount) .setWeight1(weight1).setWeight2(weight2).setWeight3(weight3) .setIsDithering(isDithering) .setTask(task); rgbPalette.buildPalette(); } } catch (Exception e) { MyBoxLog.debug(e); } return this; } @Override public String resultInfo() { return rgbPalette.resultInfo(); } @Override public Color operateColor(Color color) { if (color.getRGB() == 0) { return color; } Color regionColor = map(color); handleRegionColor(color, regionColor); return regionColor; } public Color map(Color color) { if (color.getRGB() == 0) { return color; } Color regionColor; if (rgbPalette != null) { regionColor = rgbPalette.operateColor(color); } else { regionColor = new Color(color.getRGB(), false); } return regionColor; } public void handleRegionColor(Color color, Color regionColor) { } } public static class PopularityRegion extends RegionQuantization { protected Map<Color, PopularityRegionValue> regionsMap; public static PopularityRegion create() { return new PopularityRegion(); } @Override public RegionQuantization buildPalette() { super.buildPalette(); regionsMap = new HashMap<>(); return this; } @Override public void handleRegionColor(Color color, Color regionColor) { PopularityRegionValue value = regionsMap.get(regionColor); if (value == null) { value = new PopularityRegionValue(); value.regionColor = regionColor; value.redAccum = color.getRed(); value.greenAccum = color.getGreen(); value.blueAccum = color.getBlue(); value.pixelsCount = 1; regionsMap.put(regionColor, value); } else { value.redAccum += color.getRed(); value.greenAccum += color.getGreen(); value.blueAccum += color.getBlue(); value.pixelsCount += 1; } } public List<PopularityRegionValue> getRegionValues(int quantizationSize) { List<PopularityRegionValue> values = new ArrayList<>(); values.addAll(regionsMap.values()); for (PopularityRegionValue region : values) { region.averageColor = new Color( Math.min(255, (int) (region.redAccum / region.pixelsCount)), Math.min(255, (int) (region.greenAccum / region.pixelsCount)), Math.min(255, (int) (region.blueAccum / region.pixelsCount))); } Collections.sort(values, new Comparator<PopularityRegionValue>() { @Override public int compare(PopularityRegionValue r1, PopularityRegionValue r2) { long diff = r2.pixelsCount - r1.pixelsCount; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); if (quantizationSize < values.size()) { values = values.subList(0, quantizationSize); } regionsMap.clear(); return values; } } public static class RegionPopularityQuantization extends ImageQuantization { protected PopularityRegion regionQuantization; protected List<PopularityRegionValue> regionValues; public static RegionPopularityQuantization create() { return new RegionPopularityQuantization(); } @Override public RegionPopularityQuantization buildPalette() { try { algorithm = QuantizationAlgorithm.RegionPopularityQuantization; colorMatch = new ColorMatch(); regionQuantization = PopularityRegion.create(); regionQuantization.setQuantizationSize(regionSize) .setRegionSize(regionSize) .setFirstColor(firstColor) .setWeight1(weight1).setWeight2(weight2).setWeight3(weight3) .setRecordCount(false) .setImage(image).setScope(scope) .setOperationType(PixelsOperation.OperationType.Quantization) .setIsDithering(isDithering) .setTask(task); regionQuantization.buildPalette().start(); regionValues = regionQuantization.getRegionValues(quantizationSize); if (recordCount) { counts = new HashMap<>(); } } catch (Exception e) { MyBoxLog.debug(e); } return this; } @Override public String resultInfo() { if (regionValues == null) { return null; } return message(algorithm.name()) + "\n" + message("ColorsNumber") + ": " + regionValues.size() + "\n-----\n" + regionQuantization.resultInfo(); } @Override public Color operateColor(Color color) { if (color.getRGB() == 0) { return color; } Color mappedColor = null; Color regionColor = regionQuantization.map(color); for (int i = 0; i < regionValues.size(); ++i) { PopularityRegionValue region = regionValues.get(i); if (region.regionColor.equals(regionColor)) { mappedColor = region.averageColor; break; } } if (mappedColor == null) { double minDistance = Integer.MAX_VALUE; PopularityRegionValue nearestRegion = regionValues.get(0); for (int i = 0; i < regionValues.size(); ++i) { PopularityRegionValue region = regionValues.get(i); double distance = colorMatch.distance(region.averageColor, color); if (distance < minDistance) { minDistance = distance; nearestRegion = region; } } mappedColor = nearestRegion.averageColor; } countColor(mappedColor); return mappedColor; } } public static class KMeansRegion extends RegionQuantization { protected List<Color> regionColors; public static KMeansRegion create() { return new KMeansRegion(); } @Override public RegionQuantization buildPalette() { super.buildPalette(); regionColors = new ArrayList<>(); return this; } @Override public void handleRegionColor(Color color, Color regionColor) { if (!regionColors.contains(regionColor)) { regionColors.add(regionColor); } } } public static class RegionKMeansClusteringQuantization extends ImageQuantization { protected ImageRegionKMeans kmeans; public static RegionKMeansClusteringQuantization create() throws Exception { return new RegionKMeansClusteringQuantization(); } @Override public RegionKMeansClusteringQuantization buildPalette() { algorithm = QuantizationAlgorithm.RegionKMeansClustering; kmeans = imageRegionKMeans(); if (recordCount) { counts = new HashMap<>(); } return this; } @Override public String resultInfo() { if (kmeans == null) { return null; } return message(algorithm.name()) + "\n" + message("ColorsNumber") + ": " + kmeans.centerSize() + "\n" + message("ActualLoop") + ": " + kmeans.getLoopCount() + "\n-----\n" + kmeans.regionQuantization.resultInfo(); } @Override public Color operateColor(Color color) { if (color.getRGB() == 0) { return color; } Color mappedColor = kmeans.map(color); countColor(mappedColor); return mappedColor; } /* get/set */ public ImageRegionKMeans getKmeans() { return kmeans; } public void setKmeans(ImageRegionKMeans kmeans) { this.kmeans = kmeans; } } public static class KMeansClusteringQuantization extends ImageQuantization { protected ImageKMeans kmeans; public static KMeansClusteringQuantization create() throws Exception { return new KMeansClusteringQuantization(); } @Override public KMeansClusteringQuantization buildPalette() { algorithm = QuantizationAlgorithm.KMeansClustering; kmeans = imageKMeans(); if (recordCount) { counts = new HashMap<>(); } return this; } @Override public String resultInfo() { if (kmeans == null) { return null; } return message(algorithm.name()) + "\n" + message("ColorsNumber") + ": " + kmeans.centerSize() + "\n" + message("ActualLoop") + ": " + kmeans.getLoopCount(); } @Override public Color operateColor(Color color) { if (color.getRGB() == 0) { return color; } Color mappedColor = kmeans.map(color); countColor(mappedColor); return mappedColor; } /* get/set */ public ImageKMeans getKmeans() { return kmeans; } public void setKmeans(ImageKMeans kmeans) { this.kmeans = kmeans; } } // https://www.researchgate.net/publication/220502178_On_spatial_quantization_of_color_images public static class Spatialquantization { } // https://www.codeproject.com/Tips/1046574/OctTree-Based-Nearest-Color-Search public class ColorFinder { // Declare a root node to contain all of the source colors. private Node rootNode; public ColorFinder(Color[] colors) { // Create the root node. rootNode = new Node(0, colors); // Add all source colors to it. for (int i = 0; i < colors.length; ++i) { rootNode.AddColor(i); } } public int GetNearestColorIndex(Color color) { return rootNode.GetNearestColorIndex(color)[0]; } private class Node { private int level; private Color[] colors; private final Node[] children = new Node[8]; private int colorIndex = -1; // Cached distance calculations. private final int[][] Distance = new int[256][256]; // Cached bit masks. private final int[] Mask = {128, 64, 32, 16, 8, 4, 2, 1}; public Node() { // precalculate every possible distance for (int i = 0; i < 256; ++i) { for (int j = 0; j < 256; ++j) { Distance[i][j] = ((i - j) * (i - j)); } } } public Node(int level, Color[] colors) { this.level = level; this.colors = colors; } public void AddColor(int colorIndex) { if (level == 7) { // LEAF MODE. // The deepest level contains the averageColor mappedValue and no children. this.colorIndex = colorIndex; } else { // BRANCH MODE. // Get the oct mappedValue for the specified source averageColor at this level. int index = colorIndex(colors[colorIndex], level); // If the necessary child node doesn't exist, root it. if (children[index] == null) { children[index] = new Node((level + 1), colors); } // Pass the averageColor along to the proper child node. children[index].AddColor(colorIndex); } } public int colorIndex(Color color, int level) { // Take 1 bit from each averageColor channel // to return a 3-bit value ranging from 0 to 7. // Level 0 uses the highest bit, level 1 uses the second-highest bit, etc. int shift = (7 - level); return (((color.getRed() & Mask[level]) >> shift) | ((color.getGreen() & Mask[level]) << 1 >> shift) | ((color.getBlue() & Mask[level]) << 2 >> shift)); } public int distance(int b1, int b2) { return Distance[b1][b2]; } public int distance(Color c1, Color c2) { return distance(c1.getRed(), c2.getRed()) + distance(c1.getGreen(), c2.getGreen()) + distance(c1.getBlue(), c2.getBlue()); } public int[] GetNearestColorIndex(Color color) { int[] ret = new int[2]; ret[0] = -1; ret[1] = Integer.MAX_VALUE; if (level == 7) { // LEAF MODE. ret[0] = colorIndex; ret[1] = distance(color, colors[colorIndex]); } else { // BRANCH MODE. int index = colorIndex(color, level); if (children[index] == null) { int minDistance = Integer.MAX_VALUE; int minIndex = -1; for (Node child : children) { if (child != null) { int[] v = child.GetNearestColorIndex(color); if (v[1] < minDistance) { minIndex = v[0]; minDistance = v[1]; } } } ret[0] = minIndex; ret[1] = minDistance; } else { // DIRECT CHILD EXISTS. ret = children[index].GetNearestColorIndex(color); } } return ret; } } } public static class Octree { private OctreeNode rootNode; public Octree(BufferedImage image, int colorsNumber) { rootNode = new OctreeNode(); rootNode.afterSetParam(); for (int i = 0; i < image.getWidth(); ++i) { for (int j = 0; j < image.getHeight(); ++j) { int colorValue = image.getRGB(i, j); if (colorValue == 0) { // transparency is not involved continue; } rootNode.addColor(colorValue, colorsNumber); } } } public static class OctreeNode { protected int level = 0; protected OctreeNode parent; protected OctreeNode[] children = new OctreeNode[8]; protected boolean isLeaf = false; protected int redAccum = 0; protected int greenAccum = 0; protected int blueAccum = 0; protected int piexlsCount = 0; protected Map<Integer, List<OctreeNode>> levelMapping; public void addColor(int colorValue, int number) { if (level != 0 || this.parent != null) { throw new UnsupportedOperationException(); } int speed = 7 + 1 - number; int r = colorValue >> 16 & 0xFF; int g = colorValue >> 8 & 0xFF; int b = colorValue & 0xFF; OctreeNode proNode = this; for (int i = 7; i >= speed; --i) { int item = ((r >> i & 1) << 2) + ((g >> i & 1) << 1) + (b >> i & 1); OctreeNode child = proNode.getChild(item); if (child == null) { child = new OctreeNode(); child.setLevel(8 - i); child.setParent(proNode); child.afterSetParam(); this.levelMapping.get(child.getLevel()).add(child); proNode.setChild(item, child); } if (i == speed) { child.setIsLeaf(true); } if (child.isIsLeaf()) { child.setPixel(r, g, b); break; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/image/data/ImageColorSpace.java
released/MyBox/src/main/java/mara/mybox/image/data/ImageColorSpace.java
package mara.mybox.image.data; import com.github.jaiimageio.impl.plugins.pcx.PCXImageReaderSpi; import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriterSpi; import com.github.jaiimageio.impl.plugins.pnm.PNMImageReaderSpi; import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriterSpi; import com.github.jaiimageio.impl.plugins.raw.RawImageReaderSpi; import com.github.jaiimageio.impl.plugins.raw.RawImageWriterSpi; import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReaderSpi; import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriterSpi; import com.luciad.imageio.webp.WebPImageReaderSpi; import com.luciad.imageio.webp.WebPImageWriterSpi; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.spi.IIORegistry; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.image.file.ImageFileWriters; import static mara.mybox.image.file.ImageJpgFile.getJpegCompressionTypes; import mara.mybox.value.Languages; import org.apache.pdfbox.rendering.ImageType; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ImageColorSpace { public static List<String> RGBColorSpaces = new ArrayList<>() { { addAll(Arrays.asList( "sRGB", "Linear sRGB", "Apple RGB", "Adobe RGB", "Color Match RGB", "ECI RGB" )); } }; public static List<String> CMYKColorSpaces = new ArrayList<>() { { addAll(Arrays.asList( "ECI CMYK", "Adobe CMYK - CoatedFOGRA27", "Adobe CMYK - CoatedFOGRA39", "Adobe CMYK - JapanColor2001Coated", "Adobe CMYK_JapanColor2001Uncoated", "Adobe CMYK - JapanColor2002Newspaper", "Adobe CMYK - JapanWebCoated", "Adobe CMYK - USSheetfedCoated", "Adobe CMYK - USSheetfedUncoated", "Adobe CMYK - USWebCoatedSWOP", "Adobe CMYK - USWebUncoated", "Adobe CMYK - UncoatedFOGRA29", "Adobe CMYK - WebCoatedFOGRA28" )); } }; public static List<String> OtherColorSpaces = new ArrayList<>() { { addAll(Arrays.asList( "Gray", "BlackOrWhite" )); } }; public static void registrySupportedImageFormats() { IIORegistry registry = IIORegistry.getDefaultInstance(); // tiff of ECI CMYK can not be opened by reader in jdk registry.registerServiceProvider(new TIFFImageWriterSpi()); registry.registerServiceProvider(new TIFFImageReaderSpi()); // registry.registerServiceProvider(new BMPImageWriterSpi()); // registry.registerServiceProvider(new BMPImageReaderSpi()); // registry.registerServiceProvider(new GIFImageWriterSpi()); // registry.registerServiceProvider(new WBMPImageWriterSpi()); // registry.registerServiceProvider(new WBMPImageReaderSpi()); registry.registerServiceProvider(new RawImageWriterSpi()); registry.registerServiceProvider(new RawImageReaderSpi()); registry.registerServiceProvider(new PCXImageWriterSpi()); registry.registerServiceProvider(new PCXImageReaderSpi()); registry.registerServiceProvider(new PNMImageWriterSpi()); registry.registerServiceProvider(new PNMImageReaderSpi()); // registry.registerServiceProvider(new J2KImageWriterSpi()); // registry.registerServiceProvider(new J2KImageReaderSpi()); // String readFormats[] = ImageIO.getReaderFormatNames(); // String writeFormats[] = ImageIO.getWriterFormatNames(); // MyBoxLog.console("Readers:" + Arrays.asList(readFormats)); // MyBoxLog.console("Writers:" + Arrays.asList(writeFormats)); //Readers:[JPG, JPEG 2000, tiff, bmp, PCX, gif, WBMP, PNG, RAW, JPEG, PNM, tif, TIFF, wbmp, jpeg, jpg, JPEG2000, BMP, pcx, GIF, png, raw, pnm, TIF, jpeg2000, jpeg 2000] //Writers:[JPEG 2000, JPG, tiff, bmp, PCX, gif, WBMP, PNG, RAW, JPEG, PNM, tif, TIFF, wbmp, jpeg, jpg, JPEG2000, BMP, pcx, GIF, png, raw, pnm, TIF, jpeg2000, jpeg 2000] registry.registerServiceProvider(new WebPImageWriterSpi()); registry.registerServiceProvider(new WebPImageReaderSpi()); } public static String[] getCompressionTypes(String imageFormat, String colorSpace, boolean hasAlpha) { if (imageFormat == null || colorSpace == null) { return null; } String[] compressionTypes; switch (imageFormat) { case "jpg": case "jpeg": compressionTypes = getJpegCompressionTypes(); break; case "gif": compressionTypes = new String[]{"LZW"}; break; case "tif": case "tiff": // Summarized based on API of class "com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam" and debugging if (Languages.message("BlackOrWhite").equals(colorSpace)) { compressionTypes = new String[]{"CCITT T.6", "CCITT RLE", "CCITT T.4", "ZLib", "Deflate", "LZW", "PackBits"}; } else { if (hasAlpha || ImageColorSpace.CMYKColorSpaces.contains(colorSpace)) { compressionTypes = new String[]{"LZW", "ZLib", "Deflate", "PackBits"}; } else { compressionTypes = new String[]{"LZW", "ZLib", "Deflate", "JPEG", "PackBits"}; } } // compressionTypes = ImageTools.getTiffCompressionTypes(); break; case "bmp": // Summarized based on API of class "com.github.jaiimageio.plugins.bmp.BMPImageWriteParam" and debugging if (Languages.message("Gray").equals(colorSpace)) { compressionTypes = new String[]{"BI_RGB", "BI_RLE8", "BI_BITFIELDS"}; } else if (Languages.message("BlackOrWhite").equals(colorSpace)) { compressionTypes = new String[]{"BI_RGB", "BI_BITFIELDS"}; } else { compressionTypes = new String[]{"BI_RGB", "BI_BITFIELDS"}; } break; default: compressionTypes = getCompressionTypes(imageFormat); } return compressionTypes; } public static String[] getCompressionTypes(String imageFormat, ImageType imageColor) { if (imageFormat == null || imageColor == null) { return null; } String[] compressionTypes = null; switch (imageFormat) { case "jpg": case "jpeg": compressionTypes = getJpegCompressionTypes(); break; case "gif": String[] giftypes = {"LZW"}; return giftypes; case "tif": case "tiff": // Summarized based on API of class "com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam" and debugging switch (imageColor) { case BINARY: { String[] types = {"CCITT T.6", "CCITT RLE", "CCITT T.4", "ZLib", "Deflate", "LZW", "PackBits"}; return types; } case GRAY: { String[] types = {"LZW", "ZLib", "Deflate", "JPEG", "PackBits"}; return types; } case RGB: { String[] types = {"LZW", "ZLib", "Deflate", "JPEG", "PackBits"}; return types; } case ARGB: { String[] types = {"LZW", "ZLib", "Deflate", "PackBits"}; return types; } default: break; } // compressionTypes = ImageTools.getTiffCompressionTypes(); break; case "bmp": // Summarized based on API of class "com.github.jaiimageio.plugins.bmp.BMPImageWriteParam" and debugging switch (imageColor) { case BINARY: { String[] types = {"BI_RGB", "BI_BITFIELDS"}; return types; } case GRAY: { String[] types = {"BI_RGB", "BI_RLE8", "BI_BITFIELDS"}; return types; } case RGB: { String[] types = {"BI_RGB", "BI_BITFIELDS"}; return types; } case ARGB: { return null; } default: // compressionTypes = getCompressionTypes(imageFormat); } break; default: compressionTypes = getCompressionTypes(imageFormat); } return compressionTypes; } public static String[] getCompressionTypes(String imageFormat) { try { ImageWriter writer = ImageFileWriters.getWriter(imageFormat); ImageWriteParam param = writer.getDefaultWriteParam(); return param.getCompressionTypes(); } catch (Exception e) { return null; } } public static boolean canImageCompressed(String imageFormat) { return getCompressionTypes(imageFormat) != null; } public static String imageType(int type) { switch (type) { case BufferedImage.TYPE_3BYTE_BGR: return "3BYTE_BGR"; case BufferedImage.TYPE_4BYTE_ABGR: return "4BYTE_ABGR"; case BufferedImage.TYPE_4BYTE_ABGR_PRE: return "4BYTE_ABGR_PRE"; case BufferedImage.TYPE_BYTE_BINARY: return "BYTE_BINARY"; case BufferedImage.TYPE_BYTE_GRAY: return "BYTE_GRAY"; case BufferedImage.TYPE_BYTE_INDEXED: return "BYTE_INDEXED"; case BufferedImage.TYPE_CUSTOM: return "CUSTOM"; case BufferedImage.TYPE_INT_ARGB: return "INT_ARGB"; case BufferedImage.TYPE_INT_ARGB_PRE: return "INT_ARGB_PRE"; case BufferedImage.TYPE_INT_BGR: return "INT_BGR"; case BufferedImage.TYPE_INT_RGB: return "INT_RGB"; case BufferedImage.TYPE_USHORT_555_RGB: return "USHORT_555_RGB"; case BufferedImage.TYPE_USHORT_565_RGB: return "USHORT_565_RGB"; } return type + ""; } public static ColorSpace srgbColorSpace() { return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_sRGB); } public static ColorSpace grayColorSpace() { return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_GRAY); } public static ColorSpace linearSRGBColorSpace() { return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_LINEAR_RGB); } public static ColorSpace ciexyzColorSpace() { return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_CIEXYZ); } public static ColorSpace pyccColorSpace() { return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_PYCC); } public static ColorSpace appleRGBColorSpace() { return new ICC_ColorSpace(appleRGBProfile()); } public static ColorSpace adobeRGBColorSpace() { return new ICC_ColorSpace(adobeRGBProfile()); } public static ColorSpace colorMatchRGBColorSpace() { return new ICC_ColorSpace(colorMatchRGBProfile()); } public static ColorSpace eciRGBColorSpace() { return new ICC_ColorSpace(eciRGBProfile()); } public static ICC_ColorSpace eciCmykColorSpace() { try { return new ICC_ColorSpace(eciCmykProfile()); } catch (Exception ex) { return null; } } // public static ICC_ColorSpace internalColorSpace(String profileName) { try { return new ICC_ColorSpace(internalProfile(profileName)); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ICC_ColorSpace colorSpace(String profileName) { try { return new ICC_ColorSpace(iccProfile(profileName)); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ICC_ColorSpace adobeCmykColorSpace() { try { return new ICC_ColorSpace(adobeCmykProfile()); } catch (Exception ex) { return null; } } // https://stackoverflow.com/questions/8118712/java-cmyk-to-rgb-with-profile-output-is-too-dark/12132556#12132556 public static ICC_Profile internalProfileByName(String name) { try { switch (name) { case "sRGB": return sRGBProfile(); case "Linear sRGB": return linearRGBProfile(); case "Apple RGB": return appleRGBProfile(); case "Adobe RGB": return adobeRGBProfile(); case "Color Match RGB": return colorMatchRGBProfile(); case "ECI RGB": return eciRGBProfile(); case "ECI CMYK": return eciCmykProfile(); case "Adobe CMYK - CoatedFOGRA27": return internalProfile("AdobeCMYK_CoatedFOGRA27.icc"); case "Adobe CMYK - CoatedFOGRA39": return internalProfile("AdobeCMYK_CoatedFOGRA39.icc"); case "Adobe CMYK - JapanColor2001Coated": return internalProfile("AdobeCMYK_JapanColor2001Coated.icc"); case "Adobe CMYK - JapanColor2001Uncoated": return internalProfile("AdobeCMYK_JapanColor2001Uncoated.icc"); case "Adobe CMYK - JapanColor2002Newspaper": return internalProfile("AdobeCMYK_JapanColor2002Newspaper.icc"); case "Adobe CMYK - JapanWebCoated": return internalProfile("AdobeCMYK_JapanWebCoated.icc"); case "Adobe CMYK - USSheetfedCoated": return internalProfile("AdobeCMYK_USSheetfedCoated.icc"); case "Adobe CMYK - USSheetfedUncoated": return internalProfile("AdobeCMYK_USSheetfedUncoated.icc"); case "Adobe CMYK - USWebCoatedSWOP": return internalProfile("AdobeCMYK_USWebCoatedSWOP.icc"); case "Adobe CMYK - USWebUncoated": return internalProfile("AdobeCMYK_USWebUncoated.icc"); case "Adobe CMYK - UncoatedFOGRA29": return internalProfile("AdobeCMYK_UncoatedFOGRA29.icc"); case "Adobe CMYK - WebCoatedFOGRA28": return internalProfile("AdobeCMYK_WebCoatedFOGRA28.icc"); case "Gray": return grayProfile(); default: if (Languages.message("Gray").equals(name)) { return grayProfile(); } return null; } } catch (Exception e) { return null; } } public static ICC_Profile iccProfile(String file) { try { ICC_Profile profile = ICC_Profile.getInstance(file); return iccProfile(profile); } catch (Exception ex) { return null; } } public static ICC_Profile internalProfile(String filename) { try { File file = FxFileTools.getInternalFile("/data/ICC/" + filename, "ICC", filename); ICC_Profile profile = ICC_Profile.getInstance(file.getAbsolutePath()); return iccProfile(profile); } catch (Exception ex) { return null; } } public static ICC_Profile iccProfile(ICC_Profile profile) { try { if (profile.getProfileClass() != ICC_Profile.CLASS_DISPLAY) { byte[] profileData = profile.getData(); // Need to clone entire profile, due to a JDK 7 bug if (profileData[ICC_Profile.icHdrRenderingIntent] == ICC_Profile.icPerceptual) { intToBigEndian(ICC_Profile.icSigDisplayClass, profileData, ICC_Profile.icHdrDeviceClass); // Header is first profile = ICC_Profile.getInstance(profileData); } } return profile; } catch (Exception ex) { return null; } } static void intToBigEndian(int value, byte[] array, int index) { array[index] = (byte) (value >> 24); array[index + 1] = (byte) (value >> 16); array[index + 2] = (byte) (value >> 8); array[index + 3] = (byte) (value); } public static ICC_Profile sRGBProfile() { return ICC_Profile.getInstance(ICC_ColorSpace.CS_sRGB); } public static ICC_Profile grayProfile() { return ICC_Profile.getInstance(ICC_ColorSpace.CS_GRAY); } public static ICC_Profile linearRGBProfile() { return ICC_Profile.getInstance(ICC_ColorSpace.CS_LINEAR_RGB); } public static ICC_Profile xyzProfile() { return ICC_Profile.getInstance(ICC_ColorSpace.CS_CIEXYZ); } public static ICC_Profile pyccProfile() { return ICC_Profile.getInstance(ICC_ColorSpace.CS_PYCC); } public static ICC_Profile eciRGBProfile() { return internalProfile("ECI_RGB_v2_ICCv4.icc"); } public static ICC_Profile appleRGBProfile() { return internalProfile("Adobe_AppleRGB.icc"); } public static ICC_Profile adobeRGBProfile() { return internalProfile("AdobeRGB_1998.icc"); } public static ICC_Profile colorMatchRGBProfile() { return internalProfile("Adobe_ColorMatchRGB.icc"); } public static ICC_Profile eciCmykProfile() { return internalProfile("ECI_CMYK.icc"); } public static ICC_Profile adobeCmykProfile() { return internalProfile("AdobeCMYK_UncoatedFOGRA29.icc"); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false