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/alpha/MyBox/src/main/java/mara/mybox/data/SVG.java | alpha/MyBox/src/main/java/mara/mybox/data/SVG.java | package mara.mybox.data;
import java.awt.Rectangle;
import java.io.File;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.SvgTools;
import mara.mybox.tools.XmlTools;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* @Author Mara
* @CreateDate 2023-6-27
* @License Apache License Version 2.0
*/
public class SVG {
protected Document doc;
protected Element svgNode;
protected float width, height, renderedWidth, renderedheight;
protected Rectangle viewBox;
protected File imageFile;
public SVG() {
doc = null;
svgNode = null;
width = -1;
height = -1;
viewBox = null;
imageFile = null;
}
public SVG(Document doc) {
try {
this.doc = doc;
width = -1;
height = -1;
viewBox = null;
if (doc == null) {
return;
}
svgNode = XmlTools.findName(doc, "svg", 0);
NamedNodeMap attrs = svgNode.getAttributes();
if (attrs == null || attrs.getLength() == 0) {
return;
}
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String name = attr.getNodeName();
String value = attr.getNodeValue();
if (name == null || value == null) {
continue;
}
try {
switch (name.toLowerCase()) {
case "width":
width = Float.parseFloat(value);
break;
case "height":
height = Float.parseFloat(value);
break;
case "viewbox":
viewBox = SvgTools.viewBox(value);
break;
}
} catch (Exception e) {
}
}
if (viewBox != null) {
if (width <= 0) {
width = (float) viewBox.getWidth();
}
if (height <= 0) {
height = (float) viewBox.getHeight();
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
/*
get
*/
public Document getDoc() {
return doc;
}
public Element getSvgNode() {
return svgNode;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public Rectangle getViewBox() {
return viewBox;
}
/*
set
*/
public SVG setDoc(Document doc) {
this.doc = doc;
return this;
}
public SVG setSvgNode(Element svgNode) {
this.svgNode = svgNode;
return this;
}
public SVG setWidth(float width) {
this.width = width;
return this;
}
public SVG setHeight(float height) {
this.height = height;
return this;
}
public SVG setRenderedWidth(float renderedWidth) {
this.renderedWidth = renderedWidth;
return this;
}
public SVG setRenderedheight(float renderedheight) {
this.renderedheight = renderedheight;
return this;
}
public SVG setViewBox(Rectangle viewBox) {
this.viewBox = viewBox;
return this;
}
public SVG setImageFile(File imageFile) {
this.imageFile = imageFile;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/IntValue.java | alpha/MyBox/src/main/java/mara/mybox/data/IntValue.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2019-2-10 12:47:33
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IntValue {
private String type, name;
private int value;
private float percentage;
public IntValue() {
}
public IntValue(int value) {
this.type = null;
this.name = null;
this.value = value;
}
public IntValue(String name, int value) {
this.type = null;
this.name = name;
this.value = value;
}
public IntValue(String type, String name, int value) {
this.type = type;
this.name = name;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public float getPercentage() {
return percentage;
}
public void setPercentage(float percentage) {
this.percentage = percentage;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/Link.java | alpha/MyBox/src/main/java/mara/mybox/data/Link.java | package mara.mybox.data;
import java.io.File;
import java.net.URL;
import java.util.Date;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.UrlTools;
/**
* @Author Mara
* @CreateDate 2020-10-13
* @License Apache License Version 2.0
*/
public class Link {
private URL url;
private String address, addressOriginal, addressPath, addressFile,
title, name, file, fileParent, filename, html;
private int index;
private Date dlTime;
public enum FilenameType {
ByLinkName, ByLinkTitle, ByLinkAddress, None
}
public Link() {
}
public Link(URL url) {
this.url = url;
address = url.toString();
}
public Link(URL url, String address, String name, String title, int index) {
this.url = url;
this.address = address;
this.name = name;
this.title = title;
this.index = index;
}
public String pageName(FilenameType nameType) {
String pageName = null;
if (nameType == null || nameType == FilenameType.ByLinkName) {
pageName = name != null && !name.isBlank() ? name : title;
} else if (nameType == FilenameType.ByLinkTitle) {
pageName = title != null && !title.isBlank() ? title : name;
}
if (pageName == null || pageName.isBlank()) {
pageName = UrlTools.filePrefix(getUrl());
}
return FileNameTools.filter(pageName);
}
public String filename(File path, FilenameType nameType) {
if (url == null || path == null) {
return null;
}
try {
String pageName = pageName(nameType);
pageName = (pageName == null || pageName.isBlank()) ? "index" : pageName;
if (url.getPath().isBlank()) {
return path + File.separator + pageName + ".html";
}
String suffix = null;
if (!getAddress().endsWith("/")) {
suffix = UrlTools.fileSuffix(url);
}
suffix = (suffix == null || suffix.isBlank()) ? ".html" : suffix;
return path + File.separator + pageName + suffix;
} catch (Exception e) {
MyBoxLog.console(e.toString());
return null;
}
}
public static Link create() {
return new Link();
}
/*
customized get/set
*/
public String getAddress() {
if (address == null && url != null) {
address = url.toString();
}
return address;
}
public URL getUrl() {
if (url == null && address != null) {
url = UrlTools.url(address);
}
return url;
}
public String getAddressPath() {
url = getUrl();
if (url != null) {
addressPath = UrlTools.fullPath(url);
}
return addressPath;
}
public String getAddressFile() {
if (addressFile == null && getUrl() != null) {
addressFile = UrlTools.file(url);
}
return addressFile;
}
public String getFile() {
return file;
}
public String getFilename() {
if (filename == null && file != null) {
filename = new File(file).getName();
}
return filename;
}
public String getFileParent() {
if (fileParent == null && file != null) {
fileParent = new File(file).getParent();
}
return fileParent;
}
/*
get/set
*/
public Link setUrl(URL url) {
this.url = url;
return this;
}
public Link setAddress(String address) {
this.address = address;
return this;
}
public String getName() {
return name;
}
public Link setName(String name) {
this.name = name;
return this;
}
public Link setFile(String file) {
this.file = file;
return this;
}
public Link setFileName(String fileName) {
this.filename = fileName;
return this;
}
public Link setAddressFile(String addressFile) {
this.addressFile = addressFile;
return this;
}
public String getTitle() {
return title;
}
public Link setTitle(String title) {
this.title = title;
return this;
}
public int getIndex() {
return index;
}
public Link setIndex(int index) {
this.index = index;
return this;
}
public Link setAddressPath(String addressPath) {
this.addressPath = addressPath;
return this;
}
public String getAddressOriginal() {
return addressOriginal;
}
public Link setAddressOriginal(String addressOriginal) {
this.addressOriginal = addressOriginal;
return this;
}
public Date getDlTime() {
return dlTime;
}
public Link setDlTime(Date dlTime) {
this.dlTime = dlTime;
return this;
}
public Link setFilepath(String filepath) {
this.fileParent = filepath;
return this;
}
public String getHtml() {
return html;
}
public Link setHtml(String html) {
this.html = html;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleRectangle.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleRectangle.java | package mara.mybox.data;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import javafx.scene.image.Image;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:23:40
* @License Apache License Version 2.0
*/
public class DoubleRectangle implements DoubleShape {
protected double x, y, width, height, roundx, roundy;
public DoubleRectangle() {
roundx = 0;
roundy = 0;
}
public static DoubleRectangle xywh(double x, double y, double width, double height) {
DoubleRectangle rect = new DoubleRectangle();
rect.setX(x);
rect.setY(y);
rect.setWidth(width);
rect.setHeight(height);
return rect;
}
public static DoubleRectangle xy12(double x1, double y1, double x2, double y2) {
DoubleRectangle rect = new DoubleRectangle();
rect.setX(Math.min(x1, x2));
rect.setY(Math.min(y1, y2));
rect.setWidth(Math.abs(x2 - x1));
rect.setHeight(Math.abs(y2 - y1));
return rect;
}
public static DoubleRectangle rect(Rectangle2D.Double rect2D) {
if (rect2D == null) {
return null;
}
DoubleRectangle rect = new DoubleRectangle();
rect.setX(rect2D.getX());
rect.setY(rect2D.getY());
rect.setWidth(rect2D.getWidth());
rect.setHeight(rect2D.getHeight());
return rect;
}
public static DoubleRectangle image(Image image) {
if (image == null) {
return null;
}
DoubleRectangle rect = new DoubleRectangle();
rect.setX(0);
rect.setY(0);
rect.setWidth(image.getWidth());
rect.setHeight(image.getHeight());
return rect;
}
public static DoubleRectangle image(BufferedImage image) {
if (image == null) {
return null;
}
DoubleRectangle rect = new DoubleRectangle();
rect.setX(0);
rect.setY(0);
rect.setWidth(image.getWidth());
rect.setHeight(image.getHeight());
return rect;
}
@Override
public String name() {
return message("Rectangle");
}
@Override
public Shape getShape() {
if (roundx > 0 || roundy > 0) {
return new RoundRectangle2D.Double(x, y, width, height, roundx, roundy);
} else {
return new Rectangle2D.Double(x, y, width, height);
}
}
@Override
public DoubleRectangle copy() {
DoubleRectangle rect = DoubleRectangle.xywh(x, y, width, height);
rect.setRoundx(roundx);
rect.setRoundy(roundy);
return rect;
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid() || width <= 0 || height <= 0;
}
public boolean contains(double px, double py) {
if (roundx > 0 || roundy > 0) {
return DoubleShape.contains(this, px, py);
} else {
return px >= x && px < x + width && py >= y && py < y + height;
}
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
x += offsetX;
y += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
width *= scaleX;
height *= scaleY;
return true;
}
@Override
public String pathAbs() {
double sx = imageScale(x);
double sy = imageScale(y);
double sw = imageScale(x + width);
double sh = imageScale(y + height);
return "M " + sx + "," + sy + " \n"
+ "H " + sw + " \n"
+ "V " + sh + " \n"
+ "H " + sx + " \n"
+ "V " + sy;
}
@Override
public String pathRel() {
double sx = imageScale(x);
double sy = imageScale(y);
double sw = imageScale(width);
double sh = imageScale(height);
return "M " + sx + "," + sy + " \n"
+ "h " + sw + " \n"
+ "v " + sh + " \n"
+ "h " + (-sw) + " \n"
+ "v " + (-sh);
}
@Override
public String elementAbs() {
return "<rect x=\"" + imageScale(x) + "\""
+ " y=\"" + imageScale(y) + "\""
+ " width=\"" + imageScale(width) + "\""
+ " height=\"" + imageScale(height) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
public boolean same(DoubleRectangle rect) {
return rect != null
&& x == rect.getX() && y == rect.getY()
&& width == rect.getWidth() && height == rect.getHeight();
}
// exclude maxX and maxY
public double getMaxX() {
return x + width;
}
public double getMaxY() {
return y + height;
}
public void setMaxX(double maxX) {
width = Math.abs(maxX - x);
}
public void setMaxY(double maxY) {
height = Math.abs(maxY - y);
}
public void changeX(double nx) {
width = width + x - nx;
x = nx;
}
public void changeY(double ny) {
height = height + y - ny;
y = ny;
}
/*
get
*/
public final double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public final double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRoundx() {
return roundx;
}
public void setRoundx(double roundx) {
this.roundx = roundx;
}
public double getRoundy() {
return roundy;
}
public void setRoundy(double roundy) {
this.roundy = roundy;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleShape.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleShape.java | package mara.mybox.data;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseShapeController;
import mara.mybox.controller.ControlSvgNodeEdit;
import mara.mybox.controller.TextEditorController;
import mara.mybox.controller.TextPopController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
import org.w3c.dom.Element;
/**
* @Author Mara
* @CreateDate 2019-04-02
* @License Apache License Version 2.0
*/
public interface DoubleShape {
DoubleShape copy();
boolean isValid();
boolean isEmpty();
Shape getShape();
boolean translateRel(double offsetX, double offsetY);
boolean scale(double scaleX, double scaleY);
String name();
String pathRel();
String pathAbs();
String elementAbs();
String elementRel();
/*
static
*/
public static enum ShapeType {
Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Polylines,
Cubic, Quadratic, Arc, Path, Text;
}
public static final double ChangeThreshold = 0.01;
public static boolean changed(double offsetX, double offsetY) {
return Math.abs(offsetX) > ChangeThreshold || Math.abs(offsetY) > ChangeThreshold;
}
public static boolean changed(DoublePoint p1, DoublePoint p2) {
if (p1 == null || p2 == null) {
return false;
}
return changed(p1.getX() - p2.getX(), p1.getY() - p2.getY());
}
public static boolean translateCenterAbs(DoubleShape shapeData, double x, double y) {
DoublePoint center = getCenter(shapeData);
if (center == null) {
return false;
}
double offsetX = x - center.getX();
double offsetY = y - center.getY();
if (DoubleShape.changed(offsetX, offsetY)) {
return shapeData.translateRel(offsetX, offsetY);
}
return false;
}
public static boolean translateRel(DoubleShape shapeData, double offsetX, double offsetY) {
if (DoubleShape.changed(offsetX, offsetY)) {
return shapeData.translateRel(offsetX, offsetY);
}
return false;
}
public static boolean scale(DoubleShape shapeData, double scaleX, double scaleY) {
try {
if (shapeData == null) {
return true;
}
DoublePoint c = getCenter(shapeData);
if (shapeData.scale(scaleX, scaleY)) {
DoubleShape.translateCenterAbs(shapeData, c.getX(), c.getY());
return true;
} else {
return false;
}
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public static DoublePath rorate(DoubleShape shapeData, double angle, double x, double y) {
try {
if (shapeData == null) {
return null;
}
AffineTransform t = AffineTransform.getRotateInstance(Math.toRadians(angle), x, y);
Shape shape = t.createTransformedShape(shapeData.getShape());
return DoublePath.shapeToPathData(shape);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePath shear(DoubleShape shapeData, double x, double y) {
try {
if (shapeData == null) {
return null;
}
AffineTransform t = AffineTransform.getShearInstance(x, y);
Shape shape = t.createTransformedShape(shapeData.getShape());
return DoublePath.shapeToPathData(shape);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePath pathData(DoubleShape shapeData) {
try {
if (shapeData == null) {
return null;
}
return DoublePath.shapeToPathData(shapeData.getShape());
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
// notice bound may truncate values
public static Rectangle2D getBound(DoubleShape shapeData) {
try {
return shapeData.getShape().getBounds2D();
} catch (Exception e) {
return null;
}
}
public static boolean contains(DoubleShape shapeData, double x, double y) {
return shapeData.isValid() && shapeData.getShape().contains(x, y);
}
public static DoublePoint getCenter(DoubleShape shapeData) {
try {
Rectangle2D bound = getBound(shapeData);
return new DoublePoint(bound.getCenterX(), bound.getCenterY());
} catch (Exception e) {
return null;
}
}
public static String values(DoubleShape shapeData) {
try {
Rectangle2D bounds = getBound(shapeData);
return shapeData.name() + "\n"
+ message("LeftTop") + ": " + imageScale(bounds.getMinX()) + ", " + imageScale(bounds.getMinY()) + "\n"
+ message("RightBottom") + ": " + imageScale(bounds.getMaxX()) + ", " + imageScale(bounds.getMaxY()) + "\n"
+ message("Center") + ": " + imageScale(bounds.getCenterX()) + ", " + imageScale(bounds.getCenterY()) + "\n"
+ message("Width") + ": " + imageScale(bounds.getWidth()) + " " + message("Height") + ": " + imageScale(bounds.getHeight());
} catch (Exception e) {
return "";
}
}
public static DoubleShape toShape(BaseController controller, Element node) {
try {
if (node == null) {
return null;
}
switch (node.getNodeName().toLowerCase()) {
case "rect":
return toRect(node);
case "circle":
return toCircle(node);
case "ellipse":
return toEllipse(node);
case "line":
return toLine(node);
case "polyline":
return toPolyline(node);
case "polygon":
return toPolygon(node);
case "path":
return toPath(controller, node);
}
} catch (Exception e) {
}
return null;
}
public static DoubleRectangle toRect(Element node) {
try {
float x, y, w, h;
try {
x = Float.parseFloat(node.getAttribute("x"));
} catch (Exception e) {
return null;
}
try {
y = Float.parseFloat(node.getAttribute("y"));
} catch (Exception e) {
return null;
}
try {
w = Float.parseFloat(node.getAttribute("width"));
} catch (Exception e) {
w = -1f;
}
if (w <= 0) {
return null;
}
try {
h = Float.parseFloat(node.getAttribute("height"));
} catch (Exception e) {
h = -1f;
}
if (h <= 0) {
return null;
}
return DoubleRectangle.xywh(x, y, w, h);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoubleCircle toCircle(Element node) {
try {
float x, y, r;
try {
x = Float.parseFloat(node.getAttribute("cx"));
} catch (Exception e) {
return null;
}
try {
y = Float.parseFloat(node.getAttribute("cy"));
} catch (Exception e) {
return null;
}
try {
r = Float.parseFloat(node.getAttribute("r"));
} catch (Exception e) {
r = -1f;
}
if (r <= 0) {
return null;
}
return new DoubleCircle(x, y, r);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoubleEllipse toEllipse(Element node) {
try {
float cx, cy, rx, ry;
try {
cx = Float.parseFloat(node.getAttribute("cx"));
} catch (Exception e) {
return null;
}
try {
cy = Float.parseFloat(node.getAttribute("cy"));
} catch (Exception e) {
return null;
}
try {
rx = Float.parseFloat(node.getAttribute("rx"));
} catch (Exception e) {
rx = -1f;
}
if (rx <= 0) {
return null;
}
try {
ry = Float.parseFloat(node.getAttribute("ry"));
} catch (Exception e) {
ry = -1f;
}
if (ry <= 0) {
return null;
}
return DoubleEllipse.ellipse(cx, cy, rx, ry);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoubleLine toLine(Element node) {
try {
float x1, y1, x2, y2;
try {
x1 = Float.parseFloat(node.getAttribute("x1"));
} catch (Exception e) {
return null;
}
try {
y1 = Float.parseFloat(node.getAttribute("y1"));
} catch (Exception e) {
return null;
}
try {
x2 = Float.parseFloat(node.getAttribute("x2"));
} catch (Exception e) {
return null;
}
try {
y2 = Float.parseFloat(node.getAttribute("y2"));
} catch (Exception e) {
return null;
}
return new DoubleLine(x1, y1, x2, y2);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePolyline toPolyline(Element node) {
try {
DoublePolyline polyline = new DoublePolyline();
polyline.setAll(DoublePoint.parseImageCoordinates(node.getAttribute("points")));
return polyline;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePolygon toPolygon(Element node) {
try {
DoublePolygon polygon = new DoublePolygon();
polygon.setAll(DoublePoint.parseImageCoordinates(node.getAttribute("points")));
return polygon;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePath toPath(BaseController controller, Element node) {
try {
String d = node.getAttribute("d");
return new DoublePath(controller, d);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> elementMenu(BaseController controller, Element node) {
return svgMenu(controller, toShape(controller, node));
}
public static List<MenuItem> svgMenu(BaseController controller, DoubleShape shapeData) {
if (shapeData == null) {
return null;
}
List<MenuItem> items = new ArrayList<>();
MenuItem menu;
if (shapeData instanceof DoublePath) {
DoublePath pathData = (DoublePath) shapeData;
menu = new MenuItem(message("ConvertToAbsoluteCoordinates"), StyleTools.getIconImageView("iconDelimiter.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
if (pathData.toAbs(controller)) {
if (controller instanceof BaseShapeController) {
((BaseShapeController) controller).maskShapeDataChanged();
} else if (controller instanceof ControlSvgNodeEdit) {
((ControlSvgNodeEdit) controller).loadPath(pathData.getContent());
}
}
}
});
items.add(menu);
menu = new MenuItem(message("ConvertToRelativeCoordinates"), StyleTools.getIconImageView("iconDelimiter.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
if (pathData.toRel(controller)) {
if (controller instanceof BaseShapeController) {
((BaseShapeController) controller).maskShapeDataChanged();
} else if (controller instanceof ControlSvgNodeEdit) {
((ControlSvgNodeEdit) controller).loadPath(pathData.getContent());
}
}
}
});
items.add(menu);
items.add(new SeparatorMenuItem());
}
items.addAll(svgInfoMenu(shapeData));
items.add(new SeparatorMenuItem());
return items;
}
public static List<MenuItem> svgInfoMenu(DoubleShape shapeData) {
if (shapeData == null) {
return null;
}
List<MenuItem> items = new ArrayList<>();
MenuItem menu;
if (shapeData instanceof DoublePath) {
DoublePath pathData = (DoublePath) shapeData;
menu = new MenuItem(message("Pop"), StyleTools.getIconImageView("iconPop.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText(pathData.getContent());
}
});
items.add(menu);
menu = new MenuItem(message("TextEditer"), StyleTools.getIconImageView("iconEdit.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextEditorController.edit(pathData.getContent());
}
});
items.add(menu);
}
if (shapeData instanceof DoublePath || shapeData instanceof DoubleQuadratic
|| shapeData instanceof DoubleCubic || shapeData instanceof DoubleArc) {
menu = new MenuItem(message("DisplaySVGElement") + " - " + message("AbsoluteCoordinate"),
StyleTools.getIconImageView("iconView.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText(shapeData.elementAbs());
}
});
items.add(menu);
menu = new MenuItem(message("DisplaySVGElement") + " - " + message("RelativeCoordinate"),
StyleTools.getIconImageView("iconMeta.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText(shapeData.elementRel());
}
});
items.add(menu);
} else {
menu = new MenuItem(message("DisplaySVGElement"), StyleTools.getIconImageView("iconMeta.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText(shapeData.elementAbs());
}
});
items.add(menu);
menu = new MenuItem(message("DisplaySVGPath") + " - " + message("AbsoluteCoordinate"),
StyleTools.getIconImageView("iconMeta.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText("<path d=\"\n" + shapeData.pathAbs() + "\n\">");
}
});
items.add(menu);
menu = new MenuItem(message("DisplaySVGPath") + " - " + message("RelativeCoordinate"),
StyleTools.getIconImageView("iconMeta.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent mevent) {
TextPopController.loadText("<path d=\"\n" + shapeData.pathRel() + "\n\">");
}
});
items.add(menu);
}
return items;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FileInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/FileInformation.java | package mara.mybox.data;
import java.io.File;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.concurrent.Task;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2018-6-23 6:44:22
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class FileInformation {
protected File file;
protected long tableIndex, fileSize = -1, createTime, modifyTime, filesNumber = 0;
protected String data, handled;
protected FileType fileType;
protected final BooleanProperty selected = new SimpleBooleanProperty(false);
protected long sizeWithSubdir = -1, sizeWithoutSubdir = -1, filesWithSubdir = -1, filesWithoutSubdir = -1;
protected long duration; // milliseconds
public enum FileType {
File, Directory, Link, Socket, Block, Character, FIFO, Root, Digest, NotExist
}
public enum FileSelectorType {
All, ExtensionEuqalAny, ExtensionNotEqualAny,
NameIncludeAny, NameIncludeAll, NameNotIncludeAny, NameNotIncludeAll,
NameMatchRegularExpression, NameNotMatchRegularExpression,
NameIncludeRegularExpression, NameNotIncludeRegularExpression,
FileSizeLargerThan, FileSizeSmallerThan, ModifiedTimeEarlierThan,
ModifiedTimeLaterThan
}
public FileInformation() {
init();
}
public final void init() {
file = null;
filesNumber = tableIndex = fileSize = createTime = modifyTime = -1;
fileType = FileType.NotExist;
handled = null;
data = null;
selected.set(false);
sizeWithSubdir = sizeWithoutSubdir = filesWithSubdir = filesWithoutSubdir = -1;
duration = 3000;
}
public FileInformation(File file) {
setFileAttributes(file);
}
public final void setFileAttributes(File file) {
init();
this.file = file;
if (duration < 0) {
duration = 3000;
}
if (file == null) {
return;
}
if (!file.exists()) {
this.fileType = FileType.NotExist;
return;
}
if (file.isFile()) {
filesNumber = 1;
fileSize = file.length();
fileType = FileType.File;
} else if (file.isDirectory()) {
// long[] size = FileTools.countDirectorySize(file);
// this.filesNumber = size[0];
// this.fileSize = size[1];
sizeWithSubdir = sizeWithoutSubdir = -1;
filesWithSubdir = filesWithoutSubdir = -1;
fileType = FileType.Directory;
}
this.createTime = FileTools.createTime(file);
this.modifyTime = file.lastModified();
}
public void countDirectorySize(Task task, boolean countSubdir, boolean reset) {
if (file == null || !file.isDirectory()) {
return;
}
if (countSubdir) {
if (reset || sizeWithSubdir < 0 || filesWithSubdir < 0) {
long[] size = FileTools.countDirectorySize(file, countSubdir);
if (task == null || task.isCancelled()) {
return;
}
filesWithSubdir = size[0];
sizeWithSubdir = size[1];
}
fileSize = sizeWithSubdir;
filesNumber = filesWithSubdir;
} else {
if (reset || sizeWithoutSubdir < 0 || filesWithoutSubdir < 0) {
long[] size = FileTools.countDirectorySize(file, countSubdir);
if (task == null || task.isCancelled()) {
return;
}
filesWithoutSubdir = size[0];
sizeWithoutSubdir = size[1];
}
fileSize = sizeWithoutSubdir;
filesNumber = filesWithoutSubdir;
}
}
public String getHierarchyNumber() {
return hierarchyNumber(file);
}
public static String hierarchyNumber(File f) {
if (f == null) {
return "";
}
File parent = f.getParentFile();
if (parent == null) {
return "";
}
String p = hierarchyNumber(parent);
String[] children = parent.list();
p = p == null || p.isBlank() ? "" : p + ".";
String name = f.getName();
for (int i = 0; i < children.length; i++) {
String c = children[i];
if (name.equals(c)) {
return p + (i + 1);
}
}
return null;
}
public static FileInformation clone(FileInformation sourceInfo, FileInformation targetInfo) {
if (sourceInfo == null || targetInfo == null) {
return null;
}
targetInfo.file = sourceInfo.file;
targetInfo.tableIndex = sourceInfo.tableIndex;
targetInfo.fileSize = sourceInfo.fileSize;
targetInfo.createTime = sourceInfo.createTime;
targetInfo.modifyTime = sourceInfo.modifyTime;
targetInfo.filesNumber = sourceInfo.filesNumber;
targetInfo.data = sourceInfo.data;
targetInfo.handled = sourceInfo.handled;
targetInfo.fileType = sourceInfo.fileType;
targetInfo.selected.set(sourceInfo.selected.get());
targetInfo.sizeWithSubdir = sourceInfo.sizeWithSubdir;
targetInfo.sizeWithoutSubdir = sourceInfo.sizeWithoutSubdir;
targetInfo.filesWithSubdir = sourceInfo.filesWithSubdir;
targetInfo.filesWithoutSubdir = sourceInfo.filesWithoutSubdir;
targetInfo.duration = sourceInfo.duration;
return targetInfo;
}
/*
custmized get/set
*/
public void setFile(File file) {
setFileAttributes(file);
}
public String getSuffix() {
if (file != null) {
if (file.isDirectory()) {
return null;
} else {
return FileNameTools.ext(file.getName());
}
} else if (data != null) {
return FileNameTools.ext(data);
} else {
return null;
}
}
public String getAbsolutePath() {
if (file != null) {
return file.getAbsolutePath();
} else {
return null;
}
}
public String getFullName() {
if (file != null) {
return file.getAbsolutePath();
} else {
return data;
}
}
public String getPath() {
if (file != null) {
if (file.isDirectory()) {
return file.getAbsolutePath() + File.separator;
} else {
return file.getParent() + File.separator;
}
} else {
return null;
}
}
public String getTfileName() {
if (file != null) {
if (file.isDirectory()) {
return null;
} else {
return file.getName();
}
} else {
return null;
}
}
public String getFileName() {
if (file != null) {
return file.getName();
} else {
return null;
}
}
public boolean isSelected() {
return selected.get();
}
/*
get/set
*/
public File getFile() {
return file;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getHandled() {
return handled;
}
public void setHandled(String handled) {
this.handled = handled;
}
public FileType getFileType() {
return fileType;
}
public void setFileType(FileType fileType) {
this.fileType = fileType;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getModifyTime() {
return modifyTime;
}
public void setModifyTime(long modifyTime) {
this.modifyTime = modifyTime;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public long getFilesNumber() {
return filesNumber;
}
public void setFilesNumber(long filesNumber) {
this.filesNumber = filesNumber;
}
public BooleanProperty getSelected() {
return selected;
}
public void setSelected(boolean select) {
selected.set(select);
}
public long getTableIndex() {
return tableIndex;
}
public void setTableIndex(long tableIndex) {
this.tableIndex = tableIndex;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/LongRange.java | alpha/MyBox/src/main/java/mara/mybox/data/LongRange.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2020-10-6
* @License Apache License Version 2.0
*/
public class LongRange {
protected long start = -1, end = -1, length = -1;
public LongRange() {
start = -1;
end = -1;
length = -1;
}
public LongRange(long start) {
this.start = start;
}
public LongRange(long start, long end) {
this.start = start;
this.end = end;
}
public long getLength() {
if (length < 0) {
length = end - start;
}
return length;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
public void setLength(long length) {
this.length = length;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePathParser.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePathParser.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.data.DoublePathSegment.PathSegmentType;
import org.apache.batik.parser.PathHandler;
import org.apache.batik.parser.PathParser;
/**
* @Author Mara
* @CreateDate 2023-7-30
* @License Apache License Version 2.0
*/
public class DoublePathParser implements PathHandler {
protected double currentX, currentY; // The point between previous segment and current segment
protected double xCenter, yCenter; // for smooth curve
protected int index, scale;
protected List<DoublePathSegment> segments;
public DoublePathParser parse(BaseController controller, String content, int scale) {
try {
segments = null;
this.scale = scale;
currentX = 0;
currentY = 0;
xCenter = 0;
yCenter = 0;
if (content == null || content.isBlank()) {
return null;
}
PathParser pathParser = new PathParser();
pathParser.setPathHandler(this);
pathParser.parse(content);
return this;
} catch (Exception e) {
controller.displayError(e.toString());
return null;
}
}
public List<DoublePathSegment> getSegments() {
if (segments == null || segments.isEmpty()) {
return null;
}
List<DoublePathSegment> list = new ArrayList<>();
for (DoublePathSegment seg : segments) {
list.add(seg.copy());
}
return list;
}
@Override
public void startPath() {
segments = new ArrayList<>();
index = 0;
}
@Override
public void endPath() {
}
@Override
public void closePath() {
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Close)
.setIsAbsolute(true)
.setStartPoint(new DoublePoint(currentX, currentY))
.setEndPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
}
@Override
public void movetoRel(float x, float y) {
xCenter = currentX + x;
yCenter = currentY + y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Move)
.setIsAbsolute(false)
.setScale(scale)
.setEndPoint(new DoublePoint(xCenter, yCenter))
.setEndPointRel(new DoublePoint(x, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
@Override
public void movetoAbs(float x, float y) {
xCenter = x;
yCenter = y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Move)
.setIsAbsolute(true)
.setScale(scale)
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
@Override
public void linetoRel(float x, float y) {
xCenter = currentX + x;
yCenter = currentY + y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Line)
.setIsAbsolute(false)
.setScale(scale)
.setEndPoint(new DoublePoint(xCenter, yCenter))
.setEndPointRel(new DoublePoint(x, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
@Override
public void linetoAbs(float x, float y) {
xCenter = x;
yCenter = y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Line)
.setIsAbsolute(true)
.setScale(scale)
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
@Override
public void linetoHorizontalRel(float x) {
xCenter = currentX + x;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.LineHorizontal)
.setIsAbsolute(false)
.setScale(scale)
.setValue(xCenter)
.setValueRel(x)
.setEndPoint(new DoublePoint(xCenter, currentY))
.setEndPointRel(new DoublePoint(x, 0))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
}
@Override
public void linetoHorizontalAbs(float x) {
xCenter = x;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.LineVertical)
.setIsAbsolute(true)
.setScale(scale)
.setValue(x)
.setEndPoint(new DoublePoint(x, currentY))
.setEndPointRel(new DoublePoint(x - currentX, 0))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
}
@Override
public void linetoVerticalRel(float y) {
yCenter = currentY + y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.LineVertical)
.setIsAbsolute(false)
.setScale(scale)
.setValue(yCenter)
.setValueRel(y)
.setEndPoint(new DoublePoint(currentX, yCenter))
.setEndPointRel(new DoublePoint(0, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentY += y;
}
@Override
public void linetoVerticalAbs(float y) {
yCenter = y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.LineVertical)
.setIsAbsolute(true)
.setScale(scale)
.setValue(y)
.setEndPoint(new DoublePoint(currentX, y))
.setEndPointRel(new DoublePoint(0, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentY = y;
}
@Override
public void curvetoCubicRel(float x1, float y1,
float x2, float y2,
float x, float y) {
xCenter = currentX + x2;
yCenter = currentY + y2;
DoublePoint p = new DoublePoint(x, y);
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Cubic)
.setIsAbsolute(false)
.setScale(scale)
.setControlPoint1(new DoublePoint(currentX + x1, currentY + y1))
.setControlPoint1Rel(new DoublePoint(x1, y1))
.setControlPoint2(new DoublePoint(xCenter, yCenter))
.setControlPoint2Rel(new DoublePoint(x2, y2))
.setEndPoint(new DoublePoint(currentX + x, currentY + y))
.setEndPointRel(p)
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
@Override
public void curvetoCubicAbs(float x1, float y1,
float x2, float y2,
float x, float y) {
xCenter = x2;
yCenter = y2;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Cubic)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(x1, y1))
.setControlPoint1Rel(new DoublePoint(x1 - currentX, y1 - currentY))
.setControlPoint2(new DoublePoint(x2, y2))
.setControlPoint2Rel(new DoublePoint(x2 - currentX, y2 - currentY))
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
// refer to "org.apache.batik.parser.curvetoCubicSmoothRel"
@Override
public void curvetoCubicSmoothRel(float x2, float y2,
float x, float y) {
xCenter = currentX + x2;
yCenter = currentY + y2;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.CubicSmooth)
.setIsAbsolute(false)
.setScale(scale)
.setControlPoint1(new DoublePoint(currentX * 2 - xCenter, currentY * 2 - yCenter))
.setControlPoint1Rel(new DoublePoint(currentX - xCenter, currentY - yCenter))
.setControlPoint2(new DoublePoint(xCenter, yCenter))
.setControlPoint2Rel(new DoublePoint(x2, y2))
.setEndPoint(new DoublePoint(currentX + x, currentY + y))
.setEndPointRel(new DoublePoint(x, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
// refer to "org.apache.batik.parser.curvetoCubicSmoothAbs"
@Override
public void curvetoCubicSmoothAbs(float x2, float y2,
float x, float y) {
xCenter = x2;
yCenter = y2;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.CubicSmooth)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(currentX * 2 - xCenter, currentY * 2 - yCenter))
.setControlPoint1Rel(new DoublePoint(currentX - xCenter, currentY - yCenter))
.setControlPoint2(new DoublePoint(x2, y2))
.setControlPoint2Rel(new DoublePoint(x2 - currentX, y2 - currentY))
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
@Override
public void curvetoQuadraticRel(float x1, float y1,
float x, float y) {
xCenter = currentX + x1;
yCenter = currentY + y1;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Quadratic)
.setIsAbsolute(false)
.setScale(scale)
.setControlPoint1(new DoublePoint(xCenter, yCenter))
.setControlPoint1Rel(new DoublePoint(x1, y1))
.setEndPoint(new DoublePoint(currentX + x, currentY + y))
.setEndPointRel(new DoublePoint(x, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
@Override
public void curvetoQuadraticAbs(float x1, float y1,
float x, float y) {
xCenter = x1;
yCenter = y1;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Quadratic)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(x1, y1))
.setControlPoint1Rel(new DoublePoint(x1 - currentX, y1 - currentY))
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
// refer to "org.apache.batik.parser.curvetoQuadraticSmoothRel"
@Override
public void curvetoQuadraticSmoothRel(float x, float y) {
xCenter = currentX * 2 - xCenter;
yCenter = currentY * 2 - yCenter;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.QuadraticSmooth)
.setIsAbsolute(false)
.setScale(scale)
.setControlPoint1(new DoublePoint(xCenter, yCenter))
.setControlPoint1Rel(new DoublePoint(xCenter - currentX, yCenter - currentY))
.setEndPoint(new DoublePoint(currentX + x, currentY + y))
.setEndPointRel(new DoublePoint(x, y))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
// refer to "org.apache.batik.parser.curvetoQuadraticSmoothAbs"
@Override
public void curvetoQuadraticSmoothAbs(float x, float y) {
xCenter = currentX * 2 - xCenter;
yCenter = currentY * 2 - yCenter;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.QuadraticSmooth)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(xCenter, yCenter))
.setControlPoint1Rel(new DoublePoint(xCenter - currentX, yCenter - currentY))
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
@Override
public void arcRel(float rx, float ry,
float xAxisRotation,
boolean largeArcFlag, boolean sweepFlag,
float x, float y) {
xCenter = currentX + x;
yCenter = currentY + y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Arc)
.setIsAbsolute(false)
.setScale(scale)
.setArcRadius(new DoublePoint(rx, ry))
.setEndPoint(new DoublePoint(xCenter, yCenter))
.setEndPointRel(new DoublePoint(x, y))
.setValue(xAxisRotation)
.setFlag1(largeArcFlag)
.setFlag2(sweepFlag)
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX += x;
currentY += y;
}
@Override
public void arcAbs(float rx, float ry,
float xAxisRotation,
boolean largeArcFlag, boolean sweepFlag,
float x, float y) {
xCenter = x;
yCenter = y;
DoublePathSegment segment = new DoublePathSegment()
.setType(PathSegmentType.Arc)
.setIsAbsolute(true)
.setScale(scale)
.setArcRadius(new DoublePoint(rx, ry))
.setEndPoint(new DoublePoint(x, y))
.setEndPointRel(new DoublePoint(x - currentX, y - currentY))
.setValue(xAxisRotation)
.setFlag1(largeArcFlag)
.setFlag2(sweepFlag)
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = x;
currentY = y;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/ShortCut.java | alpha/MyBox/src/main/java/mara/mybox/data/ShortCut.java | package mara.mybox.data;
import javafx.scene.image.ImageView;
import mara.mybox.fxml.style.StyleTools;
/**
* @Author Mara
* @CreateDate 2022-3-1
* @License Apache License Version 2.0
*/
public class ShortCut {
protected String functionKey, action, possibleAlternative;
protected ImageView icon;
public ShortCut(String key, String combine, String action, String alt, String iconName) {
functionKey = key;
if (combine != null && !combine.isBlank()) {
functionKey += "+" + combine;
}
this.action = action;
this.possibleAlternative = alt;
if (iconName != null && !iconName.isBlank()) {
icon = StyleTools.getIconImageView(iconName);
}
}
/*
get/set
*/
public String getFunctionKey() {
return functionKey;
}
public void setFunctionKey(String functionKey) {
this.functionKey = functionKey;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getPossibleAlternative() {
return possibleAlternative;
}
public void setPossibleAlternative(String possibleAlternative) {
this.possibleAlternative = possibleAlternative;
}
public ImageView getIcon() {
return icon;
}
public void setIcon(ImageView icon) {
this.icon = icon;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePoint.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePoint.java | package mara.mybox.data;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.tools.DoubleTools;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:23:02
* @License Apache License Version 2.0
*/
public class DoublePoint {
public final static String Separator = "\\s+|\\,";
private double x, y;
public DoublePoint() {
x = Double.NaN;
y = Double.NaN;
}
public DoublePoint(double x, double y) {
this.x = x;
this.y = y;
}
public DoublePoint(Point2D p) {
this.x = p.getX();
this.y = p.getY();
}
public boolean same(DoublePoint p) {
if (p == null || !p.valid()) {
return !this.valid();
} else if (!this.valid()) {
return false;
} else {
return x == p.getX() && y == p.getY();
}
}
public boolean valid() {
return !DoubleTools.invalidDouble(x) && !DoubleTools.invalidDouble(y);
}
public DoublePoint translate(double offsetX, double offsetY) {
return new DoublePoint(x + offsetX, y + offsetY);
}
public DoublePoint scale(double scaleX, double scaleY) {
return new DoublePoint(x * scaleX, y * scaleY);
}
public String text(int scale) {
return DoubleTools.scale(x, scale) + "," + DoubleTools.scale(y, scale);
}
public DoublePoint copy() {
return new DoublePoint(x, y);
}
/*
static
*/
public static DoublePoint create() {
return new DoublePoint();
}
public static DoublePoint imageCoordinate(double x, double y) {
int scale = UserConfig.imageScale();
return new DoublePoint(DoubleTools.scale(x, scale), DoubleTools.scale(y, scale));
}
public static double distanceSquare(double x1, double y1, double x2, double y2) {
double distanceX = x1 - x2;
double distanceY = y1 - y2;
return distanceX * distanceX + distanceY * distanceY;
}
public static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt(DoublePoint.distanceSquare(x1, y1, x2, y2));
}
public static double distanceSquare(DoublePoint A, DoublePoint B) {
double distanceX = A.getX() - B.getX();
double distanceY = A.getY() - B.getY();
return distanceX * distanceX + distanceY * distanceY;
}
public static double distance(DoublePoint A, DoublePoint B) {
return Math.sqrt(distanceSquare(A, B));
}
public static int compare(String string1, String string2, String separator, boolean desc) {
return compare(parse(string1, separator), parse(string2, separator), desc);
}
public static int compare(DoublePoint p1, DoublePoint p2, boolean desc) {
try {
if (p1 == null || !p1.valid()) {
if (p2 == null || !p2.valid()) {
return 0;
} else {
return desc ? 1 : -1;
}
} else {
if (p2 == null || !p2.valid()) {
return desc ? -1 : 1;
} else {
int p1c = DoubleTools.compare(p1.x, p2.x, desc);
if (p1c == 0) {
return DoubleTools.compare(p1.y, p2.y, desc);
} else {
return p1c;
}
}
}
} catch (Exception e) {
return 1;
}
}
public static List<DoublePoint> parseImageCoordinates(String string) {
return DoublePoint.parseList(string, DoublePoint.Separator, UserConfig.imageScale());
}
public static List<DoublePoint> parseList(String string, int scale) {
return DoublePoint.parseList(string, DoublePoint.Separator, scale);
}
public static List<DoublePoint> parseList(String string, String separator, int scale) {
try {
if (string == null || string.isBlank()) {
return null;
}
String[] vs = string.split(separator);
if (vs == null || vs.length < 2) {
return null;
}
List<DoublePoint> list = new ArrayList<>();
for (int i = 0; i < vs.length - 1; i += 2) {
list.add(new DoublePoint(
DoubleTools.scale(Double.parseDouble(vs[i]), scale),
DoubleTools.scale(Double.parseDouble(vs[i + 1]), scale)));
}
return list;
} catch (Exception e) {
return null;
}
}
public static DoublePoint parse(String string, String separator) {
try {
if (string == null || string.isBlank()) {
return null;
}
String[] vs = string.split(separator);
if (vs == null || vs.length < 2) {
return null;
}
return new DoublePoint(Double.parseDouble(vs[0]), Double.parseDouble(vs[1]));
} catch (Exception e) {
return null;
}
}
public static String imageCoordinatesToText(List<DoublePoint> points, String separator) {
return toText(points, UserConfig.imageScale(), separator);
}
public static String toText(List<DoublePoint> points, int scale, String separator) {
if (points == null || points.isEmpty()) {
return null;
}
String s = null;
for (DoublePoint p : points) {
if (s != null) {
s += separator;
} else {
s = "";
}
s += DoubleTools.scale(p.getX(), scale) + ","
+ DoubleTools.scale(p.getY(), scale);
}
return s;
}
public static DoublePoint scale(DoublePoint p, int scale) {
try {
if (p == null || scale < 0) {
return p;
}
return new DoublePoint(DoubleTools.scale(p.getX(), scale), DoubleTools.scale(p.getY(), scale));
} catch (Exception e) {
return p;
}
}
public static List<DoublePoint> scaleImageCoordinates(List<DoublePoint> points) {
return scaleList(points, UserConfig.imageScale());
}
public static List<DoublePoint> scaleList(List<DoublePoint> points, int scale) {
if (points == null || points.isEmpty()) {
return points;
}
List<DoublePoint> scaled = new ArrayList<>();
for (DoublePoint p : points) {
scaled.add(scale(p, scale));
}
return scaled;
}
public static List<List<DoublePoint>> scaleLists(List<List<DoublePoint>> list, int scale) {
if (list == null || list.isEmpty()) {
return list;
}
List<List<DoublePoint>> scaled = new ArrayList<>();
for (List<DoublePoint> points : list) {
scaled.add(scaleList(points, scale));
}
return scaled;
}
/*
get/set
*/
public double getX() {
return x;
}
public DoublePoint setX(double x) {
this.x = x;
return this;
}
public double getY() {
return y;
}
public DoublePoint setY(double y) {
this.y = y;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/HtmlNode.java | alpha/MyBox/src/main/java/mara/mybox/data/HtmlNode.java | package mara.mybox.data;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
/**
* @Author Mara
* @CreateDate 2023-2-13
* @License Apache License Version 2.0
*/
public class HtmlNode {
protected Element element;
protected final BooleanProperty selected = new SimpleBooleanProperty(false);
public HtmlNode() {
element = null;
}
public HtmlNode(String tag) {
setElement(new Element(tag));
}
public HtmlNode(Element element) {
setElement(element);
}
public boolean equal(HtmlNode node) {
Element nodeElement = node.getElement();
if (element == null || nodeElement == null) {
return false;
}
return element.equals(nodeElement);
}
/*
set
*/
final public void setElement(Element element) {
this.element = element;
}
/*
get
*/
public Element getElement() {
return element;
}
public String getTitle() {
return getTag();
}
public String getValue() {
return getWholeText();
}
public String getTag() {
return element == null ? null : element.tagName();
}
public String getId() {
return element == null ? null : element.id();
}
public String getName() {
return element == null ? null : element.nodeName();
}
public String getWholeOwnText() {
return element == null ? null : element.wholeOwnText();
}
public String getWholeText() {
return element == null ? null : element.wholeText();
}
public String getText() {
return element == null ? null : element.text();
}
public String getElementValue() {
return element == null ? null : element.val();
}
public String getData() {
return element == null ? null : element.data();
}
public String getInnerHtml() {
return element == null ? null : element.html();
}
public String getOuterHtml() {
return element == null ? null : element.outerHtml();
}
public String getClassname() {
return element == null ? null : element.className();
}
public Attributes getAttributes() {
return element == null ? null : element.attributes();
}
public BooleanProperty getSelected() {
return selected;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/ProcessParameters.java | alpha/MyBox/src/main/java/mara/mybox/data/ProcessParameters.java | package mara.mybox.data;
import java.io.File;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2019-4-11 10:54:30
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ProcessParameters implements Cloneable {
public FileInformation currentSourceFile;
public File currentTargetPath;
public String status, targetPath, targetRootPath;
public boolean targetSubDir, isBatch;
public int fromPage, toPage, startPage; // 0-based, exclude end
public String password;
@Override
public Object clone() throws CloneNotSupportedException {
try {
ProcessParameters newCode = (ProcessParameters) super.clone();
if (currentSourceFile != null) {
newCode.currentSourceFile = currentSourceFile;
}
if (currentTargetPath != null) {
newCode.currentTargetPath = new File(currentTargetPath.getAbsolutePath());
}
return newCode;
} 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/alpha/MyBox/src/main/java/mara/mybox/data/KeyValue.java | alpha/MyBox/src/main/java/mara/mybox/data/KeyValue.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2020-7-30
* @License Apache License Version 2.0
*/
public class KeyValue {
protected String key;
protected String value;
public KeyValue(String key, String value) {
this.key = key;
this.value = value;
}
/*
get/set
*/
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/ListKMeans.java | alpha/MyBox/src/main/java/mara/mybox/data/ListKMeans.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2019-10-7
* @License Apache License Version 2.0
*/
public class ListKMeans<T> {
protected List<T> centers;
protected List<Integer>[] clusters;
protected int k, maxIteration, loopCount;
protected long cost;
protected Map<T, T> dataMap;
protected FxTask task;
public ListKMeans() {
k = 1;
maxIteration = 10000;
}
public static ListKMeans create() {
return new ListKMeans();
}
public void initData() {
}
public boolean isDataEmpty() {
return true;
}
public int dataSize() {
return 0;
}
public T getData(int index) {
return null;
}
public List<T> allData() {
return null;
}
public int centerSize() {
return centers != null ? centers.size() : 0;
}
public void initCenters() {
try {
centers = new ArrayList<>();
int dataSize = dataSize();
if (dataSize < k) {
centers.addAll(allData());
return;
}
int mod = dataSize / k;
for (int i = 0; i < dataSize; i = i + mod) {
if (task != null && !task.isWorking()) {
return;
}
centers.add(getData(i));
if (centers.size() == k) {
return;
}
}
Random random = new Random();
while (centers.size() < k) {
if (task != null && !task.isWorking()) {
return;
}
int index = random.nextInt(dataSize);
T d = getData(index);
if (!centers.contains(d)) {
centers.add(d);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public double distance(T p1, T p2) {
return 0;
}
public boolean equal(T p1, T p2) {
return true;
}
public T calculateCenters(List<Integer> ps) {
return null;
}
public boolean run() {
loopCount = 0;
if (k <= 0) {
return false;
}
if (isDataEmpty()) {
initData();
if (isDataEmpty()) {
return false;
}
}
if (centers == null || centers.isEmpty()) {
initCenters();
if (centers == null || centers.isEmpty()) {
return false;
}
}
int dataSize = dataSize();
if (dataSize < k) {
clusters = new ArrayList[dataSize];
for (int i = 0; i < dataSize; ++i) {
clusters[i] = new ArrayList<>();
clusters[i].add(i);
}
return true;
}
clusters = new ArrayList[k];
try {
if (task != null) {
task.setInfo("data: " + dataSize() + " k:" + k
+ " maxIteration:" + maxIteration + " loopCount:" + loopCount);
}
while (true) {
if (task != null && !task.isWorking()) {
return false;
}
for (int i = 0; i < k; ++i) {
clusters[i] = new ArrayList<>();
}
for (int i = 0; i < dataSize; ++i) {
if (task != null && !task.isWorking()) {
return false;
}
T p = getData(i);
double min = Double.MAX_VALUE;
int index = 0;
for (int j = 0; j < centers.size(); ++j) {
if (task != null && !task.isWorking()) {
return false;
}
T center = centers.get(j);
double distance = distance(center, p);
if (distance < min) {
min = distance;
index = j;
}
}
clusters[index].add(i);
}
boolean centerchange = false;
for (int i = 0; i < k; ++i) {
if (task != null && !task.isWorking()) {
return false;
}
T newCenter = calculateCenters(clusters[i]);
T oldCenter = centers.get(i);
if (!equal(newCenter, oldCenter)) {
centerchange = true;
centers.set(i, newCenter);
}
}
loopCount++;
if (!centerchange || loopCount >= maxIteration) {
break;
}
if (task != null && (loopCount % 100 == 0)) {
task.setInfo("loopCount:" + loopCount);
}
}
if (task != null) {
task.setInfo("loopCount:" + loopCount);
task.setInfo("centers: " + centers.size() + " clusters: " + clusters.length);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeMap() {
if (isDataEmpty() || centers == null || clusters == null) {
return false;
}
dataMap = new HashMap<>();
for (int i = 0; i < clusters.length; ++i) {
if (task != null && !task.isWorking()) {
return false;
}
List<Integer> cluster = clusters[i];
T centerData = centers.get(i);
for (Integer index : cluster) {
if (task != null && !task.isWorking()) {
return false;
}
dataMap.put(getData(index), centerData);
}
}
// MyBoxLog.debug("dataMap: " + dataMap.size());
return true;
}
public T belongCenter(T value) {
if (isDataEmpty() || value == null || clusters == null) {
return value;
}
for (int i = 0; i < clusters.length; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
List<Integer> cluster = clusters[i];
T centerData = centers.get(i);
for (Integer index : cluster) {
if (task != null && !task.isWorking()) {
return null;
}
if (getData(index) == value) {
return centerData;
}
}
}
return null;
}
public T preProcess(T value) {
return value;
}
public T nearestCenter(T value) {
try {
if (value == null) {
return value;
}
T targetValue = value;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < centers.size(); ++i) {
if (task != null && !task.isWorking()) {
return null;
}
T centerValue = centers.get(i);
double distance = distance(value, centerValue);
if (distance < minDistance) {
minDistance = distance;
targetValue = centerValue;
}
}
return targetValue;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public T map(T value) {
try {
if (value == null) {
return value;
}
T targetValue = preProcess(value);
T mappedValue;
if (dataMap == null) {
mappedValue = belongCenter(value);
} else {
mappedValue = dataMap.get(targetValue);
}
// Some new colors maybe generated outside regions due to dithering again
if (mappedValue == null) {
mappedValue = nearestCenter(targetValue);
// dataMap.put(targetValue, mappedValue);
}
return mappedValue;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
get/set
*/
public List<T> getCenters() {
return centers;
}
public ListKMeans setCenters(List<T> centers) {
this.centers = centers;
return this;
}
public int getK() {
return k;
}
public ListKMeans setK(int k) {
this.k = k;
return this;
}
public int getMaxIteration() {
return maxIteration;
}
public ListKMeans setMaxIteration(int maxIteration) {
this.maxIteration = maxIteration;
return this;
}
public int getLoopCount() {
return loopCount;
}
public void setLoopCount(int loopCount) {
this.loopCount = loopCount;
}
public long getCost() {
return cost;
}
public void setCost(long cost) {
this.cost = cost;
}
public List<Integer>[] getClusters() {
return clusters;
}
public void setClusters(List<Integer>[] clusters) {
this.clusters = clusters;
}
public Map<T, T> getDataMap() {
return dataMap;
}
public void setDataMap(Map<T, T> dataMap) {
this.dataMap = dataMap;
}
public FxTask getTask() {
return task;
}
public ListKMeans 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/alpha/MyBox/src/main/java/mara/mybox/data/DoublePolyline.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePolyline.java | package mara.mybox.data;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @License Apache License Version 2.0
*/
public class DoublePolyline implements DoubleShape {
private final List<DoublePoint> points;
public DoublePolyline() {
points = new ArrayList<>();
}
@Override
public String name() {
return message("Polyline");
}
@Override
public Shape getShape() {
Path2D.Double path = new Path2D.Double();
DoublePoint p = points.get(0);
path.moveTo(p.getX(), p.getY());
for (int i = 1; i < points.size(); i++) {
p = points.get(i);
path.lineTo(p.getX(), p.getY());
}
return path;
}
public boolean add(double x, double y) {
return add(new DoublePoint(x, y));
}
public boolean add(DoublePoint p) {
if (p == null) {
return false;
}
points.add(p);
return true;
}
public boolean addAll(List<DoublePoint> ps) {
if (ps == null) {
return false;
}
points.addAll(ps);
return true;
}
public boolean addAll(String values) {
return addAll(DoublePoint.parseImageCoordinates(values));
}
public boolean setAll(List<DoublePoint> ps) {
points.clear();
return addAll(ps);
}
public boolean set(int index, DoublePoint p) {
if (p == null || index < 0 || index >= points.size()) {
return false;
}
points.set(index, p);
return true;
}
public boolean remove(double x, double y) {
if (points == null || points.isEmpty()) {
return false;
}
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
if (p.getX() == x && p.getY() == y) {
remove(i);
break;
}
}
return true;
}
public boolean remove(int i) {
if (points == null || i < 0 || i >= points.size()) {
return false;
}
points.remove(i);
return true;
}
public boolean removeLast() {
if (points == null || points.isEmpty()) {
return false;
}
return remove(points.size() - 1);
}
@Override
public boolean isValid() {
return points != null;
}
@Override
public boolean isEmpty() {
return !isValid() || points.isEmpty();
}
@Override
public DoublePolyline copy() {
DoublePolyline np = new DoublePolyline();
np.addAll(points);
return np;
}
public boolean same(DoublePolyline polyline) {
if (polyline == null) {
return false;
}
if (points == null || points.isEmpty()) {
return polyline.getPoints() == null || polyline.getPoints().isEmpty();
} else {
if (polyline.getPoints() == null || points.size() != polyline.getPoints().size()) {
return false;
}
}
List<DoublePoint> bPoints = polyline.getPoints();
for (int i = 0; i < points.size(); ++i) {
DoublePoint point = points.get(i);
if (!point.same(bPoints.get(i))) {
return false;
}
}
return true;
}
public void clear() {
points.clear();
}
public List<DoublePoint> getPoints() {
return points;
}
public int getSize() {
if (points == null) {
return 0;
}
return points.size();
}
public List<Double> getData() {
List<Double> d = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
d.add(points.get(i).getX());
d.add(points.get(i).getY());
}
return d;
}
public Map<String, int[]> getIntXY() {
Map<String, int[]> xy = new HashMap<>();
if (points == null || points.isEmpty()) {
return xy;
}
int[] x = new int[points.size()];
int[] y = new int[points.size()];
for (int i = 0; i < points.size(); ++i) {
x[i] = (int) Math.round(points.get(i).getX());
y[i] = (int) Math.round(points.get(i).getY());
}
xy.put("x", x);
xy.put("y", y);
return xy;
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
List<DoublePoint> moved = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
moved.add(p.translate(offsetX, offsetY));
}
points.clear();
points.addAll(moved);
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
List<DoublePoint> scaled = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
scaled.add(p.scale(scaleX, scaleY));
}
points.clear();
points.addAll(scaled);
return true;
}
@Override
public String pathAbs() {
String path = "";
DoublePoint p = points.get(0);
path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
for (int i = 1; i < points.size(); i++) {
p = points.get(i);
path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
}
return path;
}
@Override
public String pathRel() {
String path = "";
DoublePoint p = points.get(0);
path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
double lastx = p.getX();
double lasty = p.getY();
for (int i = 1; i < points.size(); i++) {
p = points.get(i);
path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n";
lastx = p.getX();
lasty = p.getY();
}
return path;
}
@Override
public String elementAbs() {
return "<polygon points=\""
+ DoublePoint.toText(points, UserConfig.imageScale(), " ") + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
public DoublePoint get(int i) {
if (points == null || points.isEmpty()) {
return null;
}
return points.get(i);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/TextEditInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/TextEditInformation.java | package mara.mybox.data;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.tools.TextTools.bomBytes;
import static mara.mybox.tools.TextTools.bomSize;
/**
* @Author Mara
* @CreateDate 2018-12-10 13:06:33
* @License Apache License Version 2.0
*/
public class TextEditInformation extends FileEditInformation {
public TextEditInformation() {
editType = Edit_Type.Text;
}
public TextEditInformation(File file) {
super(file);
editType = Edit_Type.Text;
initValues();
}
@Override
public boolean readTotalNumbers(FxTask currentTask) {
if (file == null || pagination.pageSize <= 0 || lineBreakValue == null) {
return false;
}
pagination.objectsNumber = 0;
pagination.rowsNumber = 0;
pagination.pagesNumber = 1;
long lineIndex = 0, charIndex = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) {
String line;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
charIndex += line.length();
lineIndex++;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
pagination.rowsNumber = lineIndex;
pagination.pagesNumber = pagination.rowsNumber / pagination.pageSize;
if (pagination.rowsNumber % pagination.pageSize > 0) {
pagination.pagesNumber++;
}
pagination.objectsNumber = charIndex
+ (pagination.rowsNumber > 0 ? pagination.rowsNumber - 1 : 0);
totalNumberRead = true;
return true;
}
@Override
public String readPage(FxTask currentTask, long pageNumber) {
return readLines(currentTask, pageNumber * pagination.pageSize, pagination.pageSize);
}
@Override
public String readLines(FxTask currentTask, long from, long number) {
if (file == null || from < 0 || number <= 0
|| (pagination.rowsNumber > 0 && from >= pagination.rowsNumber)) {
return null;
}
long lineIndex = 0, charIndex = 0, lineStart = 0;
StringBuilder pageText = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) {
lineStart = (from / pagination.pageSize) * pagination.pageSize;
long lineEnd = Math.max(from + number, lineStart + pagination.pageSize);
String line, fixedLine;
boolean moreLine = false;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (lineIndex > 0) {
fixedLine = "\n" + line;
} else {
fixedLine = line;
}
charIndex += fixedLine.length();
if (lineIndex++ < lineStart) {
continue;
}
if (moreLine) {
pageText.append(fixedLine);
} else {
pageText.append(line);
moreLine = true;
}
if (lineIndex >= lineEnd) {
break;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
pagination.currentPage = lineStart / pagination.pageSize;
pagination.startObjectOfCurrentPage = charIndex - pageText.length();
pagination.endObjectOfCurrentPage = charIndex;
pagination.startRowOfCurrentPage = lineStart;
pagination.endRowOfCurrentPage = lineIndex;
return pageText.toString();
}
@Override
public String readObjects(FxTask currentTask, long from, long number) {
if (file == null || from < 0 || number <= 0
|| (pagination.objectsNumber > 0 && from >= pagination.objectsNumber)) {
return null;
}
long charIndex = 0, lineIndex = 0, lineStart = 0;
StringBuilder pageText = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) {
long to = from + number;
boolean moreLine = false;
String line, fixedLine;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (lineIndex > 0) {
fixedLine = "\n" + line;
} else {
fixedLine = line;
}
if (moreLine) {
pageText.append(fixedLine);
} else {
pageText.append(line);
moreLine = true;
}
charIndex += fixedLine.length();
if (++lineIndex == lineStart + pagination.pageSize && charIndex < from) {
lineStart = lineIndex;
pageText = new StringBuilder();
moreLine = false;
}
if (charIndex >= to && lineIndex >= lineStart + pagination.pageSize) {
break;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
pagination.currentPage = lineStart / pagination.pageSize;
pagination.startObjectOfCurrentPage = charIndex - pageText.length();
pagination.endObjectOfCurrentPage = charIndex;
pagination.startRowOfCurrentPage = lineStart;
pagination.endRowOfCurrentPage = lineIndex;
return pageText.toString();
}
@Override
public File filter(FxTask currentTask, boolean recordLineNumbers) {
try {
if (file == null || filterStrings == null || filterStrings.length == 0) {
return file;
}
File targetFile = FileTmpTools.getTempFile();
long lineIndex = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset));
BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) {
String line;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (isMatchFilters(line)) {
if (recordLineNumbers) {
line = StringTools.fillRightBlank(lineIndex, 15) + line;
}
writer.write(line + lineBreakValue);
}
lineIndex++;
}
writer.flush();
}
return targetFile;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
@Override
public boolean writeObject(FxTask currentTask, String text) {
if (file == null || charset == null || text == null || text.isEmpty()) {
return false;
}
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) {
if (withBom) {
byte[] bytes = bomBytes(charset.name());
outputStream.write(bytes);
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (lineBreak != Line_Break.LF) {
writer.write(text.replaceAll("\n", lineBreakValue));
} else {
writer.write(text);
}
writer.flush();
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
return true;
}
@Override
public boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String pageText) {
try {
if (sourceInfo.getFile() == null || sourceInfo.getCharset() == null
|| sourceInfo.pagination.pageSize <= 0 || pageText == null
|| file == null || charset == null || lineBreakValue == null) {
return false;
}
File targetFile = file;
if (sourceInfo.getFile().equals(file)) {
targetFile = FileTmpTools.getTempFile();
}
try (BufferedReader reader = new BufferedReader(new FileReader(sourceInfo.getFile(), sourceInfo.charset));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) {
if (sourceInfo.isWithBom()) {
reader.skip(bomSize(sourceInfo.getCharset().name()));
}
if (withBom) {
byte[] bytes = bomBytes(charset.name());
outputStream.write(bytes);
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
String line, text;
long lineIndex = 0, pageLineStart = sourceInfo.pagination.startRowOfCurrentPage,
pageLineEnd = sourceInfo.pagination.endRowOfCurrentPage;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
text = null;
if (lineIndex < pageLineStart || lineIndex >= pageLineEnd) {
text = line;
} else if (lineIndex == pageLineStart) {
if (lineBreak != Line_Break.LF) {
text = pageText.replaceAll("\n", lineBreakValue);
} else {
text = pageText;
}
}
if (text != null) {
if (lineIndex > 0) {
text = lineBreakValue + text;
}
writer.write(text);
}
lineIndex++;
}
writer.flush();
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (sourceInfo.getFile().equals(file)) {
FileTools.override(targetFile, file);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceFile.java | alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceFile.java | package mara.mybox.data;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.data.FileEditInformation.Edit_Type;
import static mara.mybox.data.FindReplaceString.Operation.FindAll;
import static mara.mybox.data.FindReplaceString.Operation.ReplaceAll;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.FxTask;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2020-11-9
* @License Apache License Version 2.0
*/
public class FindReplaceFile extends FindReplaceString {
protected BaseController controller;
protected FileEditInformation fileInfo;
protected long position;
protected LongRange fileRange; // location in whole file
protected DataFileCSV matchesData;
public FindReplaceFile() {
}
@Override
public FindReplaceString reset() {
super.reset();
fileRange = null;
matchesData = null;
return this;
}
public FindReplaceString findReplaceString() {
FindReplaceString findReplaceString = new FindReplaceString()
.setOperation(operation)
.setInputString(inputString)
.setFindString(findString)
.setAnchor(anchor)
.setUnit(unit)
.setReplaceString(replaceString)
.setIsRegex(isRegex)
.setCaseInsensitive(caseInsensitive)
.setMultiline(multiline)
.setDotAll(dotAll)
.setWrap(wrap);
return findReplaceString;
}
public boolean shouldHandleAsString() {
return fileInfo.pagination.pagesNumber < 2
&& inputString != null && !inputString.isEmpty();
}
public boolean handlePage(FxTask currentTask) {
reset();
if (operation == null || fileInfo == null
|| findString == null || findString.isEmpty()) {
return false;
}
fileInfo.setFindReplace(this);
// MyBoxLog.debug("operation:" + operation + " unit:" + unit
// + " anchor:" + anchor + " position:" + position + " page:" + fileInfo.getCurrentPage());
if (shouldHandleAsString()) {
return handleString(currentTask);
}
// try current page at first
if (operation == Operation.FindNext || operation == Operation.ReplaceFirst
|| operation == Operation.FindPrevious) {
FindReplaceString findReplaceString = findReplaceString().setWrap(false);
findReplaceString.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (findReplaceString.getStringRange() != null) {
stringRange = findReplaceString.getStringRange();
lastMatch = findReplaceString.getLastMatch();
outputString = findReplaceString.getOutputString();
lastReplacedLength = findReplaceString.getLastReplacedLength();
matches = findReplaceString.getMatches();
// MyBoxLog.debug("stringRange:" + stringRange.getStart() + " " + stringRange.getEnd());
fileRange = FindReplaceTextFile.fileRange(this);
// MyBoxLog.debug("fileRange:" + fileRange.getStart() + " " + fileRange.getEnd());
return true;
}
}
return false;
}
public boolean handleFile(FxTask currentTask) {
// MyBoxLog.console(operation);
reset();
if (operation == null || fileInfo == null
|| findString == null || findString.isEmpty()) {
return false;
}
fileInfo.setFindReplace(this);
// MyBoxLog.debug("operation:" + operation + " unit:" + unit
// + " anchor:" + anchor + " position:" + position + " page:" + fileInfo.getCurrentPage());
if (shouldHandleAsString()) {
return handleString(currentTask);
}
// MyBoxLog.debug("findString.length():" + findString.length());
// MyBoxLog.debug(fileInfo.getEditType());
if (fileInfo.getEditType() != Edit_Type.Bytes) {
// MyBoxLog.debug("fileFindString.length():" + fileFindString.length());
switch (operation) {
case Count:
return FindReplaceTextFile.countText(currentTask, fileInfo, this);
case FindNext:
return FindReplaceTextFile.findNextText(currentTask, fileInfo, this);
case FindPrevious:
return FindReplaceTextFile.findPreviousText(currentTask, fileInfo, this);
case ReplaceFirst:
return FindReplaceTextFile.replaceFirstText(currentTask, fileInfo, this);
case ReplaceAll:
return FindReplaceTextFile.replaceAllText(currentTask, fileInfo, this);
case FindAll:
return FindReplaceTextFile.findAllText(currentTask, fileInfo, this);
default:
break;
}
} else {
switch (operation) {
case Count:
return FindReplaceBytesFile.countBytes(currentTask, fileInfo, this);
case FindNext:
return FindReplaceBytesFile.findNextBytes(currentTask, fileInfo, this);
case FindPrevious:
return FindReplaceBytesFile.findPreviousBytes(currentTask, fileInfo, this);
case ReplaceFirst:
return FindReplaceBytesFile.replaceFirstBytes(currentTask, fileInfo, this);
case ReplaceAll:
return FindReplaceBytesFile.replaceAllBytes(currentTask, fileInfo, this);
case FindAll:
return FindReplaceBytesFile.findAllBytes(currentTask, fileInfo, this);
default:
break;
}
}
return currentTask == null || currentTask.isWorking();
}
public void backup(FxTask currentTask, File file) {
if (controller == null) {
return;
}
if (file != null && UserConfig.getBoolean(controller.getBaseName() + "BackupWhenSave", true)) {
controller.addBackup(currentTask, file);
}
}
public boolean isMultiplePages() {
return fileInfo != null && fileInfo.pagination.pagesNumber > 1;
}
public DataFileCSV initMatchesData(File sourceFile) {
String dname = sourceFile == null ? "" : (sourceFile.getName() + "_") + message("Find");
matchesData = new DataFileCSV();
File matchesFile = matchesData.tmpFile(dname, null, "csv");
matchesData.setFile(matchesFile)
.setDataName(dname)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",").setHasHeader(true)
.setColsNumber(3)
.setComments(sourceFile == null ? "" : (message("SourceFile") + ": " + sourceFile + "\n")
+ message("Find") + ": " + findString);
List<Data2DColumn> columns = new ArrayList<>();
if (sourceFile == null) {
columns.add(new Data2DColumn(message("File"), ColumnDefinition.ColumnType.String));
}
columns.add(new Data2DColumn(message("Start"), ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(message("End"), ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(message("String") + "1", ColumnDefinition.ColumnType.String));
matchesData.setColumns(columns);
return matchesData;
}
/*
get/set
*/
public FileEditInformation getFileInfo() {
return fileInfo;
}
public FindReplaceFile setFileInfo(FileEditInformation fileInfo) {
this.fileInfo = fileInfo;
return this;
}
public LongRange getFileRange() {
return fileRange;
}
public FindReplaceFile setFileRange(LongRange lastFound) {
this.fileRange = lastFound;
return this;
}
public long getPosition() {
return position;
}
public FindReplaceFile setPosition(long position) {
this.position = position;
return this;
}
public DataFileCSV getMatchesData() {
return matchesData;
}
public FindReplaceFile setMatchesData(DataFileCSV matchesData) {
this.matchesData = matchesData;
return this;
}
public BaseController getController() {
return controller;
}
public FindReplaceFile setController(BaseController controller) {
this.controller = controller;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/CertificateEntry.java | alpha/MyBox/src/main/java/mara/mybox/data/CertificateEntry.java | package mara.mybox.data;
import java.security.cert.Certificate;
/**
* @Author Mara
* @CreateDate 2019-12-1
* @License Apache License Version 2.0
*/
public class CertificateEntry {
protected String alias;
protected long createTime;
protected Certificate[] certificateChain;
public static CertificateEntry create() {
return new CertificateEntry();
}
public String getCertificates() {
if (certificateChain == null) {
return "";
}
String s = "";
for (Certificate cert : certificateChain) {
s += cert + "\n\n";
}
return s;
}
public String getAlias() {
return alias;
}
public CertificateEntry setAlias(String alias) {
this.alias = alias;
return this;
}
public long getCreateTime() {
return createTime;
}
public CertificateEntry setCreateTime(long createTime) {
this.createTime = createTime;
return this;
}
public Certificate[] getCertificateChain() {
return certificateChain;
}
public CertificateEntry setCertificateChain(Certificate[] certificateChain) {
this.certificateChain = certificateChain;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleValue.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleValue.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2019-2-10 12:47:33
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class DoubleValue {
private String type, name;
private double value;
private double percentage;
public DoubleValue() {
}
public DoubleValue(double value) {
this.type = null;
this.name = null;
this.value = value;
}
public DoubleValue(String name, double value) {
this.type = null;
this.name = name;
this.value = value;
}
public DoubleValue(String type, String name, double value) {
this.type = type;
this.name = name;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/PdfInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/PdfInformation.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Optional;
import javafx.application.Platform;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.PdfTools;
import static mara.mybox.value.Languages.message;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
/**
* @Author Mara
* @CreateDate 2018-6-9 12:18:38
* @License Apache License Version 2.0
*/
public class PdfInformation extends FileInformation {
protected String userPassword, ownerPassword, title, subject, author, creator, producer, keywords;
protected float version;
protected int numberOfPages, fromPage, toPage; // 0-based, exclude end
protected String firstPageSize, firstPageSize2, error;
protected PDDocument doc;
protected PDDocumentOutline outline;
protected AccessPermission access;
protected boolean infoLoaded;
public PdfInformation() {
}
public PdfInformation(File file) {
super(file);
fromPage = 0;
toPage = 0;
doc = null;
}
public void openDocument(String password) {
try {
this.userPassword = password;
if (doc == null) {
doc = Loader.loadPDF(file, password);
}
infoLoaded = false;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void closeDocument() {
try {
if (doc != null) {
doc.close();
}
doc = null;
infoLoaded = false;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void loadInformation(FxTask task) {
try {
if (doc == null) {
return;
}
if (task != null) {
task.setInfo(message("ReadingData"));
}
PDDocumentInformation docInfo = doc.getDocumentInformation();
if (docInfo.getCreationDate() != null) {
createTime = docInfo.getCreationDate().getTimeInMillis();
}
if (docInfo.getModificationDate() != null) {
modifyTime = docInfo.getModificationDate().getTimeInMillis();
}
creator = docInfo.getCreator();
producer = docInfo.getProducer();
title = docInfo.getTitle();
subject = docInfo.getSubject();
author = docInfo.getAuthor();
numberOfPages = doc.getNumberOfPages();
keywords = docInfo.getKeywords();
version = doc.getVersion();
access = doc.getCurrentAccessPermission();
if (task != null) {
task.setInfo(message("NumberOfPages") + ": " + numberOfPages);
}
PDPage page = doc.getPage(0);
String size = "";
PDRectangle box = page.getMediaBox();
if (box != null) {
size += "MediaBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
+ PdfTools.pixels2mm(box.getHeight()) + "mm";
}
box = page.getTrimBox();
if (box != null) {
size += " TrimBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
+ PdfTools.pixels2mm(box.getHeight()) + "mm";
}
firstPageSize = size;
size = "";
box = page.getCropBox();
if (box != null) {
size += "CropBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
+ PdfTools.pixels2mm(box.getHeight()) + "mm";
}
box = page.getBleedBox();
if (box != null) {
size += " BleedBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
+ PdfTools.pixels2mm(box.getHeight()) + "mm";
}
firstPageSize2 = size;
if (task != null) {
task.setInfo(message("Size") + ": " + firstPageSize);
}
outline = doc.getDocumentCatalog().getDocumentOutline();
infoLoaded = true;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void loadInfo(FxTask task, String password) {
try {
openDocument(password);
if (doc == null) {
return;
}
loadInformation(task);
closeDocument();
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void readInfo(FxTask task, PDDocument doc) {
this.doc = doc;
loadInformation(task);
}
public BufferedImage readPageAsImage(int page) {
return readPageAsImage(page, ImageType.ARGB);
}
public BufferedImage readPageAsImage(int page, ImageType imageType) {
try {
if (doc == null) {
return null;
}
PDFRenderer renderer = new PDFRenderer(doc);
BufferedImage image = renderer.renderImage(page, 1, imageType);
return image;
} catch (Exception e) {
return null;
}
}
public static boolean readPDF(FxTask task, PdfInformation info) {
if (info == null) {
return false;
}
if (task != null) {
task.setInfo(message("LoadingFileInfo"));
}
try (PDDocument doc = Loader.loadPDF(info.getFile(), info.getUserPassword())) {
info.readInfo(task, doc);
doc.close();
return true;
} catch (InvalidPasswordException e) {
try {
Platform.runLater(() -> {
TextInputDialog dialog = new TextInputDialog();
dialog.setContentText(message("UserPassword"));
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
info.setUserPassword(result.get());
}
synchronized (info) {
info.notifyAll();
}
});
synchronized (info) {
info.wait();
}
Platform.requestNextPulse();
try (PDDocument doc = Loader.loadPDF(info.getFile(), info.getUserPassword())) {
info.readInfo(task, doc);
doc.close();
return true;
} catch (Exception ee) {
info.setError(ee.toString());
return false;
}
} catch (Exception eee) {
info.setError(eee.toString());
return false;
}
} catch (Exception eeee) {
info.setError(eeee.toString());
return false;
}
}
// cell values
public int getFrom() {
return fromPage + 1;
}
public int getTo() {
return toPage;
}
/*
get/set
*/
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getVersion() {
return version;
}
public void setVersion(float version) {
this.version = version;
}
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getFirstPageSize() {
return firstPageSize;
}
public void setFirstPageSize(String firstPageSize) {
this.firstPageSize = firstPageSize;
}
public String getFirstPageSize2() {
return firstPageSize2;
}
public void setFirstPageSize2(String firstPageSize2) {
this.firstPageSize2 = firstPageSize2;
}
public PDDocument getDoc() {
return doc;
}
public void setDoc(PDDocument doc) {
this.doc = doc;
}
public boolean isInfoLoaded() {
return infoLoaded;
}
public void setInfoLoaded(boolean infoLoaded) {
this.infoLoaded = infoLoaded;
}
public PDDocumentOutline getOutline() {
return outline;
}
public void setOutline(PDDocumentOutline outline) {
this.outline = outline;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public AccessPermission getAccess() {
return access;
}
public void setAccess(AccessPermission access) {
this.access = access;
}
public String getOwnerPassword() {
return ownerPassword;
}
public void setOwnerPassword(String ownerPassword) {
this.ownerPassword = ownerPassword;
}
public int getFromPage() {
return fromPage;
}
public void setFromPage(int fromPage) {
this.fromPage = fromPage;
}
public int getToPage() {
return toPage;
}
public void setToPage(int toPage) {
this.toPage = toPage;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/JShellSnippet.java | alpha/MyBox/src/main/java/mara/mybox/data/JShellSnippet.java | package mara.mybox.data;
import jdk.jshell.ErroneousSnippet;
import jdk.jshell.ExpressionSnippet;
import jdk.jshell.ImportSnippet;
import jdk.jshell.JShell;
import jdk.jshell.MethodSnippet;
import jdk.jshell.Snippet;
import jdk.jshell.VarSnippet;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-3-5
* @License Apache License Version 2.0
*/
public class JShellSnippet {
protected Snippet snippet;
protected String id, name, type, subType, status, source, value, some1, some2;
public JShellSnippet(JShell jShell, Snippet snippet) {
if (jShell == null || snippet == null) {
return;
}
this.snippet = snippet;
id = snippet.id();
type = snippet.kind().name();
subType = snippet.subKind().name();
switch (jShell.status(snippet)) {
case DROPPED:
status = message("Dropped");
break;
case NONEXISTENT:
status = message("Nonexistent");
break;
case OVERWRITTEN:
status = message("Overwritten");
break;
case RECOVERABLE_DEFINED:
case RECOVERABLE_NOT_DEFINED:
status = message("RecoverableUnresolved");
break;
case REJECTED:
status = message("Rejected");
break;
case VALID:
status = message("Valid");
break;
}
source = snippet.source();
if (snippet instanceof VarSnippet) {
makeVar(jShell, (VarSnippet) snippet);
} else if (snippet instanceof ExpressionSnippet) {
makeExpression((ExpressionSnippet) snippet);
} else if (snippet instanceof MethodSnippet) {
makeMethod((MethodSnippet) snippet);
} else if (snippet instanceof ImportSnippet) {
makeImport((ImportSnippet) snippet);
} else if (snippet instanceof ErroneousSnippet) {
makeError((ErroneousSnippet) snippet);
}
}
private void makeVar(JShell jShell, VarSnippet varSnippet) {
if (jShell == null || varSnippet == null) {
return;
}
name = varSnippet.name();
some1 = varSnippet.typeName();
value = jShell.varValue(varSnippet);
}
private void makeExpression(ExpressionSnippet expSnippet) {
if (expSnippet == null) {
return;
}
name = expSnippet.name();
some1 = expSnippet.typeName();
}
private void makeMethod(MethodSnippet methodSnippet) {
if (methodSnippet == null) {
return;
}
name = methodSnippet.name();
some1 = methodSnippet.parameterTypes();
some2 = methodSnippet.signature();
}
private void makeImport(ImportSnippet importSnippet) {
if (importSnippet == null) {
return;
}
name = importSnippet.name();
some1 = importSnippet.fullname();
some2 = importSnippet.isStatic() ? "Static" : "";
}
private void makeError(ErroneousSnippet errorSnippet) {
if (errorSnippet == null) {
return;
}
some1 = errorSnippet.probableKind().name();
}
/*
get/set
*/
public Snippet getSnippet() {
return snippet;
}
public void setSnippet(Snippet snippet) {
this.snippet = snippet;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubType() {
return subType;
}
public void setSubType(String subType) {
this.subType = subType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSome1() {
return some1;
}
public void setSome1(String some1) {
this.some1 = some1;
}
public String getSome2() {
return some2;
}
public void setSome2(String some2) {
this.some2 = some2;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/ImageItem.java | alpha/MyBox/src/main/java/mara/mybox/data/ImageItem.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import java.io.File;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javax.imageio.ImageIO;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.tools.FileNameTools;
/**
* @Author Mara
* @CreateDate 2020-1-5
* @License Apache License Version 2.0
*/
public class ImageItem {
protected String name, address, comments;
protected int index, width;
protected SimpleBooleanProperty selected = new SimpleBooleanProperty(false);
public ImageItem() {
init();
}
public ImageItem(String address) {
init();
this.address = address;
}
private void init() {
name = null;
address = null;
comments = null;
selected = new SimpleBooleanProperty(false);
}
public boolean isInternal() {
return address != null
&& (address.startsWith("img/") || address.startsWith("buttons/"));
}
public int getWidth() {
if (width > 0) {
return width;
}
if (name != null && name.startsWith("icon")) {
return 100;
}
return address != null && address.startsWith("buttons/") ? 100 : 500;
}
public boolean isColor() {
return address != null && address.startsWith("color:");
}
public boolean isFile() {
return address != null && new File(address).exists();
}
public Image readImage() {
Image image = null;
try {
if (address == null || isColor()) {
return null;
}
if (isInternal()) {
image = new Image(address);
} else if (isFile()) {
File file = new File(address);
if (file.exists()) {
BufferedImage bf = ImageIO.read(file);
image = SwingFXUtils.toFXImage(bf, null);
}
}
} catch (Exception e) {
}
if (image != null) {
width = (int) image.getWidth();
}
return image;
}
public Node makeNode(int size, boolean checkSize) {
try {
if (isColor()) {
Rectangle rect = new Rectangle();
rect.setFill(Color.web(address.substring(6)));
rect.setWidth(size);
rect.setHeight(size);
rect.setStyle("-fx-padding: 10 10 10 10;-fx-background-radius: 10;");
rect.setUserData(index);
return rect;
} else {
Image image = readImage();
if (image == null) {
return null;
}
int w = size;
if (checkSize && w > image.getWidth()) {
w = (int) image.getWidth();
}
ImageView view = new ImageView(image);
view.setPreserveRatio(false);
view.setFitWidth(w);
view.setFitHeight(w);
view.setUserData(index);
return view;
}
} catch (Exception e) {
return null;
}
}
public File getFile() {
try {
File file = null;
if (isInternal()) {
file = FxFileTools.getInternalFile("/" + address, "image",
name != null ? name : FileNameTools.name(address, "/"));
} else if (isFile()) {
file = new File(address);
}
if (file != null && file.exists()) {
return file;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
/*
static
*/
/*
get/set
*/
public String getAddress() {
return address;
}
public ImageItem setAddress(String address) {
this.address = address;
return this;
}
public String getComments() {
return comments;
}
public ImageItem setComments(String comments) {
this.comments = comments;
return this;
}
public boolean isSelected() {
return selected.get();
}
public SimpleBooleanProperty getSelected() {
return selected;
}
public ImageItem setSelected(SimpleBooleanProperty selected) {
this.selected = selected;
return this;
}
public ImageItem setSelected(boolean selected) {
this.selected.set(selected);
return this;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public ImageItem setName(String name) {
this.name = name;
return this;
}
public ImageItem 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/alpha/MyBox/src/main/java/mara/mybox/data/DownloadItem.java | alpha/MyBox/src/main/java/mara/mybox/data/DownloadItem.java | /*
* Apache License Version 2.0
*/
package mara.mybox.data;
import java.io.File;
import java.util.Date;
import mara.mybox.fxml.DownloadTask;
import mara.mybox.tools.FileTools;
/**
*
* @author mara
*/
public class DownloadItem {
protected String address;
protected File targetFile;
protected long totalSize, currentSize, startTime, endTime, cost;
protected String status, progress, speed;
protected DownloadTask task;
public static DownloadItem create() {
return new DownloadItem();
}
public String getAddress() {
return address;
}
public DownloadItem setAddress(String address) {
this.address = address;
return this;
}
public File getTargetFile() {
return targetFile;
}
public DownloadItem setTargetFile(File targetFile) {
this.targetFile = targetFile;
return this;
}
public long getTotalSize() {
return totalSize;
}
public DownloadItem setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public long getCurrentSize() {
return currentSize;
}
public DownloadItem setCurrentSize(long currentSize) {
this.currentSize = currentSize;
return this;
}
public String getStatus() {
return status;
}
public DownloadItem setStatus(String status) {
this.status = status;
return this;
}
public long getStartTime() {
return startTime;
}
public DownloadItem setStartTime(long startTime) {
this.startTime = startTime;
return this;
}
public String getProgress() {
if (totalSize == 0) {
return "0%";
} else {
int v = (int) (currentSize * 100 / totalSize);
v = Math.max(0, Math.min(100, v));
return v + "%";
}
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public long getCost() {
if (endTime > startTime) {
return endTime - startTime;
} else {
long v = new Date().getTime() - startTime;
return v > 0 ? v : 0;
}
}
public void setCost(long cost) {
this.cost = cost;
}
public String getSpeed() {
if (currentSize <= 0 || getCost() <= 0) {
return "0";
} else {
return FileTools.showFileSize(currentSize / getCost()) + "/s";
}
}
public DownloadTask getTask() {
return task;
}
public DownloadItem setTask(DownloadTask 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/alpha/MyBox/src/main/java/mara/mybox/data/ValueRange.java | alpha/MyBox/src/main/java/mara/mybox/data/ValueRange.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2022-11-22
* @License Apache License Version 2.0
*/
public class ValueRange {
protected Object start, end;
protected boolean includeStart, includeEnd;
public static enum SplitType {
Size, Number, List
}
public ValueRange() {
start = null;
end = null;
includeStart = false;
includeEnd = false;
}
@Override
public String toString() {
return (includeStart ? "[" : "(")
+ start + "," + end
+ (includeEnd ? "]" : ")");
}
/*
get/set
*/
public Object getStart() {
return start;
}
public ValueRange setStart(Object start) {
this.start = start;
return this;
}
public Object getEnd() {
return end;
}
public ValueRange setEnd(Object end) {
this.end = end;
return this;
}
public boolean isIncludeStart() {
return includeStart;
}
public ValueRange setIncludeStart(boolean includeStart) {
this.includeStart = includeStart;
return this;
}
public boolean isIncludeEnd() {
return includeEnd;
}
public ValueRange setIncludeEnd(boolean includeEnd) {
this.includeEnd = includeEnd;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePolylines.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePolylines.java | package mara.mybox.data;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.List;
import javafx.geometry.Point2D;
import javafx.scene.shape.Line;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @License Apache License Version 2.0
*/
public class DoublePolylines implements DoubleShape {
private List<List<DoublePoint>> lines;
public DoublePolylines() {
lines = new ArrayList<>();
}
@Override
public String name() {
return message("Polylines");
}
@Override
public Path2D.Double getShape() {
if (lines == null) {
return null;
}
Path2D.Double path = new Path2D.Double();
for (List<DoublePoint> line : lines) {
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());
}
}
return path;
}
public boolean addLine(List<DoublePoint> line) {
if (line == null) {
return false;
}
lines.add(line);
return true;
}
public boolean setLine(int index, List<DoublePoint> line) {
if (line == null || index < 0 || index >= lines.size()) {
return false;
}
lines.set(index, line);
return true;
}
public boolean removeLine(int index) {
if (lines == null || index < 0 || index >= lines.size()) {
return false;
}
lines.remove(index);
return true;
}
@Override
public boolean isValid() {
return lines != null;
}
@Override
public boolean isEmpty() {
return !isValid() || lines.isEmpty();
}
@Override
public DoublePolylines copy() {
DoublePolylines np = new DoublePolylines();
for (List<DoublePoint> line : lines) {
List<DoublePoint> newline = new ArrayList<>();
newline.addAll(line);
np.addLine(newline);
}
return np;
}
public List<Line> getLineList() {
List<Line> dlines = new ArrayList<>();
int lastx, lasty = -1, thisx, thisy;
for (List<DoublePoint> lineData : lines) {
if (lineData.size() == 1) {
DoublePoint linePoint = lineData.get(0);
thisx = (int) Math.round(linePoint.getX());
thisy = (int) Math.round(linePoint.getY());
Line line = new Line(thisx, thisy, thisx, thisy);
dlines.add(line);
} else {
lastx = Integer.MAX_VALUE;
for (DoublePoint linePoint : lineData) {
thisx = (int) Math.round(linePoint.getX());
thisy = (int) Math.round(linePoint.getY());
if (lastx != Integer.MAX_VALUE) {
Line line = new Line(lastx, lasty, thisx, thisy);
dlines.add(line);
}
lastx = thisx;
lasty = thisy;
}
}
}
return dlines;
}
public boolean contains(double x, double y) {
if (!isValid()) {
return false;
}
Point2D point = new Point2D(x, y);
for (Line line : getLineList()) {
if (line.contains(point)) {
return true;
}
}
return false;
}
public void clear() {
lines.clear();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
List<List<DoublePoint>> npoints = new ArrayList<>();
for (List<DoublePoint> line : lines) {
List<DoublePoint> newline = new ArrayList<>();
for (DoublePoint p : line) {
newline.add(new DoublePoint(p.getX() + offsetX, p.getY() + offsetY));
}
npoints.add(newline);
}
lines.clear();
lines.addAll(npoints);
return true;
}
public void translateLineRel(int index, double offsetX, double offsetY) {
if (index < 0 || index >= lines.size()) {
return;
}
List<DoublePoint> newline = new ArrayList<>();
List<DoublePoint> line = lines.get(index);
for (int i = 0; i < line.size(); i++) {
DoublePoint p = line.get(i);
newline.add(p.translate(offsetX, offsetY));
}
lines.set(index, newline);
}
@Override
public boolean scale(double scaleX, double scaleY) {
List<List<DoublePoint>> npoints = new ArrayList<>();
for (List<DoublePoint> line : lines) {
List<DoublePoint> newline = new ArrayList<>();
for (DoublePoint p : line) {
newline.add(p.scale(scaleX, scaleY));
}
npoints.add(newline);
}
lines.clear();
lines.addAll(npoints);
return true;
}
public void scale(int index, double scaleX, double scaleY) {
if (index < 0 || index >= lines.size()) {
return;
}
List<DoublePoint> newline = new ArrayList<>();
List<DoublePoint> line = lines.get(index);
for (int i = 0; i < line.size(); i++) {
DoublePoint p = line.get(i);
newline.add(p.scale(scaleX, scaleY));
}
lines.set(index, newline);
}
@Override
public String pathAbs() {
String path = "";
for (List<DoublePoint> line : lines) {
DoublePoint p = line.get(0);
path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
for (int i = 1; i < line.size(); i++) {
p = line.get(i);
path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
}
}
return path;
}
@Override
public String pathRel() {
String path = "";
double lastx = 0, lasty = 0;
for (List<DoublePoint> line : lines) {
DoublePoint p = line.get(0);
path += "M " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n";
lastx = p.getX();
lasty = p.getY();
for (int i = 1; i < line.size(); i++) {
p = line.get(i);
path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n";
lastx = p.getX();
lasty = p.getY();
}
}
return path;
}
@Override
public String elementAbs() {
String e = "";
int scale = UserConfig.imageScale();
for (List<DoublePoint> line : lines) {
e += "<polygon points=\""
+ DoublePoint.toText(line, scale, " ") + "\">\n";
}
return e;
}
@Override
public String elementRel() {
return elementAbs();
}
public int getLinesSize() {
return lines.size();
}
public List<List<DoublePoint>> getLines() {
return lines;
}
public List<Path2D.Double> getPaths() {
if (lines == null) {
return null;
}
List<Path2D.Double> paths = new ArrayList<>();
for (List<DoublePoint> line : lines) {
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());
}
paths.add(path);
}
return paths;
}
public void setLines(List<List<DoublePoint>> linePoints) {
this.lines = linePoints;
}
public boolean removeLastLine() {
if (lines.isEmpty()) {
return false;
}
lines.remove(lines.size() - 1);
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/GeographyCode.java | alpha/MyBox/src/main/java/mara/mybox/data/GeographyCode.java | package mara.mybox.data;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2020-1-20
* @License Apache License Version 2.0
*/
public class GeographyCode implements Cloneable {
protected double area;
protected long population;
protected AddressLevel level;
protected String name, fullName, chineseName, englishName, levelName,
code1, code2, code3, code4, code5, alias1, alias2, alias3, alias4, alias5,
continent, country, province, city, county, town, village,
building, poi, title, info, description;
protected double longitude, latitude, altitude, precision;
protected CoordinateSystem coordinateSystem;
protected int markSize;
public static CoordinateSystem defaultCoordinateSystem = CoordinateSystem.CGCS2000;
public static AddressLevel defaultAddressLevel = AddressLevel.Other;
public static enum AddressLevel {
Global, Continent, Country, Province, City, County,
Town, Village, Building, PointOfInterest, Other
}
public static enum CoordinateSystem {
CGCS2000, GCJ_02, WGS_84, BD_09, Mapbar, Other
}
public GeographyCode() {
area = -1;
population = -1;
level = defaultAddressLevel;
coordinateSystem = defaultCoordinateSystem;
longitude = latitude = -200;
altitude = precision = AppValues.InvalidDouble;
markSize = -1;
}
@Override
public Object clone() throws CloneNotSupportedException {
try {
GeographyCode newCode = (GeographyCode) super.clone();
newCode.setLevel(level);
newCode.setCoordinateSystem(coordinateSystem);
return newCode;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
custmized get/set
*/
public String getName() {
if (Languages.isChinese()) {
name = chineseName != null ? chineseName : englishName;
} else {
name = englishName != null ? englishName : chineseName;
}
if (name == null) {
return message(level.name());
}
return name;
}
public String getFullName() {
getName();
if (level == null || level.ordinal() <= 3) {
fullName = name;
} else {
if (Languages.isChinese()) {
if (country != null) {
fullName = country;
} else {
fullName = "";
}
if (province != null && !province.isBlank()) {
fullName = fullName.isBlank() ? province : fullName + "-" + province;
}
if (city != null && !city.isBlank()) {
fullName = fullName.isBlank() ? city : fullName + "-" + city;
}
if (county != null && !county.isBlank()) {
fullName = fullName.isBlank() ? county : fullName + "-" + county;
}
if (town != null && !town.isBlank()) {
fullName = fullName.isBlank() ? town : fullName + "-" + town;
}
if (village != null && !village.isBlank()) {
fullName = fullName.isBlank() ? village : fullName + "-" + village;
}
if (building != null && !building.isBlank()) {
fullName = fullName.isBlank() ? building : fullName + "-" + building;
}
if (name != null && !name.isBlank()) {
fullName = fullName.isBlank() ? name : fullName + "-" + name;
}
} else {
if (name != null) {
fullName = name;
} else {
fullName = "";
}
if (building != null && !building.isBlank()) {
fullName = fullName.isBlank() ? building : fullName + "," + building;
}
if (village != null && !village.isBlank()) {
fullName = fullName.isBlank() ? village : fullName + "," + village;
}
if (town != null && !town.isBlank()) {
fullName = fullName.isBlank() ? town : fullName + "," + town;
}
if (county != null && !county.isBlank()) {
fullName = fullName.isBlank() ? county : fullName + "," + county;
}
if (city != null && !city.isBlank()) {
fullName = fullName.isBlank() ? city : fullName + "," + city;
}
if (province != null && !province.isBlank()) {
fullName = fullName.isBlank() ? province : fullName + "," + province;
}
if (country != null && !country.isBlank()) {
fullName = fullName.isBlank() ? country : fullName + "," + country;
}
}
}
return fullName;
}
public AddressLevel getLevel() {
if (level == null) {
level = defaultAddressLevel;
}
return level;
}
public String getLevelName() {
levelName = message(getLevel().name());
return levelName;
}
public CoordinateSystem getCoordinateSystem() {
if (coordinateSystem == null) {
coordinateSystem = defaultCoordinateSystem;
}
return coordinateSystem;
}
public String getTitle() {
return title != null ? title : getName();
}
/*
get/set
*/
public String getChineseName() {
return chineseName;
}
public void setChineseName(String chineseName) {
this.chineseName = chineseName;
}
public String getEnglishName() {
return englishName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public String getCode1() {
return code1;
}
public void setCode1(String code1) {
this.code1 = code1;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2;
}
public String getCode3() {
return code3;
}
public void setCode3(String code3) {
this.code3 = code3;
}
public String getAlias1() {
return alias1;
}
public void setAlias1(String alias1) {
this.alias1 = alias1;
}
public String getAlias2() {
return alias2;
}
public void setAlias2(String alias2) {
this.alias2 = alias2;
}
public String getAlias3() {
return alias3;
}
public void setAlias3(String alias3) {
this.alias3 = alias3;
}
public double getLongitude() {
return longitude;
}
public GeographyCode setLongitude(double longitude) {
this.longitude = longitude;
return this;
}
public double getLatitude() {
return latitude;
}
public GeographyCode setLatitude(double latitude) {
this.latitude = latitude;
return this;
}
public String getContinent() {
return continent;
}
public String getCountry() {
return country;
}
public String getProvince() {
return province;
}
public String getCity() {
return city;
}
public String getCounty() {
return county;
}
public String getTown() {
return town;
}
public String getVillage() {
return village;
}
public String getBuilding() {
return building;
}
public String getPoi() {
return poi;
}
public void setCountry(String country) {
this.country = country;
}
public void setProvince(String province) {
this.province = province;
}
public void setCity(String city) {
this.city = city;
}
public void setCounty(String county) {
this.county = county;
}
public void setVillage(String village) {
this.village = village;
}
public void setTown(String town) {
this.town = town;
}
public void setBuilding(String building) {
this.building = building;
}
public String getCode4() {
return code4;
}
public void setCode4(String code4) {
this.code4 = code4;
}
public String getCode5() {
return code5;
}
public void setCode5(String code5) {
this.code5 = code5;
}
public String getAlias4() {
return alias4;
}
public void setAlias4(String alias4) {
this.alias4 = alias4;
}
public String getAlias5() {
return alias5;
}
public void setAlias5(String alias5) {
this.alias5 = alias5;
}
public void setPoi(String poi) {
this.poi = poi;
}
public void setName(String name) {
this.name = name;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setContinent(String continent) {
this.continent = continent;
}
public void setLevel(AddressLevel level) {
this.level = level;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
public void setLevelName(String levelName) {
this.levelName = levelName;
}
public double getAltitude() {
return altitude;
}
public GeographyCode setAltitude(double altitude) {
this.altitude = altitude;
return this;
}
public double getPrecision() {
return precision;
}
public void setPrecision(double precision) {
this.precision = precision;
}
public GeographyCode setCoordinateSystem(CoordinateSystem coordinateSystem) {
this.coordinateSystem = coordinateSystem;
return this;
}
public String getInfo() {
return info;
}
public GeographyCode setInfo(String info) {
this.info = info;
return this;
}
public GeographyCode setTitle(String label) {
this.title = label;
return this;
}
public int getMarkSize() {
return markSize;
}
public GeographyCode setMarkSize(int markSize) {
this.markSize = markSize;
return this;
}
public String getDescription() {
return description;
}
public GeographyCode setDescription(String description) {
this.description = description;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/TesseractOptions.java | alpha/MyBox/src/main/java/mara/mybox/data/TesseractOptions.java | package mara.mybox.data;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
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.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.tools.FileCopyTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.SystemTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.AppVariables.MyboxDataPath;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
import net.sourceforge.tess4j.ITessAPI;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.Word;
/**
* @Author Mara
* @CreateDate 2025-6-30
* @License Apache License Version 2.0
*/
public class TesseractOptions {
// 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;
protected File tesseract, dataPath;
protected String os, selectedLanguages, regionLevel, wordLevel, more,
texts, html;
protected List<Rectangle> rectangles;
protected List<Word> words;
protected int psm, tesseractVersion;
protected boolean embed, setFormats, setLevels, isVersion3, outHtml, outPdf;
protected File configFile;
protected Tesseract tessInstance;
public TesseractOptions() {
initValues();
}
final public void initValues() {
os = SystemTools.os();
readValues();
configFile = null;
tessInstance = null;
clearResults();
}
public void readValues() {
try (Connection conn = DerbyBase.getConnection()) {
tesseract = new File(UserConfig.getString(conn, "TesseractPath",
"win".equals(os) ? "D:\\Programs\\Tesseract-OCR\\tesseract.exe" : "/bin/tesseract"));
dataPath = new File(UserConfig.getString(conn, "TesseractData",
"win".equals(os) ? "D:\\Programs\\Tesseract-OCR\\tessdata" : "/usr/local/share/tessdata/"));
embed = UserConfig.getBoolean(conn, "TesseracEmbed", true);
selectedLanguages = UserConfig.getString(conn, "ImageOCRLanguages", null);
psm = UserConfig.getInt(conn, "TesseractPSM", 6);
regionLevel = UserConfig.getString(conn, "TesseractRegionLevel", message("Symbol"));
wordLevel = UserConfig.getString(conn, "TesseractWordLevel", message("Symbol"));
outHtml = UserConfig.getBoolean(conn, "TesseractOutHtml", false);
outPdf = UserConfig.getBoolean(conn, "TesseractOutPdf", false);
more = UserConfig.getString(conn, "TesseractMore", null);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void writeValues() {
try (Connection conn = DerbyBase.getConnection()) {
UserConfig.setString(conn, "TesseractPath", tesseract.getAbsolutePath());
UserConfig.setString(conn, "TesseractData", dataPath.getAbsolutePath());
UserConfig.setBoolean(conn, "ImageOCREmbed", embed);
UserConfig.setString(conn, "ImageOCRLanguages", selectedLanguages);
UserConfig.setInt(conn, "TesseractPSM", psm);
UserConfig.setString(conn, "TesseractRegionLevel", regionLevel);
UserConfig.setString(conn, "TesseractWordLevel", wordLevel);
UserConfig.setBoolean(conn, "TesseractOutHtml", outHtml);
UserConfig.setBoolean(conn, "TesseractOutPdf", outPdf);
UserConfig.setString(conn, "TesseractMore", more);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void clearResults() {
texts = null;
html = null;
rectangles = null;
words = null;
}
public boolean isWin() {
return "win".equals(os);
}
public int level(String name) {
if (name == null || name.isBlank()) {
return -1;
} else if (Languages.matchIgnoreCase("Block", name)) {
return ITessAPI.TessPageIteratorLevel.RIL_BLOCK;
} else if (Languages.matchIgnoreCase("Paragraph", name)) {
return ITessAPI.TessPageIteratorLevel.RIL_PARA;
} else if (Languages.matchIgnoreCase("Textline", name)) {
return ITessAPI.TessPageIteratorLevel.RIL_TEXTLINE;
} else if (Languages.matchIgnoreCase("Word", name)) {
return ITessAPI.TessPageIteratorLevel.RIL_WORD;
} else if (Languages.matchIgnoreCase("Symbol", name)) {
return ITessAPI.TessPageIteratorLevel.RIL_SYMBOL;
} else {
return -1;
}
}
public int wordLevel() {
return level(wordLevel);
}
public int regionLevel() {
return level(regionLevel);
}
public Map<String, String> moreOptions() {
if (more == null || more.isBlank()) {
return null;
}
Map<String, String> p = new HashMap<>();
String[] lines = more.split("\n");
for (String line : lines) {
String[] fields = line.split("\t");
if (fields.length < 2) {
continue;
}
p.put(fields[0].trim(), fields[1].trim());
}
return p;
}
// Make sure supported language files are under defined data path
public boolean initDataFiles() {
try {
if (dataPath == null || !dataPath.exists() || !dataPath.isDirectory()) {
dataPath = new File(MyboxDataPath + File.separator + "tessdata");
}
dataPath.mkdirs();
File chi_sim = new File(dataPath.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(dataPath.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(dataPath.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(dataPath.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(dataPath.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(dataPath.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(dataPath.getAbsolutePath() + File.separator + "osd.traineddata");
if (!osd.exists()) {
File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/tessdata/osd.traineddata");
FileCopyTools.copyFile(tmp, osd);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public List<String> namesList() {
return namesList(tesseractVersion > 3);
}
public List<String> namesList(boolean copyFiles) {
List<String> data = new ArrayList<>();
try {
if (copyFiles) {
initDataFiles();
}
data.addAll(names());
List<String> codes = codes();
File[] files = 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 Tesseract makeInstance() {
try {
tessInstance = new Tesseract();
// https://stackoverflow.com/questions/58286373/tess4j-pdf-to-tiff-to-tesseract-warning-invalid-resolution-0-dpi-using-70/58296472#58296472
tessInstance.setVariable("user_defined_dpi", "96");
tessInstance.setVariable("debug_file", "/dev/null");
tessInstance.setPageSegMode(psm);
Map<String, String> moreOptions = moreOptions();
if (moreOptions != null && !moreOptions.isEmpty()) {
for (String key : moreOptions.keySet()) {
tessInstance.setVariable(key, moreOptions.get(key));
}
}
tessInstance.setDatapath(dataPath.getAbsolutePath());
if (selectedLanguages != null) {
tessInstance.setLanguage(selectedLanguages);
}
return tessInstance;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public int tesseractVersion() {
try {
if (tesseract == null || !tesseract.exists()) {
return -1;
}
List<String> parameters = new ArrayList<>();
parameters.addAll(Arrays.asList(tesseract.getAbsolutePath(), "--version"));
ProcessBuilder pb = new ProcessBuilder(parameters).redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) {
String line;
while ((line = inReader.readLine()) != null) {
if (line.contains("tesseract v4.") || line.contains("tesseract 4.")) {
return 4;
}
if (line.contains("tesseract v5.") || line.contains("tesseract 5.")) {
return 5;
}
if (line.contains("tesseract v3.") || line.contains("tesseract 3.")) {
return 3;
}
if (line.contains("tesseract v2.") || line.contains("tesseract 2.")) {
return 2;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
process.waitFor();
} catch (Exception e) {
MyBoxLog.debug(e);
}
return -1;
}
public void makeConfigFile() {
try {
configFile = FileTmpTools.getTempFile();
String s = "tessedit_create_txt 1\n";
if (setFormats) {
if (outHtml) {
s += "tessedit_create_hocr 1\n";
}
if (outPdf) {
s += "tessedit_create_pdf 1\n";
}
}
Map<String, String> moreOptions = moreOptions();
if (moreOptions != null) {
for (String key : moreOptions.keySet()) {
s += key + "\t" + moreOptions.get(key) + "\n";
}
}
TextFileTools.writeFile(configFile, s, Charset.forName("utf-8"));
} catch (Exception e) {
MyBoxLog.error(e);
configFile = null;
}
}
public boolean imageOCR(FxTask currentTask, Image image, boolean allData) {
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
bufferedImage = AlphaTools.removeAlpha(currentTask, bufferedImage);
return bufferedImageOCR(currentTask, bufferedImage, allData);
}
public boolean bufferedImageOCR(FxTask currentTask, BufferedImage bufferedImage, boolean allData) {
try {
clearResults();
if (bufferedImage == null || (currentTask != null && !currentTask.isWorking())) {
return false;
}
if (tessInstance == null) {
tessInstance = makeInstance();
}
List<ITesseract.RenderedFormat> formats = new ArrayList<>();
formats.add(ITesseract.RenderedFormat.TEXT);
if (allData) {
formats.add(ITesseract.RenderedFormat.HOCR);
}
File tmpFile = File.createTempFile("MyboxOCR", "");
String tmp = tmpFile.getAbsolutePath();
FileDeleteTools.delete(tmpFile);
tessInstance.createDocumentsWithResults(bufferedImage, tmp,
tmp, formats, ITessAPI.TessPageIteratorLevel.RIL_SYMBOL);
File txtFile = new File(tmp + ".txt");
texts = TextFileTools.readTexts(currentTask, txtFile);
FileDeleteTools.delete(txtFile);
if (texts == null || (currentTask != null && !currentTask.isWorking())) {
return false;
}
if (allData) {
File htmlFile = new File(tmp + ".hocr");
html = TextFileTools.readTexts(currentTask, htmlFile);
FileDeleteTools.delete(htmlFile);
if (html == null || (currentTask != null && !currentTask.isWorking())) {
return false;
}
int wl = wordLevel();
if (wl >= 0) {
words = tessInstance.getWords(bufferedImage, wl);
}
int rl = regionLevel();
if (rl >= 0) {
rectangles = tessInstance.getSegmentedRegions(bufferedImage, rl);
}
}
return texts != null;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public Process process(File file, String prefix) {
try {
if (file == null || configFile == null || dataPath == null) {
return null;
}
List<String> parameters = new ArrayList<>();
parameters.addAll(Arrays.asList(
tesseract.getAbsolutePath(),
file.getAbsolutePath(),
prefix,
"--tessdata-dir", dataPath.getAbsolutePath(),
tesseractVersion > 3 ? "--psm" : "-psm", psm + ""
));
if (selectedLanguages != null) {
parameters.addAll(Arrays.asList("-l", selectedLanguages));
}
parameters.add(configFile.getAbsolutePath());
ProcessBuilder pb = new ProcessBuilder(parameters).redirectErrorStream(true);
return pb.start();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
static
*/
// 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;
}
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);
}
/*
get/set
*/
public boolean isEmbed() {
return embed;
}
public void setEmbed(boolean embed) {
this.embed = embed;
}
public File getTesseract() {
return tesseract;
}
public void setTesseract(File tesseract) {
this.tesseract = tesseract;
}
public File getDataPath() {
return dataPath;
}
public void setDataPath(File dataPath) {
this.dataPath = dataPath;
}
public String getSelectedLanguages() {
return selectedLanguages;
}
public void setSelectedLanguages(String selectedLanguages) {
this.selectedLanguages = selectedLanguages;
}
public String getTexts() {
return texts;
}
public TesseractOptions setTexts(String texts) {
this.texts = texts;
return this;
}
public String getHtml() {
return html;
}
public TesseractOptions setHtml(String html) {
this.html = html;
return this;
}
public List<Rectangle> getRectangles() {
return rectangles;
}
public TesseractOptions setRectangles(List<Rectangle> rectangles) {
this.rectangles = rectangles;
return this;
}
public List<Word> getWords() {
return words;
}
public TesseractOptions setWords(List<Word> words) {
this.words = words;
return this;
}
public int getPsm() {
return psm;
}
public TesseractOptions setPsm(int psm) {
this.psm = psm;
return this;
}
public String getRegionLevel() {
return regionLevel;
}
public TesseractOptions setRegionLevel(String regionLevel) {
this.regionLevel = regionLevel;
return this;
}
public String getWordLevel() {
return wordLevel;
}
public TesseractOptions setWordLevel(String wordLevel) {
this.wordLevel = wordLevel;
return this;
}
public int getTesseractVersion() {
return tesseractVersion;
}
public TesseractOptions setTesseractVersion(int tesseractVersion) {
this.tesseractVersion = tesseractVersion;
return this;
}
public boolean isSetFormats() {
return setFormats;
}
public TesseractOptions setSetFormats(boolean setFormats) {
this.setFormats = setFormats;
return this;
}
public boolean isSetLevels() {
return setLevels;
}
public TesseractOptions setSetLevels(boolean setLevels) {
this.setLevels = setLevels;
return this;
}
public boolean isIsVersion3() {
return isVersion3;
}
public TesseractOptions setIsVersion3(boolean isVersion3) {
this.isVersion3 = isVersion3;
return this;
}
public File getConfigFile() {
return configFile;
}
public TesseractOptions setConfigFile(File configFile) {
this.configFile = configFile;
return this;
}
public String getOs() {
return os;
}
public TesseractOptions setOs(String os) {
this.os = os;
return this;
}
public boolean isOutHtml() {
return outHtml;
}
public TesseractOptions setOutHtml(boolean outHtml) {
this.outHtml = outHtml;
return this;
}
public boolean isOutPdf() {
return outPdf;
}
public TesseractOptions setOutPdf(boolean outPdf) {
this.outPdf = outPdf;
return this;
}
public String getMore() {
return more;
}
public TesseractOptions setMore(String more) {
this.more = more;
return this;
}
public Tesseract getTessInstance() {
return tessInstance;
}
public void setTessInstance(Tesseract tessInstance) {
this.tessInstance = tessInstance;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/SetValue.java | alpha/MyBox/src/main/java/mara/mybox/data/SetValue.java | package mara.mybox.data;
import java.util.List;
import java.util.Random;
import mara.mybox.data2d.Data2D;
import static mara.mybox.db.data.ColumnDefinition.DefaultInvalidAs;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Empty;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Null;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Skip;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Use;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Zero;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2022-8-13
* @License Apache License Version 2.0
*/
public class SetValue {
public ValueType type;
public String parameter, error;
public int start, digit, scale;
public boolean fillZero, aotoDigit, valueInvalid;
public InvalidAs invalidAs;
final public static ValueType DefaultValueType = ValueType.Zero;
public static enum ValueType {
Value, Zero, One, Empty, Null, Random, RandomNonNegative,
Scale, Prefix, Suffix,
NumberSuffix, NumberPrefix, NumberReplace, NumberSuffixString, NumberPrefixString,
Expression, GaussianDistribution, Identify, UpperTriangle, LowerTriangle
}
public SetValue() {
init();
}
public final void init() {
type = DefaultValueType;
parameter = null;
start = 0;
digit = 0;
scale = 5;
fillZero = true;
aotoDigit = true;
invalidAs = DefaultInvalidAs;
}
public int countFinalDigit(long dataSize) {
int finalDigit = digit;
if (isFillZero()) {
if (isAotoDigit()) {
finalDigit = (dataSize + "").length();
}
} else {
finalDigit = 0;
}
return finalDigit;
}
public String scale(String value) {
double d = DoubleTools.toDouble(value, invalidAs);
if (DoubleTools.invalidDouble(d)) {
if (null == invalidAs) {
return value;
} else {
switch (invalidAs) {
case Zero:
return "0";
case Empty:
return "";
case Null:
return null;
case Skip:
return null;
case Use:
return value;
default:
return value;
}
}
} else {
return DoubleTools.scaleString(d, scale);
}
}
public String dummyValue(Data2D data2D, Data2DColumn column) {
return makeValue(data2D, column, column.dummyValue(), data2D.dummyRow(),
1, start, countFinalDigit(data2D.getRowsNumber()), new Random());
}
public String makeValue(Data2D data2D, Data2DColumn column,
String currentValue, List<String> dataRow, long rowIndex,
int dataIndex, int ddigit, Random random) {
try {
error = null;
valueInvalid = false;
switch (type) {
case Zero:
return "0";
case One:
return "1";
case Empty:
return "";
case Null:
return null;
case Random:
return data2D.random(random, column, false);
case RandomNonNegative:
return data2D.random(random, column, true);
case Scale:
return scale(currentValue);
case Prefix:
return currentValue == null ? parameter : (parameter + currentValue);
case Suffix:
return currentValue == null ? parameter : (currentValue + parameter);
case NumberSuffix:
String suffix = StringTools.fillLeftZero(dataIndex, ddigit);
return currentValue == null ? suffix : (currentValue + suffix);
case NumberPrefix:
String prefix = StringTools.fillLeftZero(dataIndex, ddigit);
return currentValue == null ? prefix : (prefix + currentValue);
case NumberReplace:
return StringTools.fillLeftZero(dataIndex, ddigit);
case NumberSuffixString:
String ssuffix = StringTools.fillLeftZero(dataIndex, ddigit);
return parameter == null ? ssuffix : (parameter + ssuffix);
case NumberPrefixString:
String sprefix = StringTools.fillLeftZero(dataIndex, ddigit);
return parameter == null ? sprefix : (sprefix + parameter);
case Expression:
if (data2D.calculateDataRowExpression(parameter, dataRow, rowIndex)) {
return data2D.expressionResult();
} else {
valueInvalid = true;
error = data2D.expressionError();
return currentValue;
}
case Value:
return parameter;
}
valueInvalid = true;
error = "InvalidData";
return currentValue;
} catch (Exception e) {
error = e.toString();
return currentValue;
}
}
public String majorParameter() {
try {
switch (type) {
case Scale:
return scale + "";
case Suffix:
case Prefix:
case NumberSuffixString:
case NumberPrefixString:
case Expression:
case Value:
return parameter;
case NumberSuffix:
case NumberPrefix:
return start + "";
}
} catch (Exception e) {
}
return null;
}
/*
set
*/
public SetValue setType(ValueType type) {
this.type = type;
return this;
}
public SetValue setParameter(String value) {
this.parameter = value;
return this;
}
public SetValue setStart(int start) {
this.start = start;
return this;
}
public SetValue setDigit(int digit) {
this.digit = digit;
return this;
}
public SetValue setFillZero(boolean fillZero) {
this.fillZero = fillZero;
return this;
}
public SetValue setAotoDigit(boolean aotoDigit) {
this.aotoDigit = aotoDigit;
return this;
}
public SetValue setScale(int scale) {
this.scale = scale;
return this;
}
public SetValue setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
return this;
}
public SetValue setError(String error) {
this.error = error;
return this;
}
/*
get
*/
public ValueType getType() {
return type;
}
public String getParameter() {
return parameter;
}
public int getStart() {
return start;
}
public int getDigit() {
return digit;
}
public boolean isFillZero() {
return fillZero;
}
public boolean isAotoDigit() {
return aotoDigit;
}
public int getScale() {
return scale;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public String getError() {
return error;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleCubic.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleCubic.java | package mara.mybox.data;
import java.awt.geom.CubicCurve2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-31
* @License Apache License Version 2.0
*/
public class DoubleCubic implements DoubleShape {
private double startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY;
public DoubleCubic() {
}
public DoubleCubic(double startX, double startY,
double control1X, double control1Y,
double control2X, double control2Y,
double endX, double endY) {
this.startX = startX;
this.startY = startY;
this.controlX1 = control1X;
this.controlY1 = control1Y;
this.controlX2 = control2X;
this.controlY2 = control2Y;
this.endX = endX;
this.endY = endY;
}
@Override
public String name() {
return message("CubicCurve");
}
@Override
public CubicCurve2D.Double getShape() {
return new CubicCurve2D.Double(startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
}
@Override
public DoubleCubic copy() {
return new DoubleCubic(startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
startX += offsetX;
startY += offsetY;
controlX1 += offsetX;
controlY1 += offsetY;
controlX2 += offsetX;
controlY2 += offsetY;
endX += offsetX;
endY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
startX *= scaleX;
startY *= scaleY;
controlX1 *= scaleX;
controlY1 *= scaleY;
controlX2 *= scaleX;
controlY2 *= scaleY;
endX *= scaleX;
endY *= scaleY;
return true;
}
@Override
public String pathAbs() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "C " + imageScale(controlX1) + "," + imageScale(controlY1) + " "
+ imageScale(controlX2) + "," + imageScale(controlY2) + " "
+ imageScale(endX) + "," + imageScale(endY) + " \n";
}
@Override
public String pathRel() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "c " + imageScale(controlX1 - startX) + "," + imageScale(controlY1 - startY) + " "
+ imageScale(controlX2 - startX) + "," + imageScale(controlY2 - startY) + " "
+ imageScale(endX - startX) + "," + imageScale(endY - startY);
}
@Override
public String elementAbs() {
return "<path d=\"\n" + pathAbs() + "\n\"> ";
}
@Override
public String elementRel() {
return "<path d=\"\n" + pathRel() + "\n\"> ";
}
public double getStartX() {
return startX;
}
public void setStartX(double startX) {
this.startX = startX;
}
public double getStartY() {
return startY;
}
public void setStartY(double startY) {
this.startY = startY;
}
public double getEndX() {
return endX;
}
public void setEndX(double endX) {
this.endX = endX;
}
public double getEndY() {
return endY;
}
public void setEndY(double endY) {
this.endY = endY;
}
public double getControlX1() {
return controlX1;
}
public void setControlX1(double controlX1) {
this.controlX1 = controlX1;
}
public double getControlY1() {
return controlY1;
}
public void setControlY1(double controlY1) {
this.controlY1 = controlY1;
}
public double getControlX2() {
return controlX2;
}
public void setControlX2(double controlX2) {
this.controlX2 = controlX2;
}
public double getControlY2() {
return controlY2;
}
public void setControlY2(double controlY2) {
this.controlY2 = controlY2;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceString.java | alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceString.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.scene.control.IndexRange;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2020-11-5
* @License Apache License Version 2.0
*/
public class FindReplaceString {
protected Operation operation;
protected boolean isRegex, caseInsensitive, multiline, dotAll, appendTail, wrap;
protected String inputString, findString, replaceString, outputString;
protected int anchor, count, lastStart, lastEnd, lastReplacedLength, unit;
protected IndexRange stringRange; // location in string
protected String lastMatch, error;
protected List<FindReplaceMatch> matches;
public enum Operation {
ReplaceAll, ReplaceFirst, FindNext, FindPrevious, Count, FindAll
}
public FindReplaceString() {
isRegex = caseInsensitive = false;
multiline = wrap = true;
unit = 1;
}
public FindReplaceString reset() {
count = 0;
stringRange = null;
lastMatch = null;
outputString = inputString;
error = null;
lastStart = lastEnd = -1;
matches = operation == Operation.FindAll ? new ArrayList<>() : null;
return this;
}
public void initMatches() {
matches = operation == Operation.FindAll ? new ArrayList<>() : null;
}
public boolean handleString(FxTask currentTask) {
reset();
if (operation == null) {
return false;
}
if (inputString == null || inputString.isEmpty()) {
if (findString == null || findString.isEmpty()) {
if (operation == Operation.ReplaceAll || operation == Operation.ReplaceFirst) {
lastReplacedLength = 0;
outputString = replaceString == null ? "" : replaceString;
return true;
}
return false;
}
return false;
}
int start, end = inputString.length();
switch (operation) {
case FindNext:
case ReplaceFirst:
if (anchor >= 0 && anchor <= inputString.length() - 1) {
start = anchor;
} else if (!wrap) {
return true;
} else {
start = 0;
}
break;
case FindPrevious:
start = 0;
if (anchor > 0 && anchor <= inputString.length()) {
end = anchor;
} else if (!wrap) {
return true;
}
break;
default:
start = 0;
break;
}
handleString(currentTask, start, end);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (lastMatch != null || !wrap) {
return true;
}
// MyBoxLog.debug(operation + " " + wrap);
switch (operation) {
case FindNext:
case ReplaceFirst:
if (start <= 0) {
return true;
}
if (isRegex) {
end = inputString.length();
start = 0;
} else {
end = start + findString.length();
start = 0;
}
return handleString(currentTask, start, end);
case FindPrevious:
if (end > inputString.length()) {
return true;
}
if (isRegex) {
end = inputString.length();
start = unit;
} else {
start = Math.max(unit, end - findString.length() + unit);
end = inputString.length();
}
handleString(currentTask, start, end);
return currentTask == null || currentTask.isWorking();
default:
return true;
}
}
public boolean handleString(FxTask currentTask, int start, int end) {
try {
// MyBoxLog.debug(operation + " start:" + start + " end:" + end + " findString:>>" + findString + "<< unit:" + unit);
// MyBoxLog.debug("findString.length():" + findString.length());
// MyBoxLog.debug("replaceString:>>" + replaceString + "<<");
// MyBoxLog.debug("\n------\n" + inputString + "\n-----");
reset();
int mode = (isRegex ? 0x00 : Pattern.LITERAL)
| (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00)
| (dotAll ? Pattern.DOTALL : 0x00)
| (multiline ? Pattern.MULTILINE : 0x00);
Pattern pattern = Pattern.compile(findString, mode);
Matcher matcher = pattern.matcher(inputString);
int finalEnd = Math.min(inputString.length(), end);
matcher.region(Math.max(0, start), finalEnd);
StringBuffer s = new StringBuffer();
String finalReplace = replaceString == null ? "" : replaceString;
if (!finalReplace.isBlank()) {
finalReplace = Matcher.quoteReplacement(finalReplace);
}
OUTER:
while (matcher.find()) {
count++;
lastMatch = matcher.group();
lastStart = matcher.start();
lastEnd = matcher.end();
if (null == operation) {
if (matcher.start() >= finalEnd) {
break OUTER;
}
matcher.region(lastStart + unit, finalEnd);
} else {
// MyBoxLog.debug(count + " " + matcher.start() + " " + matcher.end() + " " + lastMatch);
// MyBoxLog.debug(inputString.substring(0, matcher.start()) + "\n----------------");
switch (operation) {
case FindNext:
break OUTER;
case ReplaceFirst:
matcher.appendReplacement(s, finalReplace);
break OUTER;
case ReplaceAll:
matcher.appendReplacement(s, finalReplace);
// MyBoxLog.debug("\n---" + count + "---\n" + s.toString() + "\n-----");
break;
case FindAll:
FindReplaceMatch m = new FindReplaceMatch()
.setStart(lastStart).setEnd(lastEnd)
.setMatchedPrefix(lastMatch);
matches.add(m);
default:
int newStart = lastStart + unit;
if (newStart >= finalEnd) {
break;
}
matcher.region(newStart, finalEnd);
}
}
}
// MyBoxLog.debug("count:" + count);
if (lastMatch != null) {
stringRange = new IndexRange(lastStart, lastEnd);
if (operation == Operation.ReplaceAll || operation == Operation.ReplaceFirst) {
String replacedPart = s.toString();
lastReplacedLength = replacedPart.length();
// MyBoxLog.debug("lastReplacedLength:" + lastReplacedLength);
matcher.appendTail(s);
outputString = s.toString();
// MyBoxLog.debug("\n---outputString---\n" + outputString + "\n-----");
// MyBoxLog.debug("inputString:" + inputString.length() + " outputString:" + outputString.length());
}
// MyBoxLog.debug(operation + " stringRange:" + stringRange.getStart() + " " + stringRange.getEnd() + " len:" + stringRange.getLength()
// + " findString:>>" + findString + "<< lastMatch:>>" + lastMatch + "<<");
} else {
outputString = inputString + "";
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
error = e.toString();
return false;
}
}
public String replace(FxTask currentTask, String string, String find, String replace) {
setInputString(string).setFindString(find)
.setReplaceString(replace == null ? "" : replace)
.setAnchor(0)
.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return message("Canceled");
}
return outputString;
}
/*
static methods
*/
public static FindReplaceString create() {
return new FindReplaceString();
}
public static FindReplaceString finder(boolean isRegex, boolean isCaseInsensitive) {
return create().setOperation(FindReplaceString.Operation.FindNext)
.setAnchor(0).setIsRegex(isRegex).setCaseInsensitive(isCaseInsensitive).setMultiline(true);
}
public static FindReplaceString counter(boolean isRegex, boolean isCaseInsensitive) {
return create().setOperation(FindReplaceString.Operation.Count)
.setAnchor(0).setIsRegex(isRegex).setCaseInsensitive(isCaseInsensitive).setMultiline(true);
}
public static int count(FxTask currentTask, String string, String find) {
return count(currentTask, string, find, 0, false, false, true);
}
public static int count(FxTask currentTask, String string, String find, int from,
boolean isRegex, boolean caseInsensitive, boolean multiline) {
FindReplaceString stringFind = create()
.setOperation(Operation.Count)
.setInputString(string).setFindString(find).setAnchor(from)
.setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline);
stringFind.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return -1;
}
return stringFind.getCount();
}
public static IndexRange next(FxTask currentTask, String string, String find, int from,
boolean isRegex, boolean caseInsensitive, boolean multiline) {
FindReplaceString stringFind = create()
.setOperation(Operation.FindNext)
.setInputString(string).setFindString(find).setAnchor(from)
.setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline);
stringFind.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
return stringFind.getStringRange();
}
public static IndexRange previous(FxTask currentTask, String string, String find, int from,
boolean isRegex, boolean caseInsensitive, boolean multiline) {
FindReplaceString stringFind = create()
.setOperation(Operation.FindPrevious)
.setInputString(string).setFindString(find).setAnchor(from)
.setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline);
stringFind.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
return stringFind.getStringRange();
}
public static String replaceAll(FxTask currentTask, String string, String find, String replace) {
return replaceAll(currentTask, string, find, replace, 0, false, false, true);
}
public static String replaceAll(FxTask currentTask, String string, String find, String replace, int from,
boolean isRegex, boolean caseInsensitive, boolean multiline) {
FindReplaceString stringFind = create()
.setOperation(Operation.ReplaceAll)
.setInputString(string).setFindString(find).setReplaceString(replace).setAnchor(from)
.setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline);
stringFind.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
return stringFind.getOutputString();
}
public static String replaceAll(FxTask currentTask, FindReplaceString findReplace, String string, String find, String replace) {
findReplace.setInputString(string).setFindString(find).setReplaceString(replace)
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
return findReplace.getOutputString();
}
public static String replaceFirst(FxTask currentTask, String string, String find, String replace) {
return replaceFirst(currentTask, string, find, replace, 0, false, false, true);
}
public static String replaceFirst(FxTask currentTask, String string, String find, String replace, int from,
boolean isRegex, boolean caseInsensitive, boolean multiline) {
FindReplaceString stringFind = create()
.setOperation(Operation.ReplaceFirst)
.setInputString(string).setFindString(find).setReplaceString(replace).setAnchor(from)
.setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline);
stringFind.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
return stringFind.getOutputString();
}
/*
get/set
*/
public boolean isIsRegex() {
return isRegex;
}
public FindReplaceString setIsRegex(boolean isRegex) {
this.isRegex = isRegex;
return this;
}
public boolean isCaseInsensitive() {
return caseInsensitive;
}
public FindReplaceString setCaseInsensitive(boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive;
return this;
}
public boolean isMultiline() {
return multiline;
}
public FindReplaceString setMultiline(boolean multiline) {
this.multiline = multiline;
return this;
}
public String getInputString() {
return inputString;
}
public boolean isDotAll() {
return dotAll;
}
public FindReplaceString setDotAll(boolean dotAll) {
this.dotAll = dotAll;
return this;
}
public int getLastEnd() {
return lastEnd;
}
public void setLastEnd(int lastEnd) {
this.lastEnd = lastEnd;
}
public FindReplaceString setInputString(String inputString) {
this.inputString = inputString;
return this;
}
public String getFindString() {
return findString;
}
public FindReplaceString setFindString(String findString) {
this.findString = findString;
return this;
}
public String getReplaceString() {
return replaceString;
}
public FindReplaceString setReplaceString(String replaceString) {
this.replaceString = replaceString;
return this;
}
public String getOutputString() {
return outputString;
}
public FindReplaceString setOuputString(String outputString) {
this.outputString = outputString;
return this;
}
public int getCount() {
return count;
}
public FindReplaceString setCount(int count) {
this.count = count;
return this;
}
public IndexRange getStringRange() {
return stringRange;
}
public FindReplaceString setStringRange(IndexRange lastRange) {
this.stringRange = lastRange;
return this;
}
public String getLastMatch() {
return lastMatch;
}
public FindReplaceString setLastMatch(String lastMatch) {
this.lastMatch = lastMatch;
return this;
}
public FindReplaceString setAnchor(int anchor) {
this.anchor = anchor;
return this;
}
public int getAnchor() {
return anchor;
}
public Operation getOperation() {
return operation;
}
public FindReplaceString setOperation(Operation operation) {
this.operation = operation;
return this;
}
public boolean isAppendTail() {
return appendTail;
}
public FindReplaceString setAppendTail(boolean appendTail) {
this.appendTail = appendTail;
return this;
}
public int getLastStart() {
return lastStart;
}
public FindReplaceString setLastStart(int lastStart) {
this.lastStart = lastStart;
return this;
}
public int getLastReplacedLength() {
return lastReplacedLength;
}
public FindReplaceString setLastReplacedLength(int lastReplacedLength) {
this.lastReplacedLength = lastReplacedLength;
return this;
}
public boolean isWrap() {
return wrap;
}
public FindReplaceString setWrap(boolean wrap) {
this.wrap = wrap;
return this;
}
public int getUnit() {
return unit;
}
public FindReplaceString setUnit(int step) {
this.unit = step;
return this;
}
public String getError() {
return error;
}
public FindReplaceString setError(String error) {
this.error = error;
return this;
}
public List<FindReplaceMatch> getMatches() {
return matches;
}
public FindReplaceString setMatches(List<FindReplaceMatch> matches) {
this.matches = matches;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/IntPoint.java | alpha/MyBox/src/main/java/mara/mybox/data/IntPoint.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:23:02
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IntPoint {
private int x, y;
public IntPoint(int x, int y) {
this.x = x;
this.y = y;
}
public static int distance2(int x1, int y1, int x2, int y2) {
int distanceX = x1 - x2;
int distanceY = y1 - y2;
return distanceX * distanceX + distanceY * distanceY;
}
public static int distance(int x1, int y1, int x2, int y2) {
return (int) Math.sqrt(distance2(x1, y1, x2, y2));
}
public static int distance2(IntPoint A, IntPoint B) {
int distanceX = A.getX() - B.getX();
int distanceY = A.getY() - B.getY();
return distanceX * distanceX + distanceY * distanceY;
}
public static int distance(IntPoint A, IntPoint B) {
return (int) Math.sqrt(distance2(A, B));
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DataSort.java | alpha/MyBox/src/main/java/mara/mybox/data/DataSort.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-12-1
* @License Apache License Version 2.0
*/
public class DataSort {
protected String name;
protected boolean ascending;
public DataSort() {
this.name = null;
this.ascending = true;
}
public DataSort(String name, boolean ascending) {
this.name = name;
this.ascending = ascending;
}
/*
static
*/
public static List<DataSort> parse(List<String> orders) {
if (orders == null || orders.isEmpty()) {
return null;
}
List<DataSort> sorts = new ArrayList<>();
String descString = "-" + message("Descending");
String ascString = "-" + message("Ascending");
int desclen = descString.length();
int asclen = ascString.length();
String sname;
boolean asc;
for (String order : orders) {
if (order.endsWith(descString)) {
sname = order.substring(0, order.length() - desclen);
asc = false;
} else if (order.endsWith(ascString)) {
sname = order.substring(0, order.length() - asclen);
asc = true;
} else {
continue;
}
sorts.add(new DataSort(sname, asc));
}
return sorts;
}
public static List<String> parseNames(List<String> orders) {
if (orders == null || orders.isEmpty()) {
return null;
}
List<String> names = new ArrayList<>();
String descString = "-" + message("Descending");
String ascString = "-" + message("Ascending");
int desclen = descString.length();
int asclen = ascString.length();
String sname;
for (String order : orders) {
if (order.endsWith(descString)) {
sname = order.substring(0, order.length() - desclen);
} else if (order.endsWith(ascString)) {
sname = order.substring(0, order.length() - asclen);
} else {
continue;
}
if (!names.contains(sname)) {
names.add(sname);
}
}
return names;
}
public static String toString(List<DataSort> sorts) {
if (sorts == null || sorts.isEmpty()) {
return null;
}
String orderBy = null, piece;
for (DataSort sort : sorts) {
piece = sort.getName() + (sort.isAscending() ? " ASC" : " DESC");
if (orderBy == null) {
orderBy = piece;
} else {
orderBy += ", " + piece;
}
}
return orderBy;
}
public static String parseToString(List<String> orders) {
return toString(parse(orders));
}
/*
get/set
*/
public String getName() {
return name;
}
public DataSort setName(String name) {
this.name = name;
return this;
}
public boolean isAscending() {
return ascending;
}
public DataSort setAscending(boolean ascending) {
this.ascending = ascending;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleQuadratic.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleQuadratic.java | package mara.mybox.data;
import java.awt.geom.QuadCurve2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-31
* @License Apache License Version 2.0
*/
public class DoubleQuadratic implements DoubleShape {
private double startX, startY, controlX, controlY, endX, endY;
public DoubleQuadratic() {
}
public DoubleQuadratic(double startX, double startY,
double controlX, double controlY, double endX, double endY) {
this.startX = startX;
this.startY = startY;
this.controlX = controlX;
this.controlY = controlY;
this.endX = endX;
this.endY = endY;
}
@Override
public String name() {
return message("QuadraticCurve");
}
@Override
public QuadCurve2D.Double getShape() {
return new QuadCurve2D.Double(startX, startY, controlX, controlY, endX, endY);
}
@Override
public DoubleQuadratic copy() {
return new DoubleQuadratic(startX, startY, controlX, controlY, endX, endY);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
startX += offsetX;
startY += offsetY;
controlX += offsetX;
controlY += offsetY;
endX += offsetX;
endY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
startX *= scaleX;
startY *= scaleY;
controlX *= scaleX;
controlY *= scaleY;
endX *= scaleX;
endY *= scaleY;
return true;
}
@Override
public String pathAbs() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "Q " + imageScale(controlX) + "," + imageScale(controlY) + " "
+ imageScale(endX) + "," + imageScale(endY);
}
@Override
public String pathRel() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "q " + imageScale(controlX - startX) + "," + imageScale(controlY - startY) + " "
+ imageScale(endX - startX) + "," + imageScale(endY - startY);
}
@Override
public String elementAbs() {
return "<path d=\"\n" + pathAbs() + "\n\"> ";
}
@Override
public String elementRel() {
return "<path d=\"\n" + pathRel() + "\n\"> ";
}
/*
get
*/
public double getStartX() {
return startX;
}
public void setStartX(double startX) {
this.startX = startX;
}
public double getStartY() {
return startY;
}
public void setStartY(double startY) {
this.startY = startY;
}
public double getEndX() {
return endX;
}
public void setEndX(double endX) {
this.endX = endX;
}
public double getEndY() {
return endY;
}
public void setEndY(double endY) {
this.endY = endY;
}
public double getControlX() {
return controlX;
}
public void setControlX(double controlX) {
this.controlX = controlX;
}
public double getControlY() {
return controlY;
}
public void setControlY(double controlY) {
this.controlY = controlY;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/RemoteFile.java | alpha/MyBox/src/main/java/mara/mybox/data/RemoteFile.java | package mara.mybox.data;
import com.jcraft.jsch.SftpATTRS;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-03-18
* @License Apache License Version 2.0
*/
public class RemoteFile extends FileNode {
public RemoteFile() {
separator = "/";
}
public RemoteFile(SftpATTRS attrs) {
try {
if (attrs == null) {
isExisted = false;
return;
}
isExisted = true;
if (attrs.isDir()) {
setFileType(FileInformation.FileType.Directory);
} else if (attrs.isBlk()) {
setFileType(FileInformation.FileType.Block);
} else if (attrs.isChr()) {
setFileType(FileInformation.FileType.Character);
} else if (attrs.isFifo()) {
setFileType(FileInformation.FileType.FIFO);
} else if (attrs.isLink()) {
setFileType(FileInformation.FileType.Link);
} else if (attrs.isSock()) {
setFileType(FileInformation.FileType.Socket);
} else {
setFileType(FileInformation.FileType.File);
}
setFileSize(attrs.getSize());
setModifyTime(attrs.getMTime() * 1000l);
setAccessTime(attrs.getATime() * 1000l);
setUid(attrs.getUId());
setGid(attrs.getGId());
setPermission(attrs.getPermissionsString());
} catch (Exception e) {
}
}
@Override
public String getFullName() {
return nodeFullName();
}
@Override
public String getSuffix() {
return fileType != null ? message(fileType.name()) : null;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/ShapeStyle.java | alpha/MyBox/src/main/java/mara/mybox/data/ShapeStyle.java | package mara.mybox.data;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import static javafx.scene.shape.StrokeLineCap.ROUND;
import static javafx.scene.shape.StrokeLineCap.SQUARE;
import javafx.scene.shape.StrokeLineJoin;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxColorTools;
import static mara.mybox.fxml.image.FxColorTools.toAwtColor;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2023-7-11
* @License Apache License Version 2.0
*/
public class ShapeStyle {
public final static String DefaultStrokeColor = "#c94d58", DefaultAnchorColor = "#0066cc";
private String name, more;
private Color strokeColor, fillColor, anchorColor;
private float strokeWidth, strokeOpacity, fillOpacity, anchorSize, strokeLineLimit, dashOffset;
private boolean isFillColor, isStrokeDash;
private List<Double> strokeDash;
private StrokeLineCap strokeLineCap;
private StrokeLineJoin strokeLineJoin;
public ShapeStyle() {
init("");
}
public ShapeStyle(String name) {
init(name);
}
public ShapeStyle(Connection conn, String name) {
init(conn, name);
}
final public void init(String name) {
try (Connection conn = DerbyBase.getConnection()) {
init(conn, name);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
final public void init(Connection conn, String inName) {
try {
name = inName != null ? inName : "";
try {
strokeColor = Color.web(UserConfig.getString(conn, name + "StrokeColor", DefaultStrokeColor));
} catch (Exception e) {
strokeColor = Color.web(DefaultStrokeColor);
}
try {
fillColor = Color.web(UserConfig.getString(conn, name + "FillColor", "0xFFFFFFFF"));
} catch (Exception e) {
fillColor = Color.TRANSPARENT;
}
try {
anchorColor = Color.web(UserConfig.getString(conn, name + "AnchorColor", DefaultAnchorColor));
} catch (Exception e) {
anchorColor = Color.web(DefaultAnchorColor);
}
strokeWidth = UserConfig.getFloat(conn, name + "StrokeWidth", 10);
if (strokeWidth < 0) {
strokeWidth = 10f;
}
strokeOpacity = UserConfig.getFloat(conn, name + "StrokeOpacity", 1);
if (strokeOpacity < 0) {
strokeOpacity = 1;
}
fillOpacity = UserConfig.getFloat(conn, name + "FillOpacity", 1f);
if (fillOpacity < 0) {
fillOpacity = 1f;
}
isFillColor = UserConfig.getBoolean(conn, name + "IsFillColor", false);
isStrokeDash = UserConfig.getBoolean(conn, name + "IsStrokeDash", false);
anchorSize = UserConfig.getFloat(conn, name + "AnchorSize", 10);
if (anchorSize < 0) {
anchorSize = 10;
}
String text = UserConfig.getString(conn, name + "StrokeDash", null);
strokeDash = text2StrokeDash(text);
text = UserConfig.getString(conn, name + "StrokeLineCap", "BUTT");
strokeLineCap = strokeLineCap(text);
text = UserConfig.getString(conn, name + "StrokeLineJoin", "MITER");
strokeLineJoin = strokeLineJoin(text);
strokeLineLimit = UserConfig.getFloat(conn, name + "StrokeLineLimit", 10f);
dashOffset = UserConfig.getFloat(conn, name + "DashOffset", 0f);
more = null;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public ShapeStyle save() {
try (Connection conn = DerbyBase.getConnection()) {
UserConfig.setString(conn, name + "StrokeColor", strokeColor != null ? strokeColor.toString() : null);
UserConfig.setString(conn, name + "AnchorColor", anchorColor != null ? anchorColor.toString() : null);
UserConfig.setBoolean(conn, name + "IsFillColor", isFillColor);
UserConfig.setString(conn, name + "FillColor", fillColor != null ? fillColor.toString() : null);
UserConfig.setFloat(conn, name + "StrokeWidth", strokeWidth);
UserConfig.setFloat(conn, name + "AnchorSize", anchorSize);
UserConfig.setFloat(conn, name + "StrokeOpacity", strokeOpacity);
UserConfig.setFloat(conn, name + "FillOpacity", fillOpacity);
UserConfig.setBoolean(conn, name + "IsStrokeDash", isStrokeDash);
UserConfig.setString(conn, name + "StrokeDash", strokeDash2Text(strokeDash));
UserConfig.setFloat(conn, name + "DashOffset", dashOffset);
UserConfig.setString(conn, name + "StrokeLineCap",
strokeLineCap != null ? strokeLineCap.name() : null);
UserConfig.setFloat(conn, name + "StrokeLineLimit", strokeLineLimit);
UserConfig.setString(conn, name + "StrokeLineJoin",
strokeLineJoin != null ? strokeLineJoin.name() : null);
} catch (Exception e) {
MyBoxLog.debug(e);
}
return this;
}
/*
static
*/
public static List<Double> text2StrokeDash(String text) {
try {
if (text == null || text.isBlank()) {
return null;
}
String[] values = text.split("\\s+");
if (values == null || values.length == 0) {
return null;
}
List<Double> dash = new ArrayList<>();
for (String v : values) {
dash.add(Double.valueOf(v));
}
return dash;
} catch (Exception e) {
return null;
}
}
public static String strokeDash2Text(List<Double> dash) {
try {
if (dash == null || dash.isEmpty()) {
return null;
}
String text = "";
for (Double v : dash) {
text += v + " ";
}
return text;
} catch (Exception e) {
return null;
}
}
public static float[] strokeDashAwt(List<Double> vs) {
try {
if (vs == null || vs.isEmpty()) {
return null;
}
float[] values = new float[vs.size()];
for (int i = 0; i < vs.size(); i++) {
values[i] = vs.get(i).floatValue();
}
return values;
} catch (Exception e) {
return null;
}
}
public static StrokeLineCap strokeLineCap(String text) {
try {
if (text == null || text.isBlank()) {
return StrokeLineCap.BUTT;
}
if ("ROUND".equalsIgnoreCase(text)) {
return StrokeLineCap.ROUND;
} else if ("SQUARE".equalsIgnoreCase(text)) {
return StrokeLineCap.SQUARE;
} else {
return StrokeLineCap.BUTT;
}
} catch (Exception e) {
return StrokeLineCap.BUTT;
}
}
public static int strokeLineCapAwt(StrokeLineCap v) {
try {
if (null == v) {
return java.awt.BasicStroke.CAP_BUTT;
} else {
switch (v) {
case ROUND:
return java.awt.BasicStroke.CAP_ROUND;
case SQUARE:
return java.awt.BasicStroke.CAP_SQUARE;
default:
return java.awt.BasicStroke.CAP_BUTT;
}
}
} catch (Exception e) {
return java.awt.BasicStroke.CAP_BUTT;
}
}
public static StrokeLineJoin strokeLineJoin(String text) {
try {
if (text == null || text.isBlank()) {
return StrokeLineJoin.MITER;
}
if ("ROUND".equalsIgnoreCase(text)) {
return StrokeLineJoin.ROUND;
} else if ("BEVEL".equalsIgnoreCase(text)) {
return StrokeLineJoin.BEVEL;
} else {
return StrokeLineJoin.MITER;
}
} catch (Exception e) {
return StrokeLineJoin.MITER;
}
}
public static int strokeLineJoinAwt(StrokeLineJoin v) {
try {
if (null == v) {
return java.awt.BasicStroke.JOIN_MITER;
} else {
switch (v) {
case ROUND:
return java.awt.BasicStroke.JOIN_ROUND;
case BEVEL:
return java.awt.BasicStroke.JOIN_BEVEL;
default:
return java.awt.BasicStroke.JOIN_MITER;
}
}
} catch (Exception e) {
return java.awt.BasicStroke.JOIN_MITER;
}
}
/*
set
*/
public ShapeStyle setName(String name) {
this.name = name;
return this;
}
public ShapeStyle setStrokeColor(Color strokeColor) {
this.strokeColor = strokeColor;
return this;
}
public ShapeStyle setAnchorColor(Color anchorColor) {
this.anchorColor = anchorColor;
return this;
}
public ShapeStyle setIsFillColor(boolean isFillColor) {
this.isFillColor = isFillColor;
return this;
}
public ShapeStyle setFillColor(Color fillColor) {
this.fillColor = fillColor;
return this;
}
public ShapeStyle setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
return this;
}
public ShapeStyle setAnchorSize(float anchorSize) {
this.anchorSize = anchorSize;
return this;
}
public ShapeStyle setStrokeOpacity(float strokeOpacity) {
this.strokeOpacity = strokeOpacity;
return this;
}
public ShapeStyle setFillOpacity(float fillOpacity) {
this.fillOpacity = fillOpacity;
return this;
}
public ShapeStyle setIsStrokeDash(boolean isStrokeDash) {
this.isStrokeDash = isStrokeDash;
return this;
}
public ShapeStyle setStrokeDashed(boolean dashed) {
setIsStrokeDash(dashed);
if (dashed) {
setStrokeDash(text2StrokeDash(strokeWidth + " " + strokeWidth * 3));
}
return this;
}
public ShapeStyle setStrokeDash(List<Double> strokeDash) {
this.strokeDash = strokeDash;
return this;
}
public ShapeStyle setStrokeDashText(String text) {
setStrokeDash(text2StrokeDash(text));
return this;
}
public ShapeStyle setDashOffset(float dashOffset) {
this.dashOffset = dashOffset;
return this;
}
public ShapeStyle setStrokeLineCap(StrokeLineCap strokeLineCap) {
this.strokeLineCap = strokeLineCap;
return this;
}
public ShapeStyle setStrokeLineLimit(float strokeLineLimit) {
this.strokeLineLimit = strokeLineLimit;
return this;
}
public ShapeStyle setStrokeLineJoin(StrokeLineJoin strokeLineJoin) {
this.strokeLineJoin = strokeLineJoin;
return this;
}
public ShapeStyle setMore(String more) {
this.more = more;
return this;
}
/*
get
*/
public String getName() {
return name;
}
public Color getStrokeColor() {
return strokeColor;
}
public String getStrokeColorCss() {
return FxColorTools.color2css(strokeColor);
}
public java.awt.Color getStrokeColorAwt() {
return toAwtColor(getStrokeColor());
}
public Color getFillColor() {
return fillColor;
}
public java.awt.Color getFillColorAwt() {
return toAwtColor(getFillColor());
}
public String getFilleColorCss() {
return FxColorTools.color2css(fillColor);
}
public Color getAnchorColor() {
return anchorColor;
}
public java.awt.Color getAnchorColorAwt() {
return toAwtColor(getAnchorColor());
}
public float getStrokeWidth() {
return strokeWidth;
}
public float getStrokeOpacity() {
return strokeOpacity;
}
public float getFillOpacity() {
return fillOpacity;
}
public float getAnchorSize() {
return anchorSize;
}
public boolean isIsFillColor() {
return isFillColor;
}
public boolean isIsStrokeDash() {
return isStrokeDash;
}
public List<Double> getStrokeDash() {
return strokeDash;
}
public float[] getStrokeDashAwt() {
return strokeDashAwt(strokeDash);
}
public String getStrokeDashText() {
return strokeDash2Text(strokeDash);
}
public float getDashOffset() {
return dashOffset;
}
public StrokeLineCap getStrokeLineCap() {
return strokeLineCap;
}
public int getStrokeLineCapAwt() {
return strokeLineCapAwt(strokeLineCap);
}
public String getStrokeLineCapText() {
return strokeLineCap != null ? strokeLineCap.name() : null;
}
public float getStrokeLineLimit() {
return strokeLineLimit;
}
public StrokeLineJoin getStrokeLineJoin() {
return strokeLineJoin;
}
public int getStrokeLineJoinAwt() {
return strokeLineJoinAwt(strokeLineJoin);
}
public String getMore() {
return more;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleArc.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleArc.java | package mara.mybox.data;
import java.awt.geom.Arc2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-31
* @License Apache License Version 2.0
*/
public class DoubleArc implements DoubleShape {
private double centerX, centerY, radiusX, radiusY, startAngle, extentAngle;
private int type;
public DoubleArc() {
}
public static DoubleArc rect(double x1, double y1, double x2, double y2,
double startAngle, double extentAngle, int type) {
DoubleArc a = new DoubleArc();
a.setCenterX((x1 + x2) / 2);
a.setCenterY((y1 + y2) / 2);
a.setRadiusX(Math.abs(x2 - x1) / 2);
a.setRadiusY(Math.abs(y2 - y1) / 2);
a.setStartAngle(startAngle);
a.setExtentAngle(extentAngle);
a.setType(type);
return a;
}
public static DoubleArc arc(double centerX, double centerY, double radiusX, double radiusY,
double startAngle, double extentAngle, int type) {
DoubleArc a = new DoubleArc();
a.setCenterX(centerX);
a.setCenterY(centerY);
a.setRadiusX(radiusX);
a.setRadiusY(radiusY);
a.setStartAngle(startAngle);
a.setExtentAngle(extentAngle);
a.setType(type);
return a;
}
@Override
public String name() {
return message("ArcCurve");
}
public double getX1() {
return centerX - radiusX;
}
public double getY1() {
return centerY - radiusY;
}
public double getX2() {
return centerX + radiusX;
}
public double getY2() {
return centerY + radiusY;
}
@Override
public Arc2D.Double getShape() {
return new Arc2D.Double(getX1(), getY1(), radiusX * 2, radiusY * 2, startAngle, extentAngle, type);
}
@Override
public DoubleArc copy() {
return DoubleArc.arc(centerX, centerY, radiusX, radiusY, startAngle, extentAngle, type);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
centerX += offsetX;
centerY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
radiusX *= scaleX;
radiusY *= scaleY;
return true;
}
// Calculation is provided by deekseek. Fixed by mara
@Override
public String pathAbs() {
double startRad = Math.toRadians(startAngle);
double endRad = Math.toRadians(startAngle + extentAngle);
double startX = imageScale(centerX + radiusX * Math.cos(startRad));
double startY = imageScale(centerY - radiusY * Math.sin(startRad));
double endX = imageScale(centerX + radiusX * Math.cos(endRad));
double endY = imageScale(centerY - radiusY * Math.sin(endRad));
if (Math.abs(radiusX) < 1e-3 || Math.abs(radiusY) < 1e-3) {
return String.format("M %.2f,%.2f L %.2f,%.2f", startX, startY, endX, endY);
}
int largeArcFlag = computeLargeArcFlag(extentAngle);
int sweepFlag = (extentAngle >= 0) ? 0 : 1;
String arcCmd = String.format(
"A %.2f %.2f 0 %d %d %.2f %.2f",
radiusX, radiusY, largeArcFlag, sweepFlag, endX, endY
);
switch (type) {
case Arc2D.OPEN:
return String.format("M %.2f,%.2f %s", startX, startY, arcCmd);
case Arc2D.CHORD:
return String.format("M %.2f,%.2f %s Z", startX, startY, arcCmd);
case Arc2D.PIE:
return String.format("M %.2f,%.2f L %.2f,%.2f %s Z",
centerX, centerY, startX, startY, arcCmd);
default:
throw new IllegalArgumentException("Unsupported arc type");
}
}
@Override
public String pathRel() {
double startRad = Math.toRadians(startAngle);
double endRad = Math.toRadians(startAngle + extentAngle);
double startX = imageScale(centerX + radiusX * Math.cos(startRad));
double startY = imageScale(centerY - radiusY * Math.sin(startRad));
double endX = imageScale(centerX + radiusX * Math.cos(endRad));
double endY = imageScale(centerY - radiusY * Math.sin(endRad));
if (Math.abs(radiusX) < 1e-3 || Math.abs(radiusY) < 1e-3) {
return String.format("M %.2f,%.2f l %.2f,%.2f",
startX, startY, endX - startX, endY - startY);
}
int largeArcFlag = computeLargeArcFlag(extentAngle);
int sweepFlag = (extentAngle >= 0) ? 0 : 1;
String arcCmd = String.format(
"a %.2f %.2f 0 %d %d %.2f %.2f",
radiusX, radiusY, largeArcFlag, sweepFlag, endX - centerX, endY - centerY
);
switch (type) {
case Arc2D.OPEN:
return String.format("M %.2f,%.2f %s", startX, startY, arcCmd);
case Arc2D.CHORD:
return String.format("M %.2f,%.2f %s Z", startX, startY, arcCmd);
case Arc2D.PIE:
return String.format("M %.2f,%.2f l %.2f,%.2f %s Z",
centerX, centerY, startX - centerX, startY - centerY, arcCmd);
default:
throw new IllegalArgumentException("Unsupported arc type");
}
}
private static int computeLargeArcFlag(double extent) {
double absExtent = Math.abs(extent);
double extentMod = absExtent % 360;
if (extentMod == 0) {
return 1;
}
return (extentMod > 180) ? 1 : 0;
}
@Override
public String elementAbs() {
return "<path d=\"\n" + pathAbs() + "\n\"> ";
}
@Override
public String elementRel() {
return "<path d=\"\n" + pathRel() + "\n\"> ";
}
/*
get
*/
public double getCenterX() {
return centerX;
}
public double getCenterY() {
return centerY;
}
public double getRadiusX() {
return radiusX;
}
public double getRadiusY() {
return radiusY;
}
public double getStartAngle() {
return startAngle;
}
public double getExtentAngle() {
return extentAngle;
}
public int getType() {
return type;
}
/*
set
*/
public void setCenterX(double centerX) {
this.centerX = centerX;
}
public void setCenterY(double centerY) {
this.centerY = centerY;
}
public void setRadiusX(double radiusX) {
this.radiusX = radiusX;
}
public void setRadiusY(double radiusY) {
this.radiusY = radiusY;
}
public void setStartAngle(double startAngle) {
this.startAngle = startAngle;
}
public void setExtentAngle(double extentAngle) {
this.extentAngle = extentAngle;
}
public void setType(int type) {
this.type = type;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleLine.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleLine.java | package mara.mybox.data;
import java.awt.geom.Line2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-6
* @License Apache License Version 2.0
*/
public class DoubleLine implements DoubleShape {
private double startX, startY, endX, endY;
public DoubleLine() {
}
public DoubleLine(double startX, double startY, double endX, double endY) {
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
}
@Override
public String name() {
return message("StraightLine");
}
@Override
public Line2D.Double getShape() {
return new Line2D.Double(startX, startY, endX, endY);
}
@Override
public DoubleLine copy() {
return new DoubleLine(startX, startY, endX, endY);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
startX += offsetX;
startY += offsetY;
endX += offsetX;
endY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
endX *= scaleX;
endY *= scaleY;
return true;
}
@Override
public String pathAbs() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "L " + imageScale(endX) + "," + imageScale(endY);
}
@Override
public String pathRel() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "l " + imageScale(endX - startX) + "," + imageScale(endY - startY);
}
@Override
public String elementAbs() {
return "<line x1=\"" + imageScale(startX) + "\""
+ " y1=\"" + imageScale(startY) + "\""
+ " x2=\"" + imageScale(endX) + "\""
+ " y2=\"" + imageScale(endY) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
public double getStartX() {
return startX;
}
public void setStartX(double startX) {
this.startX = startX;
}
public double getStartY() {
return startY;
}
public void setStartY(double startY) {
this.startY = startY;
}
public double getEndX() {
return endX;
}
public void setEndX(double endX) {
this.endX = endX;
}
public double getEndY() {
return endY;
}
public void setEndY(double endY) {
this.endY = endY;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleOutline.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleOutline.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import mara.mybox.image.data.ImageScope;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class DoubleOutline extends DoubleRectangle {
private BufferedImage image;
private int insideColor;
public DoubleOutline() {
}
public DoubleOutline(BufferedImage image, int color) {
this.image = image;
x = 0;
y = 0;
width = image.getWidth();
height = image.getHeight();
this.insideColor = color;
}
public DoubleOutline(BufferedImage image, DoubleRectangle rect, int color) {
this.image = image;
this.insideColor = color;
x = rect.getX();
y = rect.getY();
width = rect.getWidth();
height = rect.getHeight();
}
public DoubleOutline(ImageScope scope) {
image = scope.getOutline();
insideColor = scope.isShapeExcluded() ? -1 : 0;
DoubleRectangle rect = scope.getRectangle();
x = rect.getX();
y = rect.getY();
width = rect.getWidth();
height = rect.getHeight();
}
@Override
public boolean isValid() {
return image != null && super.isValid();
}
@Override
public DoubleOutline copy() {
return new DoubleOutline(image, this, insideColor);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FunctionsList.java | alpha/MyBox/src/main/java/mara/mybox/data/FunctionsList.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.menu.DevelopmentMenu;
import mara.mybox.fxml.menu.MenuTools;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-4
* @License Apache License Version 2.0
*/
public class FunctionsList {
public static final int MaxLevel = 4;
protected BaseController controller;
protected List<MenuItem> menus;
protected boolean withLink;
protected int index;
protected StringTable table;
protected String goImageFile, lang;
protected Map<String, MenuItem> map;
public FunctionsList(BaseController controller, boolean withLink, String lang) {
this.controller = controller;
this.withLink = withLink;
this.lang = lang;
}
public StringTable make() {
try {
if (withLink) {
goImageFile = AppVariables.MyboxDataPath + "/icons/iconGo.png";
BufferedImage srcImage = SwingFXUtils.fromFXImage(StyleTools.getIconImage("iconGo.png"), null);
ImageFileWriters.writeImageFile(null, srcImage, "png", goImageFile);
goImageFile = new File(goImageFile).toURI().toString();
}
index = 0;
List<String> names = new ArrayList<>();
names.add(message(lang, "Index"));
names.add(message(lang, "HierarchyNumber"));
for (int i = 1; i <= MaxLevel; i++) {
names.add(message(lang, "Level") + " " + i);
}
if (withLink) {
names.add(message(lang, "Go"));
}
table = new StringTable(names, message(lang, "FunctionsList"));
map = new HashMap<>();
menus = MenuTools.toolsMenu(controller);
Menu devMenu = new Menu(message("Development"));
devMenu.getItems().addAll(DevelopmentMenu.menusList(controller));
menus.add(devMenu);
int number = 0;
for (MenuItem menu : menus) {
menu(menu, 0, ++number + "");
}
return table;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public void menu(MenuItem menu, int level, String number) {
try {
makeRow(menu, level, number);
if (menu instanceof Menu) {
int childIndex = 0;
for (MenuItem menuItem : ((Menu) menu).getItems()) {
String childNumber = number + "." + ++childIndex;
menu(menuItem, level + 1, childNumber);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void makeRow(MenuItem menu, int level, String number) {
try {
String name = menu.getText();
if (name == null || name.isBlank()) {
return;
}
List<String> row = new ArrayList<>();
row.add(++index + "");
row.add(number);
for (int i = 0; i < MaxLevel; i++) {
row.add("");
}
if (withLink) {
String link;
if (menu.getOnAction() != null) {
link = "<a><img src=\"" + goImageFile + "\" "
+ "onclick=\"alert('" + name + "')\" "
+ "alt=\"" + message(lang, "Go") + "\"></a>";
map.put(name, menu);
} else {
link = "";
}
row.add(link);
}
row.set(level + 2, name);
table.add(row);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
/*
get
*/
public static int getMaxLevel() {
return MaxLevel;
}
public StringTable getTable() {
return table;
}
public String getGoImageFile() {
return goImageFile;
}
public Map<String, MenuItem> getMap() {
return map;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceMatch.java | alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceMatch.java | package mara.mybox.data;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2023-5-7
* @License Apache License Version 2.0
*/
public class FindReplaceMatch {
public final static int MatchedPrefixLength = 100;
protected long line, start, end; // 0-based, exclude end
protected String matchedPrefix;
public FindReplaceMatch() {
line = start = end = -1;
matchedPrefix = null;
}
/*
static
*/
public static FindReplaceMatch create() {
return new FindReplaceMatch();
}
/*
set
*/
public FindReplaceMatch setLine(long line) {
this.line = line;
return this;
}
public FindReplaceMatch setStart(long start) {
this.start = start;
return this;
}
public FindReplaceMatch setEnd(long end) {
this.end = end;
return this;
}
public FindReplaceMatch setMatchedPrefix(String matchedPrefix) {
this.matchedPrefix = StringTools.abbreviate(matchedPrefix, MatchedPrefixLength);
return this;
}
/*
get
*/
public long getLine() {
return line;
}
public long getStart() {
return start;
}
public long getEnd() {
return end;
}
public String getMatchedPrefix() {
return matchedPrefix;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/Direction.java | alpha/MyBox/src/main/java/mara/mybox/data/Direction.java | package mara.mybox.data;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-7-30
* @License Apache License Version 2.0
*/
public class Direction {
protected Name name;
protected int angle; // clockwise
public enum Name {
East, West, North, South, EastNorth, WestNorth, EastSouth, WestSouth, Number
}
public Direction(Name value) {
this.name = value == null ? defaultName() : value;
this.angle = angle(name);
}
public Direction(String name) {
this.name = name(name);
this.angle = angle(this.name);
}
public Direction(int angle) {
this.name = name(angle);
this.angle = angle(angle);
}
public String name() {
if (name == null) {
name = defaultName();
}
return name.name();
}
/*
Static methods
*/
public static Direction defaultDirection() {
return new Direction(defaultName());
}
public static Name defaultName() {
return Name.East;
}
public static Name name(String name) {
if (name == null || name.isBlank()) {
return defaultName();
}
for (Name item : Name.values()) {
if (name.equals(item.name()) || name.equals(Languages.message(item.name()))) {
return item;
}
}
return defaultName();
}
public static int angle(String name) {
return angle(name(name));
}
public static int angle(Name name) {
if (name == null) {
name = defaultName();
}
int angle;
switch (name) {
case West:
angle = 270;
break;
case North:
angle = 0;
break;
case South:
angle = 180;
break;
case EastNorth:
angle = 135;
break;
case WestNorth:
angle = 315;
break;
case EastSouth:
angle = 135;
break;
case WestSouth:
angle = 225;
break;
case East:
default:
angle = 90;
}
return angle;
}
public static int angle(int value) {
int angle = value % 360;
if (angle < 0) {
angle += 360;
}
return angle;
}
public static Name name(int value) {
int angle = angle(value);
Name name;
switch (angle) {
case 90:
name = Name.East;
break;
case 270:
name = Name.West;
break;
case 0:
name = Name.North;
break;
case 180:
name = Name.South;
break;
case 315:
name = Name.EastNorth;
break;
case 45:
name = Name.WestNorth;
break;
case 135:
name = Name.EastSouth;
break;
case 225:
name = Name.WestSouth;
break;
default:
name = Name.Number;
break;
}
return name;
}
/*
get/set
*/
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/MediaList.java | alpha/MyBox/src/main/java/mara/mybox/data/MediaList.java | /*
* Apache License Version 2.0
*/
package mara.mybox.data;
import java.util.List;
/**
*
* @author mara
*/
public class MediaList {
protected String name;
protected List<MediaInformation> medias;
public MediaList() {
}
public static MediaList create() {
return new MediaList();
}
public MediaList(String name) {
this.name = name;
}
/*
get/set
*/
public String getName() {
return name;
}
public MediaList setName(String name) {
this.name = name;
return this;
}
public List<MediaInformation> getMedias() {
return medias;
}
public MediaList setMedias(List<MediaInformation> medias) {
this.medias = medias;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/HtmlElement.java | alpha/MyBox/src/main/java/mara/mybox/data/HtmlElement.java | package mara.mybox.data;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.UrlTools;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
/**
* @Author Mara
* @CreateDate 2022-9-7
* @License Apache License Version 2.0
*/
public class HtmlElement {
protected Element element;
protected Charset charset;
protected String tag, href, name, address, decodedHref, decodedAddress;
public HtmlElement(Element element, Charset charset) {
this.element = element;
this.charset = charset;
parse();
}
public final void parse() {
try {
href = null;
decodedHref = null;
tag = null;
name = null;
address = null;
decodedAddress = null;
if (element == null) {
return;
}
tag = element.getTagName();
if (tag == null) {
return;
}
if (tag.equalsIgnoreCase("a")) {
href = element.getAttribute("href");
name = element.getTextContent();
if (href == null) {
NamedNodeMap m = element.getAttributes();
if (m != null) {
for (int k = 0; k < m.getLength(); k++) {
if ("href".equalsIgnoreCase(m.item(k).getNodeName())) {
href = m.item(k).getNodeValue();
} else if ("title".equalsIgnoreCase(m.item(k).getNodeName())) {
name = m.item(k).getNodeValue();
}
}
}
}
} else if (tag.equalsIgnoreCase("img")) {
href = element.getAttribute("src");
name = element.getAttribute("alt");
if (href == null) {
NamedNodeMap m = element.getAttributes();
if (m != null) {
for (int k = 0; k < m.getLength(); k++) {
if ("src".equalsIgnoreCase(m.item(k).getNodeName())) {
href = m.item(k).getNodeValue();
} else if ("alt".equalsIgnoreCase(m.item(k).getNodeName())) {
name = m.item(k).getNodeValue();
}
}
}
}
}
if (href == null) {
return;
}
try {
address = UrlTools.fullAddress(element.getBaseURI(), href);
} catch (Exception e) {
address = href;
}
if (charset != null) {
decodedHref = URLDecoder.decode(href, charset);
decodedAddress = URLDecoder.decode(address, charset);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean isLink() {
return decodedHref != null && "a".equalsIgnoreCase(tag);
}
public boolean isImage() {
return decodedHref != null && "img".equalsIgnoreCase(tag);
}
/*
get/set
*/
public Element getElement() {
return element;
}
public void setElement(Element element) {
this.element = element;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDecodedAddress() {
return decodedAddress;
}
public void setDecodedAddress(String decodedAddress) {
this.decodedAddress = decodedAddress;
}
public String getDecodedHref() {
return decodedHref;
}
public void setDecodedHref(String decodedHref) {
this.decodedHref = decodedHref;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FileEditInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/FileEditInformation.java | package mara.mybox.data;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.ByteTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.tools.TextTools.bomBytes;
import static mara.mybox.tools.TextTools.bomSize;
import static mara.mybox.tools.TextTools.checkCharsetByBom;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import thridparty.EncodingDetect;
/**
* @Author Mara
* @CreateDate 2018-12-10 13:06:33
* @License Apache License Version 2.0
*/
public abstract class FileEditInformation extends FileInformation implements Cloneable {
protected Edit_Type editType;
protected boolean withBom, totalNumberRead, charsetDetermined;
protected Charset charset;
protected Line_Break lineBreak;
protected String lineBreakValue;
protected int objectUnit, lineBreakWidth;
protected String[] filterStrings;
protected FindReplaceFile findReplace;
protected StringFilterType filterType;
public Pagination pagination;
public enum Edit_Type {
Text, Bytes, Markdown
}
public enum StringFilterType {
IncludeAll, IncludeOne, NotIncludeAll, NotIncludeAny,
MatchRegularExpression, NotMatchRegularExpression,
IncludeRegularExpression, NotIncludeRegularExpression
}
public enum Line_Break {
LF, // Liunx/Unix
CR, // IOS
CRLF, // Windows
Width,
Value,
Auto
}
public FileEditInformation() {
editType = Edit_Type.Text;
}
public FileEditInformation(File file) {
super(file);
}
@Override
public Object clone() throws CloneNotSupportedException {
try {
FileEditInformation newInfo = (FileEditInformation) super.clone();
newInfo.setEditType(editType);
newInfo.setCharset(charset);
newInfo.setLineBreak(lineBreak);
newInfo.setFindReplace(findReplace);
newInfo.setFilterType(filterType);
return newInfo;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
protected final void initValues() {
filterType = StringFilterType.IncludeOne;
withBom = totalNumberRead = charsetDetermined = false;
charset = defaultCharset();
pagination = new Pagination();
pagination.init(editType == Edit_Type.Bytes
? Pagination.ObjectType.Bytes
: Pagination.ObjectType.Text);
findReplace = null;
switch (System.lineSeparator()) {
case "\r\n":
lineBreak = Line_Break.CRLF;
lineBreakValue = "\r\n";
break;
case "\r":
lineBreak = Line_Break.CR;
lineBreakValue = "\r";
break;
default:
lineBreak = Line_Break.LF;
lineBreakValue = "\n";
break;
}
lineBreakWidth = 30;
objectUnit = editType == Edit_Type.Bytes ? 3 : 1;
}
public static Charset defaultCharset() {
// return Charset.defaultCharset();
return Charset.forName("UTF-8");
}
public static FileEditInformation create(Edit_Type type, File file) {
switch (type) {
case Text:
return new TextEditInformation(file);
case Bytes:
return new BytesEditInformation(file);
default:
return new TextEditInformation(file);
}
}
public boolean checkCharset() {
try {
if (file == null) {
return false;
}
String setName;
withBom = false;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
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) {
charset = Charset.forName(setName);
withBom = true;
return true;
}
}
}
setName = EncodingDetect.detect(file);
charset = Charset.forName(setName);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean convertCharset(FxTask currentTask, FileEditInformation targetInfo) {
try {
if (file == null || charset == null
|| targetInfo == null || targetInfo.getFile() == null || targetInfo.getCharset() == null) {
return false;
}
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
InputStreamReader reader = new InputStreamReader(inputStream, charset);
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetInfo.getFile()));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, targetInfo.getCharset())) {
if (withBom) {
inputStream.skip(bomSize(charset.name()));
}
if (targetInfo.isWithBom()) {
byte[] bytes = bomBytes(targetInfo.getCharset().name());
outputStream.write(bytes);
}
char[] buf = new char[AppValues.IOBufferLength];
int bufLen;
while ((bufLen = reader.read(buf)) > 0) {
writer.write(new String(buf, 0, bufLen));
}
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public abstract boolean readTotalNumbers(FxTask currentTask);
public abstract String readPage(FxTask currentTask, long pageNumber);
public abstract boolean writeObject(FxTask currentTask, String text);
public abstract boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String text);
public abstract String readLines(FxTask currentTask, long from, long number);
public abstract String readObjects(FxTask currentTask, long from, long number);
public abstract File filter(FxTask currentTask, boolean recordLineNumbers);
public String readLine(FxTask currentTask, long line) {
return readLines(currentTask, line, 1);
}
public String readObject(FxTask currentTask, long index) {
return readObjects(currentTask, index, 1);
}
public boolean isMatchFilters(String string) {
if (string == null || string.isEmpty()) {
return false;
}
switch (filterType) {
case IncludeOne:
return includeOne(string);
case IncludeAll:
return includeAll(string);
case NotIncludeAny:
return notIncludeAny(string);
case NotIncludeAll:
return notIncludeAll(string);
case MatchRegularExpression:
return matchRegularExpression(string);
case NotMatchRegularExpression:
return notMatchRegularExpression(string);
case IncludeRegularExpression:
return includeRegularExpression(string);
case NotIncludeRegularExpression:
return notIncludeRegularExpression(string);
default:
return false;
}
}
public boolean includeOne(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (found) {
return true;
}
}
return false;
}
public boolean includeAll(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (!found) {
return false;
}
}
return true;
}
public boolean notIncludeAny(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (found) {
return false;
}
}
return true;
}
public boolean notIncludeAll(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (!found) {
return true;
}
}
return false;
}
public boolean includeRegularExpression(String string) {
return StringTools.include(string, filterStrings[0], false);
}
public boolean notIncludeRegularExpression(String string) {
return !StringTools.include(string, filterStrings[0], false);
}
public boolean matchRegularExpression(String string) {
return StringTools.match(string, filterStrings[0], false);
}
public boolean notMatchRegularExpression(String string) {
return !StringTools.match(string, filterStrings[0], false);
}
public String filterTypeName() {
return message(filterType.name());
}
public String lineBreakName() {
if (lineBreak == null) {
return "";
}
switch (lineBreak) {
case Width:
return message("BytesNumber") + lineBreakWidth;
case Value:
return message("BytesHex") + lineBreakWidth;
case LF:
return message("LFHex");
case CR:
return message("CRHex");
case CRLF:
return message("CRLFHex");
default:
return "";
}
}
/*
pagination
*/
public long getRowsNumber() {
return pagination != null ? pagination.getRowsNumber() : 0;
}
public void setRowsNumber(long v) {
if (pagination != null) {
pagination.setRowsNumber(v);
}
}
public long getObjectsNumber() {
return pagination != null ? pagination.getObjectsNumber() : 0;
}
public void setObjectsNumber(long v) {
if (pagination != null) {
pagination.setObjectsNumber(v);
}
}
public long getPagesNumber() {
return pagination != null ? pagination.getPagesNumber() : 0;
}
public void setPagesNumber(long v) {
if (pagination != null) {
pagination.setPagesNumber(v);
}
}
public int getPageSize() {
return pagination != null ? pagination.getPageSize() : 0;
}
public void setPageSize(int v) {
if (pagination != null) {
pagination.setPageSize(v);
}
}
public long getCurrentPage() {
return pagination != null ? pagination.getCurrentPage() : 0;
}
public void setCurrentPage(long v) {
if (pagination != null) {
pagination.setCurrentPage(v);
}
}
public long getStartRowOfCurrentPage() {
return pagination != null ? pagination.getStartRowOfCurrentPage() : 0;
}
public void setStartRowOfCurrentPage(long v) {
if (pagination != null) {
pagination.setStartRowOfCurrentPage(v);
}
}
public long getEndRowOfCurrentPage() {
return pagination != null ? pagination.getEndRowOfCurrentPage() : 0;
}
public void setEndRowOfCurrentPage(long v) {
if (pagination != null) {
pagination.setEndRowOfCurrentPage(v);
}
}
public long getStartObjectOfCurrentPage() {
return pagination != null ? pagination.getStartObjectOfCurrentPage() : 0;
}
public void setStartObjectOfCurrentPage(long v) {
if (pagination != null) {
pagination.setStartObjectOfCurrentPage(v);
}
}
public long getEndObjectOfCurrentPage() {
return pagination != null ? pagination.getEndObjectOfCurrentPage() : 0;
}
public void setEndObjectOfCurrentPage(long v) {
if (pagination != null) {
pagination.setEndObjectOfCurrentPage(v);
}
}
/*
get/set
*/
public boolean isWithBom() {
return withBom;
}
public void setWithBom(boolean withBom) {
this.withBom = withBom;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public Line_Break getLineBreak() {
return lineBreak;
}
public void setLineBreak(Line_Break lineBreak) {
this.lineBreak = lineBreak;
}
public Edit_Type getEditType() {
return editType;
}
public void setEditType(Edit_Type editType) {
this.editType = editType;
}
public String[] getFilterStrings() {
return filterStrings;
}
public void setFilterStrings(String[] filterStrings) {
this.filterStrings = filterStrings;
}
public StringFilterType getFilterType() {
return filterType;
}
public void setFilterType(StringFilterType filterType) {
this.filterType = filterType;
}
public int getLineBreakWidth() {
return lineBreakWidth;
}
public void setLineBreakWidth(int lineBreakWidth) {
this.lineBreakWidth = lineBreakWidth;
}
public String getLineBreakValue() {
return lineBreakValue;
}
public void setLineBreakValue(String lineBreakValue) {
this.lineBreakValue = lineBreakValue;
}
public boolean isTotalNumberRead() {
return totalNumberRead;
}
public void setTotalNumberRead(boolean totalNumberRead) {
this.totalNumberRead = totalNumberRead;
}
public Pagination getPagination() {
return pagination;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
public FindReplaceFile getFindReplace() {
return findReplace;
}
public void setFindReplace(FindReplaceFile findReplace) {
this.findReplace = findReplace;
}
public int getObjectUnit() {
return objectUnit;
}
public void setObjectUnit(int objectUnit) {
this.objectUnit = objectUnit;
}
public long getSizeWithSubdir() {
return sizeWithSubdir;
}
public void setSizeWithSubdir(long sizeWithSubdir) {
this.sizeWithSubdir = sizeWithSubdir;
}
public long getSizeWithoutSubdir() {
return sizeWithoutSubdir;
}
public void setSizeWithoutSubdir(long sizeWithoutSubdir) {
this.sizeWithoutSubdir = sizeWithoutSubdir;
}
public long getFilesWithSubdir() {
return filesWithSubdir;
}
public void setFilesWithSubdir(long filesWithSubdir) {
this.filesWithSubdir = filesWithSubdir;
}
public long getFilesWithoutSubdir() {
return filesWithoutSubdir;
}
public void setFilesWithoutSubdir(long filesWithoutSubdir) {
this.filesWithoutSubdir = filesWithoutSubdir;
}
public boolean isCharsetDetermined() {
return charsetDetermined;
}
public void setCharsetDetermined(boolean charsetDetermined) {
this.charsetDetermined = charsetDetermined;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/TTC.java | alpha/MyBox/src/main/java/mara/mybox/data/TTC.java | package mara.mybox.data;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.tools.ByteTools.bytesToHex;
import static mara.mybox.tools.ByteTools.bytesToUInt;
import static mara.mybox.tools.ByteTools.bytesToUshort;
import static mara.mybox.tools.ByteTools.subBytes;
import static mara.mybox.tools.ByteTools.uIntToBytes;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.Languages;
/**
* Reference: https://github.com/fermi1981/TTC_TTF
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*/
public class TTC {
protected File ttcFile;
protected String tag, sig;
protected long version, ttfCount, sigLength, sigOffset;
protected long[] offsets;
protected List<TTFInfo> ttfInfos;
protected List<List<DataInfo>> dataInfos;
public class TTFInfo {
String tag;
int numTables, searchRange, entrySelector, rangeShift;
}
public class DataInfo {
String tag;
long checkSum, offset, length, writeOffset, writeLength;
}
public TTC(File file) {
ttcFile = file;
}
public void parseFile() {
ttfCount = 0;
ttfInfos = null;
dataInfos = null;
if (ttcFile == null || !ttcFile.exists() || !ttcFile.isFile()) {
return;
}
try ( RandomAccessFile inputStream = new RandomAccessFile(ttcFile, "r")) {
ttfInfos = new ArrayList<>();
dataInfos = new ArrayList<>();
byte[] buf = new byte[4];
int readLen = inputStream.read(buf);
if (readLen != 4) {
return;
}
tag = new String(subBytes(buf, 0, 4));
if (tag.equals("ttcf")) {
parseTTC(inputStream);
} else {
boolean isTTF = false;
if (buf[0] == 0 && buf[1] == 1 && buf[2] == 0 && buf[3] == 0) {
isTTF = true;
} else if (!tag.toLowerCase().equals("otto")) {
isTTF = true;
}
if (isTTF) {
ttfCount = 1;
parseTTF(inputStream, 1);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void parseTTC(RandomAccessFile inputStream) {
try {
byte[] buf = new byte[8];
int readLen = inputStream.read(buf);
if (readLen != 8) {
return;
}
version = bytesToUInt(subBytes(buf, 0, 4));
ttfCount = bytesToUInt(subBytes(buf, 4, 4));
offsets = new long[(int) ttfCount];
buf = new byte[4];
for (int i = 0; i < ttfCount; i++) {
readLen = inputStream.read(buf);
if (readLen != 4) {
return;
}
offsets[i] = bytesToUInt(buf);
}
buf = new byte[12];
readLen = inputStream.read(buf);
if (readLen != 12) {
return;
}
sig = new String(subBytes(buf, 0, 4));
if (sig.equals("DSIG")) {
sigLength = bytesToUInt(subBytes(buf, 4, 4));
sigOffset = bytesToUInt(subBytes(buf, 8, 4));
// MyBoxLog.console(sig + " " + sigOffset + " " + sigLength);
}
for (int i = 0; i < ttfCount; i++) {
parseTTF(inputStream, i);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
// Looks working well without alignment.
public long ceil4(long length) {
long mod = length % 4;
if (mod > 0) {
return length + 4 - mod;
} else {
return length;
}
}
public TTFInfo parseTTF(RandomAccessFile inputStream, int index) {
try {
inputStream.seek(offsets[index]);
// MyBoxLog.console("seek:" + offsets[index]);
byte[] buf = new byte[12];
int readLen = inputStream.read(buf);
if (readLen != 12) {
return null;
}
TTFInfo ttfInfo = new TTFInfo();
ttfInfo.tag = bytesToHex(subBytes(buf, 0, 4));
ttfInfo.numTables = bytesToUshort(subBytes(buf, 4, 2));
ttfInfo.searchRange = bytesToUshort(subBytes(buf, 6, 2));
ttfInfo.entrySelector = bytesToUshort(subBytes(buf, 8, 2));
ttfInfo.rangeShift = bytesToUshort(subBytes(buf, 10, 2));
List<DataInfo> ttfData = new ArrayList<>();
long dataOffset = 12 + ttfInfo.numTables * 16;
for (int i = 0; i < ttfInfo.numTables; i++) {
buf = new byte[16];
readLen = inputStream.read(buf);
if (readLen != 16) {
MyBoxLog.error("Invalid");
return null;
}
DataInfo dataInfo = new DataInfo();
dataInfo.tag = new String(subBytes(buf, 0, 4));
dataInfo.checkSum = bytesToUInt(subBytes(buf, 4, 4));
dataInfo.offset = bytesToUInt(subBytes(buf, 8, 4));
dataInfo.length = bytesToUInt(subBytes(buf, 12, 4));
dataInfo.writeOffset = dataOffset;
dataInfo.writeLength = ceil4(dataInfo.length);
dataOffset += dataInfo.writeLength;
ttfData.add(dataInfo);
}
ttfInfos.add(ttfInfo);
dataInfos.add(ttfData);
return ttfInfo;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String html() {
try {
if (ttcFile == null || ttfInfos == null || ttfInfos.isEmpty()) {
return null;
}
String html = "TTC: " + ttcFile.getAbsolutePath() + "<BR>"
+ Languages.message("Tag") + ":" + tag + " "
+ Languages.message("Count") + ":" + ttfCount + "<BR>";
List<String> names = Arrays.asList("index", Languages.message("Offset"), Languages.message("Tag"),
"numTables", "searchRange", "entrySelector", "rangeShift");
StringTable table = new StringTable(names);
for (int i = 0; i < ttfInfos.size(); i++) {
TTFInfo ttf = ttfInfos.get(i);
List<String> row = Arrays.asList(i + "", offsets[i] + "", ttf.tag,
ttf.numTables + "", ttf.searchRange + "", ttf.entrySelector + "", ttf.rangeShift + "");
table.add(row);
}
html += table.div() + "<BR><HR><BR>";
for (int i = 0; i < ttfInfos.size(); i++) {
html += "<P align=center>TTF " + (i + 1) + "</P><BR>";
List<DataInfo> ttfData = dataInfos.get(i);
names = Arrays.asList("index", Languages.message("Tag"), "checkSum",
"offset", "length", "target offset", "target length");
table = new StringTable(names);
for (int j = 0; j < ttfData.size(); j++) {
DataInfo info = ttfData.get(j);
List<String> row = Arrays.asList(j + "", info.tag, info.checkSum + "",
info.offset + "", info.length + "", info.writeOffset + "", info.writeLength + "");
table.add(row);
}
html += table.div() + "<BR><BR>";
}
return html;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public List<File> extract(File targetPath) {
if (ttcFile == null) {
return null;
}
if (ttfInfos == null || ttfInfos.isEmpty()) {
parseFile();
}
if (ttfInfos == null || ttfInfos.isEmpty()) {
return null;
}
String namePrefix = FileNameTools.prefix(ttcFile.getName());
try ( RandomAccessFile inputStream = new RandomAccessFile(ttcFile, "r")) {
List<File> files = new ArrayList<>();
for (int i = 0; i < ttfInfos.size(); i++) {
long offset = offsets[i];
inputStream.seek(offset);
List<DataInfo> ttfData = dataInfos.get(i);
File ttfFile;
if (targetPath != null) {
ttfFile = new File(targetPath.getAbsoluteFile() + File.separator + namePrefix + "_" + i + ".ttf");
} else {
ttfFile = FileTmpTools.getTempFile(".ttf");
}
try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(ttfFile))) {
int headerLen = 12 + ttfData.size() * 16;
byte[] head = new byte[headerLen];
int readLen = inputStream.read(head);
if (readLen != headerLen) {
MyBoxLog.error(i + " offset:" + offset + " headerLen:" + headerLen + " readLen:" + readLen);
continue;
}
// MyBoxLog.console(bytesToHexFormat(head));
for (int j = 0; j < ttfData.size(); j++) {
DataInfo dataInfo = ttfData.get(j);
byte[] offsetBytes = uIntToBytes(dataInfo.writeOffset);
System.arraycopy(offsetBytes, 0, head, 12 + j * 16 + 8, 4);
byte[] lenBytes = uIntToBytes(dataInfo.writeLength);
System.arraycopy(lenBytes, 0, head, 12 + j * 16 + 12, 4);
// MyBoxLog.console(" dataOffset:" + dataInfo.wOffset + " offsetBytes:" + bytesToHexFormat(offsetBytes)
// + " fixedLength:" + dataInfo.wLength + " lenBytes:" + bytesToHexFormat(lenBytes));
}
// MyBoxLog.console(bytesToHexFormat(head));
outputStream.write(head);
for (int j = 0; j < ttfData.size(); j++) {
DataInfo dataInfo = ttfData.get(j);
inputStream.seek(dataInfo.offset);
byte[] readData = new byte[(int) dataInfo.length]; // Assume length value is smaller than Integer.MAX_VALUE
byte[] writeFata = new byte[(int) dataInfo.writeLength];
readLen = inputStream.read(readData);
if (readLen > 0) {
System.arraycopy(readData, 0, writeFata, 0, readLen);
}
outputStream.write(writeFata);
}
outputStream.flush();
} catch (Exception e) {
MyBoxLog.error(e);
continue;
}
files.add(ttfFile);
}
return files;
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
/*
get/set
*/
public File getTtcFile() {
return ttcFile;
}
public void setTtcFile(File ttcFile) {
this.ttcFile = ttcFile;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getSig() {
return sig;
}
public void setSig(String sig) {
this.sig = sig;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getTtfCount() {
return ttfCount;
}
public void setTtfCount(long ttfCount) {
this.ttfCount = ttfCount;
}
public long[] getOffsets() {
return offsets;
}
public void setOffsets(long[] offsets) {
this.offsets = offsets;
}
public long getSigLength() {
return sigLength;
}
public void setSigLength(long sigLength) {
this.sigLength = sigLength;
}
public long getSigOffset() {
return sigOffset;
}
public void setSigOffset(long sigOffset) {
this.sigOffset = sigOffset;
}
public List<TTFInfo> getTtfInfos() {
return ttfInfos;
}
public void setTtfInfos(List<TTFInfo> ttfInfos) {
this.ttfInfos = ttfInfos;
}
public List<List<DataInfo>> getDataInfos() {
return dataInfos;
}
public void setDataInfos(List<List<DataInfo>> dataInfos) {
this.dataInfos = dataInfos;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleCircle.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleCircle.java | package mara.mybox.data;
import java.awt.geom.Ellipse2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @License Apache License Version 2.0
*/
public class DoubleCircle implements DoubleShape {
private double centerX, centerY, radius;
public DoubleCircle() {
}
public DoubleCircle(double x, double y, double r) {
centerX = x;
centerY = y;
radius = r;
}
@Override
public String name() {
return message("Circle");
}
@Override
public Ellipse2D.Double getShape() {
return new Ellipse2D.Double(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
}
@Override
public DoubleCircle copy() {
return new DoubleCircle(centerX, centerY, radius);
}
@Override
public boolean isValid() {
return radius > 0;
}
@Override
public boolean isEmpty() {
return !isValid();
}
public boolean same(DoubleCircle circle) {
return centerX == circle.getCenterX() && centerY == circle.getCenterY()
&& radius == circle.getRadius();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
centerX += offsetX;
centerY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
radius *= Math.min(scaleX, scaleY);
return true;
}
@Override
public String pathAbs() {
double cx = imageScale(centerX);
double cy = imageScale(centerY);
double r = imageScale(radius);
return "M " + (cx - r) + "," + cy + " \n"
+ "A " + r + "," + r + " 0,0,1 " + (cx + r) + "," + cy + " \n"
+ "A " + r + "," + r + " 0,0,1 " + (cx - r) + "," + cy + " \n"
+ "Z";
}
@Override
public String pathRel() {
double cx = imageScale(centerX);
double cy = imageScale(centerY);
double r = imageScale(radius);
double r2 = imageScale(2 * radius);
return "M " + (cx - r) + "," + cy + " \n"
+ "a " + r + "," + r + " 0,0,1 " + r2 + "," + 0 + " \n"
+ "a " + r + "," + r + " 0,0,1 " + (-r2) + "," + 0 + " \n"
+ "z";
}
@Override
public String elementAbs() {
return "<circle cx=\"" + imageScale(centerX) + "\""
+ " cy=\"" + imageScale(centerY) + "\""
+ " r=\"" + imageScale(radius) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
/*
set
*/
public void setRadius(double radius) {
this.radius = radius;
}
/*
get
*/
public double getCenterX() {
return centerX;
}
public double getCenterY() {
return centerY;
}
public double getRadius() {
return radius;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/XmlTreeNode.java | alpha/MyBox/src/main/java/mara/mybox/data/XmlTreeNode.java | package mara.mybox.data;
import mara.mybox.tools.XmlTools;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2023-5-27
* @License Apache License Version 2.0
*/
public class XmlTreeNode {
protected String title, value;
protected NodeType type;
protected Node node;
public static enum NodeType {
Element, Attribute, Text, CDATA, EntityRefrence, Entity, ProcessingInstruction,
Comment, Document, DocumentType, DocumentFragment, Notation, Unknown
}
public XmlTreeNode() {
node = null;
title = null;
value = null;
type = NodeType.Unknown;
}
public XmlTreeNode(Node node) {
this.node = node;
type = XmlTools.type(node);
}
public int childrenSize() {
if (node == null) {
return 0;
}
NodeList children = node.getChildNodes();
if (children == null) {
return 0;
}
return children.getLength();
}
public boolean canAddNode() {
NodeType t = XmlTools.type(node);
return t == NodeType.Document
|| t == NodeType.Element || t == NodeType.Attribute
|| t == NodeType.Entity || t == NodeType.EntityRefrence
|| t == NodeType.DocumentFragment;
}
public boolean isDocWithoutElement() {
if (node == null) {
return false;
}
NodeType t = XmlTools.type(node);
if (t != NodeType.Document) {
return false;
}
NodeList children = node.getChildNodes();
if (children == null) {
return true;
}
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
return false;
}
}
return true;
}
public int index() {
return XmlTools.index(node);
}
public String hierarchyNumber() {
return XmlTools.hierarchyNumber(node);
}
public boolean canAddSvgShape() {
if (XmlTools.type(node) != NodeType.Element) {
return false;
}
String tag = node.getNodeName();
return "svg".equalsIgnoreCase(tag)
|| "g".equalsIgnoreCase(tag)
|| "defs".equalsIgnoreCase(tag);
}
public boolean isSvgShape() {
if (XmlTools.type(node) != NodeType.Element) {
return false;
}
String tag = node.getNodeName();
return "rect".equalsIgnoreCase(tag)
|| "circle".equalsIgnoreCase(tag)
|| "ellipse".equalsIgnoreCase(tag)
|| "line".equalsIgnoreCase(tag)
|| "polyline".equalsIgnoreCase(tag)
|| "polygon".equalsIgnoreCase(tag)
|| "path".equalsIgnoreCase(tag);
}
/*
custimized get
*/
public String getTitle() {
return XmlTools.name(node);
}
public String getValue() {
return XmlTools.value(node);
}
public NodeType getType() {
return type;
}
public String getTypename() {
return type == null ? null : type.name();
}
/*
set
*/
public XmlTreeNode setNode(Node node) {
this.node = node;
return this;
}
public XmlTreeNode setTitle(String title) {
this.title = title;
return this;
}
public XmlTreeNode setValue(String value) {
this.value = value;
return this;
}
public XmlTreeNode setType(NodeType type) {
this.type = type;
return this;
}
/*
get
*/
public Node getNode() {
return node;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FileNode.java | alpha/MyBox/src/main/java/mara/mybox/data/FileNode.java | package mara.mybox.data;
import java.io.File;
import mara.mybox.tools.FileNameTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-03-18
* @License Apache License Version 2.0
*/
public class FileNode extends FileInformation {
public boolean isExisted;
public FileNode parentNode;
public String nodename, permission, separator;
public long accessTime;
public int uid, gid;
public FileNode() {
init();
parentNode = null;
separator = File.separator;
}
public FileNode(File file) {
setFileAttributes(file);
isExisted = file != null && file.exists();
nodename = super.getFullName();
}
public String parentName() {
return parentNode != null ? parentNode.nodeFullName() : "";
}
public String path(boolean endSeparator) {
String pathname;
if (parentNode == null) {
pathname = nodename;
} else if (isDirectory()) {
pathname = nodeFullName();
} else {
pathname = parentNode.nodeFullName();
}
return endSeparator ? pathname + separator : pathname;
}
public String nodeFullName() {
return (parentNode != null ? parentNode.nodeFullName() + separator : "") + nodename;
}
public boolean isExisted() {
return isExisted;
}
public boolean isDirectory() {
return fileType == FileInformation.FileType.Directory;
}
/*
customized get/set
*/
@Override
public String getFileName() {
if (file != null) {
return file.getName();
} else if (nodename != null) {
return FileNameTools.name(nodename, separator);
} else if (data != null) {
return FileNameTools.name(data, separator);
} else {
return null;
}
}
@Override
public String getSuffix() {
if (fileType != null && fileType != FileType.File) {
return message(fileType.name());
}
if (file != null) {
if (file.isDirectory()) {
return null;
} else {
return FileNameTools.ext(file.getName(), separator);
}
} else if (nodename != null) {
return FileNameTools.ext(nodename, separator);
} else if (data != null) {
return FileNameTools.ext(data, separator);
} else {
return null;
}
}
@Override
public void setData(String data) {
this.data = data;
if (nodename == null) {
nodename = data;
}
}
/*
get/set
*/
public FileNode getParentNode() {
return parentNode;
}
public FileNode setParentFile(FileNode parentFile) {
this.parentNode = parentFile;
return this;
}
public String getNodename() {
return nodename;
}
public FileNode setNodename(String nodename) {
this.nodename = nodename;
return this;
}
public String getSeparator() {
return separator;
}
public FileNode setSeparator(String separator) {
this.separator = separator;
return this;
}
public long getAccessTime() {
return accessTime;
}
public FileNode setAccessTime(long accessTime) {
this.accessTime = accessTime;
return this;
}
public String getPermission() {
return permission;
}
public FileNode setPermission(String permission) {
this.permission = permission;
return this;
}
public int getUid() {
return uid;
}
public FileNode setUid(int uid) {
this.uid = uid;
return this;
}
public int getGid() {
return gid;
}
public FileNode setGid(int gid) {
this.gid = gid;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/RGBColorSpace.java | alpha/MyBox/src/main/java/mara/mybox/color/RGBColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import static mara.mybox.color.ChromaticAdaptation.matrix;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleMatrixTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 21:33:50
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*
* Reference:
* http://brucelindbloom.com/index.html?WorkingSpaceInfo.html#Specifications
*/
public class RGBColorSpace extends CIEData {
public String colorSpaceName, colorName, illuminantName, adaptAlgorithm;
public RGBColorSpace(String colorSpace, String color,
String illuminant, double[] values) {
this.colorSpaceName = colorSpace;
this.illuminantName = illuminant;
this.colorName = color;
this.adaptAlgorithm = "";
setxyY(values);
}
public RGBColorSpace(String colorSpace, String color,
String illuminant, String adaptAlgorithm, double[] values) {
this.colorSpaceName = colorSpace;
this.illuminantName = illuminant;
this.adaptAlgorithm = adaptAlgorithm;
this.colorName = color;
setTristimulusValues(values[0], values[1], values[2]);
}
/*
Static methods
*/
public static List<RGBColorSpace> standard() {
List<RGBColorSpace> data = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
double[][] p = primaries(cs);
String n = name(cs);
String t = illuminantType(cs) + "";
data.add(new RGBColorSpace(n, "Red", t, p[0]));
data.add(new RGBColorSpace(n, "Green", t, p[1]));
data.add(new RGBColorSpace(n, "Blue", t, p[2]));
}
return data;
}
public static List<RGBColorSpace> adapted() {
List<RGBColorSpace> data = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
String name = name(cs);
double[][] primaries = primariesTristimulus(name);
IlluminantType ci = illuminantType(cs);
for (IlluminantType i : IlluminantType.values()) {
for (ChromaticAdaptationAlgorithm a : ChromaticAdaptationAlgorithm.values()) {
if (ci != i) {
data.add(new RGBColorSpace(name, "Red", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
data.add(new RGBColorSpace(name, "Green", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
data.add(new RGBColorSpace(name, "Blue", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
}
data.add(new RGBColorSpace(name, "Red", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
data.add(new RGBColorSpace(name, "Green", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
data.add(new RGBColorSpace(name, "Blue", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
}
}
}
return data;
}
public static List<RGBColorSpace> all() {
List<RGBColorSpace> data = new ArrayList<>();
data.addAll(standard());
data.addAll(adapted());
return data;
}
public static List<RGBColorSpace> all(int scale) {
List<RGBColorSpace> data = RGBColorSpace.all();
for (RGBColorSpace d : data) {
d.scaleValues(scale);
}
return data;
}
public static StringTable allTable() {
try {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("ColorSpace"),
Languages.message("Illuminant"), Languages.message("AdaptationAlgorithm"), Languages.message("PrimaryColor"),
Languages.message("TristimulusX"), Languages.message("TristimulusY"), Languages.message("TristimulusZ"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"),
Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ")
));
StringTable table = new StringTable(names, Languages.message("RGBPrimaries"));
List<RGBColorSpace> data = all(8);
for (RGBColorSpace d : data) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
d.colorSpaceName, d.illuminantName, d.adaptAlgorithm, d.colorName,
d.X + "", d.Y + "", d.Z + "",
d.getNormalizedX() + "", d.getNormalizedY() + "", d.getNormalizedZ() + "",
d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + ""
));
table.add(row);
}
return table;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(name(cs));
}
return names;
}
public static String name(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return CIERGB;
case ECIRGB:
return ECIRGB;
case AdobeRGB:
return AdobeRGB;
case AppleRGB:
return AppleRGB;
case sRGB:
return sRGB;
case PALRGB:
return PALRGB;
case NTSCRGB:
return NTSCRGB;
case ColorMatchRGB:
return ColorMatchRGB;
case ProPhotoRGB:
return ProPhotoRGB;
case SMPTECRGB:
return SMPTECRGB;
}
} catch (Exception e) {
}
return null;
}
public static ColorSpaceType type(String name) {
try {
if (CIERGB.equals(name)) {
return ColorSpaceType.CIERGB;
} else if (ECIRGB.equals(name)) {
return ColorSpaceType.ECIRGB;
} else if (AdobeRGB.equals(name)) {
return ColorSpaceType.AdobeRGB;
} else if (AppleRGB.equals(name)) {
return ColorSpaceType.AppleRGB;
} else if (sRGB.equals(name)) {
return ColorSpaceType.sRGB;
} else if (PALRGB.equals(name)) {
return ColorSpaceType.PALRGB;
} else if (NTSCRGB.equals(name)) {
return ColorSpaceType.NTSCRGB;
} else if (ColorMatchRGB.equals(name)) {
return ColorSpaceType.ColorMatchRGB;
} else if (ProPhotoRGB.equals(name)) {
return ColorSpaceType.ProPhotoRGB;
} else if (SMPTECRGB.equals(name)) {
return ColorSpaceType.SMPTECRGB;
}
} catch (Exception e) {
}
return null;
}
// Based on CIE 1931 2 degree observer
public static double[][] primariesNormalized(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0];
n[0][1] = p[0][1];
n[0][2] = 1 - p[0][0] - p[0][1];
n[1][0] = p[1][0];
n[1][1] = p[1][1];
n[1][2] = 1 - p[1][0] - p[1][1];
n[2][0] = p[2][0];
n[2][1] = p[2][1];
n[2][2] = 1 - p[2][0] - p[2][1];
return n;
}
public static double[][] primariesNormalized(String csName) {
return primariesNormalized(type(csName));
}
public static double[][] primariesRelative(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0] / p[0][1];
n[0][1] = 1;
n[0][2] = (1 - p[0][0] - p[0][1]) / p[0][1];
n[1][0] = p[1][0] / p[1][1];
n[1][1] = 1;
n[1][2] = (1 - p[1][0] - p[1][1]) / p[1][1];
n[2][0] = p[2][0] / p[2][1];
n[2][1] = 1;
n[2][2] = (1 - p[2][0] - p[2][1]) / p[2][1];
return n;
}
public static double[][] primariesRelative(String csName) {
return primariesRelative(type(csName));
}
public static double[][] primariesTristimulus(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0] * p[0][2] / p[0][1];
n[0][1] = p[0][2];
n[0][2] = (1 - p[0][0] - p[0][1]) * p[0][2] / p[0][1];
n[1][0] = p[1][0] * p[1][2] / p[1][1];
n[1][1] = p[1][2];
n[1][2] = (1 - p[1][0] - p[1][1]) * p[1][2] / p[1][1];
n[2][0] = p[2][0] * p[2][2] / p[2][1];
n[2][1] = p[2][2];
n[2][2] = (1 - p[2][0] - p[2][1]) * p[2][2] / p[2][1];
return n;
}
public static double[][] primariesTristimulus(String csName) {
return primariesTristimulus(type(csName));
}
public static double[][] primaries(String csName) {
return primaries(type(csName));
}
public static double[][] primaries(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return CIEPrimariesE;
case ECIRGB:
return ECIPrimariesD50;
case AdobeRGB:
return AdobePrimariesD65;
case AppleRGB:
return ApplePrimariesD65;
case sRGB:
return sRGBPrimariesD65;
case PALRGB:
return PALPrimariesD65;
case NTSCRGB:
return NTSCPrimariesC;
case ColorMatchRGB:
return ColorMatchPrimariesD50;
case ProPhotoRGB:
return ProPhotoPrimariesD50;
case SMPTECRGB:
return SMPTECPrimariesD65;
}
} catch (Exception e) {
}
return null;
}
public static double[] whitePoint(String csName) {
return whitePoint(type(csName));
}
public static double[] whitePoint(ColorSpaceType colorSpaceType) {
double[] xy = whitePointXY(colorSpaceType);
return CIEDataTools.relative(xy[0], xy[1], 1 - xy[0] - xy[1]);
}
public static double[] whitePointXY(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return Illuminant.Illuminant1931E;
case ECIRGB:
return Illuminant.Illuminant1931D50;
case AdobeRGB:
return Illuminant.Illuminant1931D65;
case AppleRGB:
return Illuminant.Illuminant1931D65;
case sRGB:
return Illuminant.Illuminant1931D65;
case PALRGB:
return Illuminant.Illuminant1931D65;
case NTSCRGB:
return Illuminant.Illuminant1931C;
case ColorMatchRGB:
return Illuminant.Illuminant1931D50;
case ProPhotoRGB:
return Illuminant.Illuminant1931D50;
case SMPTECRGB:
return Illuminant.Illuminant1931D65;
}
} catch (Exception e) {
}
return null;
}
public static double[][] whitePointMatrix(ColorSpaceType colorSpaceType) {
return DoubleMatrixTools.columnVector(whitePoint(colorSpaceType));
}
public static String illuminantName(String csName) {
return illuminantType(type(csName)) + " - " + Illuminant.Observer.CIE1931;
}
public static IlluminantType illuminantType(String csName) {
return illuminantType(type(csName));
}
public static IlluminantType illuminantType(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return IlluminantType.E;
case ECIRGB:
return IlluminantType.D50;
case AdobeRGB:
return IlluminantType.D65;
case AppleRGB:
return IlluminantType.D65;
case sRGB:
return IlluminantType.D65;
case PALRGB:
return IlluminantType.D65;
case NTSCRGB:
return IlluminantType.C;
case ColorMatchRGB:
return IlluminantType.D50;
case ProPhotoRGB:
return IlluminantType.D50;
case SMPTECRGB:
return IlluminantType.D65;
}
} catch (Exception e) {
}
return null;
}
public static double[][] primariesAdapted(ColorSpaceType cs,
IlluminantType targetIlluminantType, Observer targetObserver,
ChromaticAdaptationAlgorithm algorithm) {
double[][] primaries = primariesTristimulus(cs);
IlluminantType ci = illuminantType(cs);
double[] red = ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[] green = ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[] blue = ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[][] adpated = {red, green, blue};
return adpated;
}
public static Object primariesAdapted(ColorSpaceType cs,
double[][] targetWhitePoint, ChromaticAdaptationAlgorithm algorithm,
int scale, boolean isDemo) {
double[][] primaries = primariesTristimulus(cs);
double[][] sourceWhitePoint = whitePointMatrix(cs);
return primariesAdapted(primaries, sourceWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
}
public static Object primariesAdapted(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
double[][] adaptMatrix;
String adaptString = null;
Map<String, Object> adapt = null;
if (DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
adapt = new HashMap<>();
adapt.put("procedure", Languages.message("NeedNotAdaptChromatic"));
adapt.put("matrix", DoubleMatrixTools.identityDouble(3));
adapt.put("adaptedPrimaries", primaries);
return adapt;
} else {
return primaries;
}
}
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
adapt = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) adapt.get("adpatMatrix");
adaptString = (String) adapt.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] sourceRed = DoubleMatrixTools.columnVector(primaries[0]);
double[][] adaptedRed = DoubleMatrixTools.multiply(adaptMatrix, sourceRed);
double[][] sourceGreen = DoubleMatrixTools.columnVector(primaries[1]);
double[][] adaptedGreen = DoubleMatrixTools.multiply(adaptMatrix, sourceGreen);
double[][] sourceBlue = DoubleMatrixTools.columnVector(primaries[2]);
double[][] adaptedBlue = DoubleMatrixTools.multiply(adaptMatrix, sourceBlue);
double[][] adaptedPrimaries = {
DoubleMatrixTools.columnValues(adaptedRed, 0),
DoubleMatrixTools.columnValues(adaptedGreen, 0),
DoubleMatrixTools.columnValues(adaptedBlue, 0)
};
if (scale >= 0) {
adaptedPrimaries = DoubleMatrixTools.scale(adaptedPrimaries, scale);
} else {
scale = 8;
}
if (isDemo) {
String s = "";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptationMatrix") + " aaaaaaaaaaaaa\n\n";
s += adaptString + "\n";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n";
s += "\nsourceRed = \n";
s += DoubleMatrixTools.print(sourceRed, 20, scale);
s += "\nadaptedRed = M * sourceRed = \n";
s += DoubleMatrixTools.print(adaptedRed, 20, scale);
s += "\nsourceGreen = \n";
s += DoubleMatrixTools.print(sourceGreen, 20, scale);
s += "\nadaptedGreen = M * sourceGreen = \n";
s += DoubleMatrixTools.print(adaptedGreen, 20, scale);
s += "\nsourceBlue = \n";
s += DoubleMatrixTools.print(sourceBlue, 20, scale);
s += "\nadaptedBlue = M * sourceBlue = \n";
s += DoubleMatrixTools.print(adaptedBlue, 20, scale);
s += "\nadaptedPrimaries = \n";
s += DoubleMatrixTools.print(adaptedPrimaries, 20, scale);
adapt.put("procedure", s);
adapt.put("adaptedPrimaries", adaptedPrimaries);
return adapt;
} else {
return adaptedPrimaries;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Gamma
*/
public static GammaType gamma(String csName) {
return gammaType(type(csName));
}
public static GammaType gammaType(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
case AdobeRGB:
case PALRGB:
case NTSCRGB:
case SMPTECRGB:
return GammaType.Gamma22;
case ECIRGB:
return GammaType.GammaL;
case AppleRGB:
case ColorMatchRGB:
case ProPhotoRGB:
return GammaType.Gamma18;
case sRGB:
return GammaType.GammaSRGB;
}
} catch (Exception e) {
}
return null;
}
public static String gammaName(GammaType gammaType) {
try {
switch (gammaType) {
case GammaSRGB:
return "sRGB";
case Gamma22:
return "2.2";
case Gamma18:
return "1.8";
case GammaL:
return "L*";
}
} catch (Exception e) {
}
return null;
}
public static String gammaName(String colorSpaceName) {
try {
if (RGBColorSpace.sRGB.equals(colorSpaceName)) {
return "sRGB";
} else if (RGBColorSpace.ECIRGB.equals(colorSpaceName)) {
return "L*";
} else if (RGBColorSpace.CIERGB.equals(colorSpaceName)
|| RGBColorSpace.AdobeRGB.equals(colorSpaceName)
|| RGBColorSpace.PALRGB.equals(colorSpaceName)
|| RGBColorSpace.NTSCRGB.equals(colorSpaceName)
|| RGBColorSpace.SMPTECRGB.equals(colorSpaceName)) {
return "2.2";
} else if (RGBColorSpace.AppleRGB.equals(colorSpaceName)
|| RGBColorSpace.ColorMatchRGB.equals(colorSpaceName)
|| RGBColorSpace.ProPhotoRGB.equals(colorSpaceName)) {
return "1.8";
}
} catch (Exception e) {
}
return null;
}
public static double gamma(double Gramma, double v) {
if (v <= 0.0) {
return 0.0;
} else {
return Math.pow(v, 1 / Gramma);
}
}
public static double gamma22(double v) {
return gamma(2.19921875, v);
}
public static double gamma18(double v) {
return gamma(1.8, v);
}
public static double gammaSRGB(double v) {
if (v <= 0.0031308) {
return v * 12.92;
} else {
return 1.055 * Math.pow(v, 1d / 2.4) - 0.055;
}
}
/*
Linear
*/
public static double linearColor(double Gramma, double v) {
if (v <= 0.0) {
return 0.0;
} else {
return Math.pow(v, Gramma);
}
}
public static double linear22(double v) {
return linearColor(2.19921875, v);
}
public static double linear18(double v) {
return linearColor(1.8, v);
}
public static double linearSRGB(double v) {
if (v <= 0.04045) {
return v / 12.92;
} else {
return Math.pow((v + 0.055) / 1.055, 2.4);
}
}
/*
Data
*/
// http://www.eci.org/en/downloads
// {r,g,b}{x, y, Y}
public static enum ColorSpaceType {
CIERGB, ECIRGB, AdobeRGB, AppleRGB, sRGB, PALRGB, NTSCRGB, ColorMatchRGB,
ProPhotoRGB, SMPTECRGB
}
public static enum GammaType {
Linear, Gamma22, Gamma18, GammaSRGB, GammaL
}
public static String CIERGB = "CIE RGB";
public static String ECIRGB = "ECI RGB v2";
public static String AdobeRGB = "Adobe RGB (1998)";
public static String AppleRGB = "Apple RGB";
public static String sRGB = "sRGB";
public static String PALRGB = "PAL/SECAM RGB";
public static String NTSCRGB = "NTSC RGB";
public static String ColorMatchRGB = "ColorMatch RGB";
public static String ProPhotoRGB = "ProPhoto RGB";
public static String SMPTECRGB = "SMPTE-C RGB";
public static double[][] CIEPrimariesE = {
{0.7350, 0.2650, 0.176204},
{0.2740, 0.7170, 0.812985},
{0.1670, 0.0090, 0.010811}
};
public static double[][] ECIPrimariesD50 = {
{0.670000, 0.330000, 0.320250},
{0.210000, 0.710000, 0.602071},
{0.140000, 0.080000, 0.077679}
};
public static double[][] sRGBPrimariesD65 = {
{0.6400, 0.3300, 0.212656},
{0.3000, 0.6000, 0.715158},
{0.1500, 0.0600, 0.072186}
};
public static double[][] AdobePrimariesD65 = {
{0.6400, 0.3300, 0.297361},
{0.2100, 0.7100, 0.627355},
{0.1500, 0.0600, 0.075285}
};
public static double[][] ApplePrimariesD65 = {
{0.6250, 0.3400, 0.244634},
{0.2800, 0.5950, 0.672034},
{0.1550, 0.0700, 0.083332}
};
public static double[][] PALPrimariesD65 = {
{0.6400, 0.3300, 0.222021},
{0.2900, 0.6000, 0.706645},
{0.1500, 0.0600, 0.071334}
};
public static double[][] NTSCPrimariesC = {
{0.6700, 0.3300, 0.298839},
{0.2100, 0.7100, 0.586811},
{0.1400, 0.0800, 0.114350}
};
public static double[][] ProPhotoPrimariesD50 = {
{0.734700, 0.265300, 0.288040},
{0.159600, 0.840400, 0.711874},
{0.036600, 0.000100, 0.000086}
};
public static double[][] ColorMatchPrimariesD50 = {
{0.630000, 0.340000, 0.274884},
{0.295000, 0.605000, 0.658132},
{0.150000, 0.075000, 0.066985}
};
public static double[][] SMPTECPrimariesD65 = {
{0.6300, 0.3400, 0.212395},
{0.3100, 0.5950, 0.701049},
{0.1550, 0.0700, 0.086556}
};
//Extra calculated values
public static double[][] CIEPrimariesD50 = {
{0.737385, 0.264518, 0.174658},
{0.266802, 0.718404, 0.824754},
{0.174329, 0.000599, 0.000588}
};
public static double[][] sRGBPrimariesD50 = {
{0.648431, 0.330856, 0.222491},
{0.321152, 0.597871, 0.716888},
{0.155886, 0.066044, 0.060621}
};
public static double[][] AdobePrimariesD50 = {
{0.648431, 0.330856, 0.311114},
{0.230154, 0.701572, 0.625662},
{0.155886, 0.066044, 0.063224}
};
public static double[][] ApplePrimariesD50 = {
{0.634756, 0.340596, 0.255166},
{0.301775, 0.597511, 0.672578},
{0.162897, 0.079001, 0.072256}
};
public static double[][] NTSCPrimariesD50 = {
{0.671910, 0.329340, 0.310889},
{0.222591, 0.710647, 0.591737},
{0.142783, 0.096145, 0.097374}
};
public static double[][] PALPrimariesD50 = {
{0.648431, 0.330856, 0.232289},
{0.311424, 0.599693, 0.707805},
{0.155886, 0.066044, 0.059906}
};
public static double[][] SMPTECPrimariesD50 = {
{0.638852, 0.340194, 0.221685},
{0.331007, 0.592082, 0.703264},
{0.162897, 0.079001, 0.075052}
};
/*
get/set
*/
public String getColorSpaceName() {
return colorSpaceName;
}
public void setColorSpaceName(String colorSpaceName) {
this.colorSpaceName = colorSpaceName;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public String getIlluminantName() {
return illuminantName;
}
public void setIlluminantName(String illuminantName) {
this.illuminantName = illuminantName;
}
public String getAdaptAlgorithm() {
return adaptAlgorithm;
}
public void setAdaptAlgorithm(String adaptAlgorithm) {
this.adaptAlgorithm = adaptAlgorithm;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ChromaticityDiagram.java | alpha/MyBox/src/main/java/mara/mybox/color/ChromaticityDiagram.java | package mara.mybox.color;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-17 9:57:29
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ChromaticityDiagram {
private int width = 1300, height = 1300;
private int margins = 60, ruler = 10, each = 5, grid = each * ruler;
private BufferedImage image;
private Color gridColor = new Color(0.9f, 0.9f, 0.9f), rulerColor = Color.LIGHT_GRAY,
textColor, bgColor;
private Graphics2D g;
private int stepH = (height - margins * 2) / grid;
private int stepW = (width - margins * 2) / grid;
private int startH = margins + stepH, startW = margins + stepW;
private int endH = stepH * grid + margins;
private int endW = stepW * grid + margins;
private int fontSize = 20;
private Font dataFont, commentsFont;
private int dotSize = 6;
private boolean isLine, show2Degree, show10Degree, showDataSource;
private File dataSourceFile;
private String dataSourceTexts;
private String title;
private LinkedHashMap<DataType, Boolean> show;
private double calculateX = -1, calculateY = -1;
private Color calculateColor;
public static enum DataType {
Grid, CIE2Degree, CIE10Degree, CIEDataSource, Calculate, Wave, CIELines, ECILines, sRGBLines, AdobeLines, AppleLines,
PALLines, NTSCLines, ColorMatchLines, ProPhotoLines, SMPTECLines, WhitePoints
}
public ChromaticityDiagram() {
show = new LinkedHashMap();
}
public static ChromaticityDiagram create() {
return new ChromaticityDiagram();
}
/*
Diagram
*/
public BufferedImage drawData(LinkedHashMap<DataType, Boolean> show) {
this.show = show;
return drawData();
}
public BufferedImage drawData() {
try {
// MyBoxLog.console(width + " " + height);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g = image.createGraphics();
if (AppVariables.ImageHints != null) {
g.addRenderingHints(AppVariables.ImageHints);
}
if (bgColor != null) {
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
}
if (fontSize <= 0) {
fontSize = 20;
}
dataFont = new Font(null, Font.PLAIN, fontSize);
commentsFont = new Font(null, Font.BOLD, fontSize + 8);
if (Color.BLACK.equals(bgColor)) {
textColor = Color.WHITE;
} else {
textColor = Color.BLACK;
}
// Title / Bottom
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setComposite(ac);
if (title == null) {
title = Languages.message("ChromaticityDiagram");
}
g.setFont(commentsFont);
g.setColor(textColor);
g.drawString(title, margins + 400, 50);
g.setFont(dataFont);
g.drawString(Languages.message("ChromaticityDiagramComments"), 20, endH + 55);
backGround();
outlines();
whitePoints();
primariesLines();
calculate();
g.dispose();
return image;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
private void backGround() {
try {
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setComposite(ac);
BasicStroke stroke;
stroke = new BasicStroke(2);
g.setStroke(stroke);
g.setFont(dataFont);
if (show.get(DataType.Grid)) {
g.setColor(gridColor);
for (int i = 0; i < grid; ++i) {
int h = startH + i * stepH;
g.drawLine(margins, h, endW, h);
int w = startW + i * stepW;
g.drawLine(w, margins, w, endH);
}
g.setColor(rulerColor);
for (int i = 0; i < ruler; ++i) {
int h = margins + i * stepH * each;
g.drawLine(margins, h, endW, h);
int w = margins + i * stepW * each;
g.drawLine(w, margins, w, endH);
}
}
g.setColor(textColor);
g.drawLine(margins, margins, margins, endH);
g.drawLine(margins, endH, endW, endH);
for (int i = 0; i < ruler; ++i) {
int h = margins + (i + 1) * stepH * each;
g.drawString("0." + (9 - i), 10, h + 10);
int w = margins + i * stepW * each;
g.drawString("0." + i, w - 10, endH + 30);
}
g.drawString("1.0", endW - 15, endH + 30);
g.drawString("1.0", 10, margins);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void outlines() {
try {
List<CIEData> data;
CIEData cieData = new CIEData();
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
if (show.get(DataType.CIE2Degree)) {
data = CIEDataTools.cie1931Observer2Degree1nmData(cs);
outline(data, Languages.message("CIE1931Observer2Degree"), 535, textColor);
}
if (show.get(DataType.CIE10Degree)) {
data = CIEDataTools.cie1964Observer10Degree1nmData(cs);
if (show.get(DataType.CIE2Degree)) {
outline(data, Languages.message("CIE1964Observer10Degree"), 525, Color.BLUE);
} else {
outline(data, Languages.message("CIE1964Observer10Degree"), 525, textColor);
}
}
if (show.get(DataType.CIEDataSource)) {
data = null;
if (dataSourceTexts != null && !dataSourceTexts.isEmpty()) {
data = CIEDataTools.read(dataSourceTexts);
} else if (dataSourceFile != null) {
data = CIEDataTools.read(dataSourceFile, cs);
}
if (data != null) {
if (show.get(DataType.CIE2Degree) || show.get(DataType.CIE10Degree)) {
outline(data, Languages.message("InputtedData"), 520, Color.RED);
} else {
outline(data, Languages.message("InputtedData"), 520, textColor);
}
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void outline(List<CIEData> data, String name, int markWave, Color waveColor) {
try {
if (data == null || data.isEmpty()) {
return;
}
Color pColor;
int dotSizeHalf = dotSize / 2;
BasicStroke strokeSized = new BasicStroke(dotSize);
BasicStroke stroke1 = new BasicStroke(1);
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y, wave, lastx = -1, lasty = -1;
double[] srgb;
for (CIEData d : data) {
wave = d.getWaveLength();
x = (int) Math.round(margins + dataW * d.getNormalizedX());
y = (int) Math.round(endH - dataH * d.getNormalizedY());
srgb = d.getChannels();
if (srgb == null) {
srgb = CIEDataTools.sRGB65(d);
}
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
g.setColor(pColor);
g.setStroke(stroke1);
if (isLine) {
if (lastx >= 0 && lasty >= 0) {
g.setStroke(strokeSized);
g.drawLine(lastx, lasty, x, y);
} else {
g.fillRect(x - dotSizeHalf, y - dotSizeHalf, dotSize, dotSize);
}
lastx = x;
lasty = y;
} else {
g.fillRect(x - dotSizeHalf, y - dotSizeHalf, dotSize, dotSize);
}
if (wave == markWave) {
g.setColor(waveColor);
g.drawLine(x, y, x + 300, y + markWave - 560);
g.drawString(name, x + 310, y + markWave - 560);
}
if (show.get(DataType.Wave)) {
if (wave == 360 || wave == 830 || wave == 460) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
} else if (wave > 470 && wave < 620) {
if (wave % 5 == 0) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
}
} else if (wave >= 620 && wave <= 640) {
if (wave % 10 == 0) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
}
}
} else {
}
}
// Bottom line
CIEData d1 = data.get(0);
CIEData d2 = data.get(data.size() - 1);
double x1 = d1.getNormalizedX(), x2 = d2.getNormalizedX();
double y1 = d1.getNormalizedY(), y2 = d2.getNormalizedY();
colorLine(x1, y1, x2, y2);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void whitePoints() {
if (!show.get(DataType.WhitePoints)) {
return;
}
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y;
g.setFont(dataFont);
g.setColor(textColor);
BasicStroke stroke1 = new BasicStroke(1);
g.setStroke(stroke1);
double[] xy = Illuminant.Illuminant1931A;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("A", x + 10, y + 5);
xy = Illuminant.Illuminant1931D50;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D50", x + 10, y + 5);
xy = Illuminant.Illuminant1931C;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("C", x + 10, y + 15);
xy = Illuminant.Illuminant1931E;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("E", x + 10, y + 10);
xy = Illuminant.Illuminant1931D65;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D65", x - 40, y);
xy = Illuminant.Illuminant1931D55;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D55", x - 30, y - 10);
}
private void primariesLines() {
if (show == null) {
return;
}
for (DataType name : show.keySet()) {
if (!show.get(name)) {
continue;
}
switch (name) {
case CIELines:
primariesLines(RGBColorSpace.CIERGB, RGBColorSpace.CIEPrimariesD50, 150, 15);
break;
case ECILines:
primariesLines(RGBColorSpace.ECIRGB, RGBColorSpace.ECIPrimariesD50, 150, -40);
break;
case sRGBLines:
primariesLines(RGBColorSpace.sRGB, RGBColorSpace.sRGBPrimariesD50, 260, 0);
break;
case AdobeLines:
primariesLines(RGBColorSpace.AdobeRGB, RGBColorSpace.AdobePrimariesD50, 180, 30);
break;
case AppleLines:
primariesLines(RGBColorSpace.AppleRGB, RGBColorSpace.ApplePrimariesD50, 220, -70);
break;
case PALLines:
primariesLines(RGBColorSpace.PALRGB, RGBColorSpace.PALPrimariesD50, 220, 20);
break;
case NTSCLines:
primariesLines(RGBColorSpace.NTSCRGB, RGBColorSpace.NTSCPrimariesD50, 130, -30);
break;
case ColorMatchLines:
primariesLines(RGBColorSpace.ColorMatchRGB, RGBColorSpace.ColorMatchPrimariesD50, 200, -30);
break;
case ProPhotoLines:
primariesLines(RGBColorSpace.ProPhotoRGB, RGBColorSpace.ProPhotoPrimariesD50, 150, 0);
break;
case SMPTECLines:
primariesLines(RGBColorSpace.SMPTECRGB, RGBColorSpace.SMPTECPrimariesD50, 150, 0);
break;
}
}
}
private void primariesLines(String name, double[][] xy, int xOffset, int yOffset) {
if (image == null || g == null) {
return;
}
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setComposite(ac);
BasicStroke stroke;
stroke = new BasicStroke(3);
g.setStroke(stroke);
g.setFont(dataFont);
int x, y;
int dataW = width - margins * 2, dataH = height - margins * 2;
// vertexes
g.setColor(Color.RED);
x = (int) Math.round(margins + dataW * xy[0][0]);
y = (int) Math.round(endH - dataH * xy[0][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Red"), x + 10, y);
g.drawLine(x, y, x + xOffset, y + yOffset);
g.drawString(name, x + xOffset + 10, y + yOffset + 10);
g.setColor(Color.GREEN);
x = (int) Math.round(margins + dataW * xy[1][0]);
y = (int) Math.round(endH - dataH * xy[1][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Green"), x + 10, y);
g.drawLine(x, y, x + xOffset, y + yOffset);
g.drawString(name, x + xOffset + 10, y + yOffset + 10);
g.setColor(Color.BLUE);
x = (int) Math.round(margins + dataW * xy[2][0]);
y = (int) Math.round(endH - dataH * xy[2][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Blue"), x + 10, y);
// lines
colorLine(xy[1][0], xy[1][1], xy[0][0], xy[0][1]);
colorLine(xy[2][0], xy[2][1], xy[0][0], xy[0][1]);
colorLine(xy[2][0], xy[2][1], xy[1][0], xy[1][1]);
}
private void colorLine(double ix1, double iy1, double ix2, double iy2) {
if (image == null || g == null || ix1 == ix2) {
return;
}
double x1, y1, x2, y2;
if (ix1 < ix2) {
x1 = ix1;
y1 = iy1;
x2 = ix2;
y2 = iy2;
} else {
x1 = ix2;
y1 = iy2;
x2 = ix1;
y2 = iy1;
}
Color pColor;
BasicStroke strokeSized = new BasicStroke(dotSize);
BasicStroke stroke1 = new BasicStroke(1);
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y, halfDot = dotSize / 2, lastx = -1, lasty = -1;
double ratio = (y2 - y1) / (x2 - x1);
double step = (x2 - x1) / 100;
double[] srgb;
for (double bx = x1 + step; bx < x2; bx += step) {
double by = (bx - x1) * ratio + y1;
double bz = 1 - bx - by;
double[] relativeXYZ = CIEDataTools.relative(bx, by, bz);
srgb = CIEColorSpace.XYZd50toSRGBd65(relativeXYZ);
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
g.setColor(pColor);
x = (int) Math.round(margins + dataW * bx);
y = (int) Math.round(endH - dataH * by);
if (isLine) {
if (lastx >= 0 && lasty >= 0) {
g.setStroke(strokeSized);
g.drawLine(lastx, lasty, x, y);
} else {
g.setStroke(stroke1);
g.fillRect(x - halfDot, y - halfDot, dotSize, dotSize);
}
lastx = x;
lasty = y;
} else {
g.setStroke(stroke1);
g.fillRect(x - halfDot, y - halfDot, dotSize, dotSize);
}
}
}
private void calculate() {
if (!show.get(DataType.Calculate)
|| calculateX < 0 || calculateX > 1
|| calculateY <= 0 || calculateY > 1) {
return;
}
int dataW = width - margins * 2, dataH = height - margins * 2;
BasicStroke stroke1 = new BasicStroke(1);
g.setStroke(stroke1);
double z = 1 - calculateX - calculateY;
if (z < 0 || z > 1) {
return;
}
Color pColor = calculateColor;
if (pColor == null) {
double[] relativeXYZ = CIEDataTools.relative(calculateX, calculateY, z);
double[] srgb = CIEColorSpace.XYZd50toSRGBd65(relativeXYZ);
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
}
int x = (int) Math.round(margins + dataW * calculateX);
int y = (int) Math.round(endH - dataH * calculateY);
g.setColor(pColor);
g.fillOval(x - 10, y - 10, 20, 20);
g.setFont(dataFont);
g.setColor(textColor);
g.drawString(Languages.message("CalculatedValues"), x + 15, y + 5);
}
/*
get/set
*/
public int getWidth() {
return width;
}
public ChromaticityDiagram setWidth(int width) {
this.width = width;
return this;
}
public int getHeight() {
return height;
}
public ChromaticityDiagram setHeight(int height) {
this.height = height;
return this;
}
public int getMargins() {
return margins;
}
public void setMargins(int margins) {
this.margins = margins;
}
public int getRuler() {
return ruler;
}
public void setRuler(int ruler) {
this.ruler = ruler;
}
public int getEach() {
return each;
}
public void setEach(int each) {
this.each = each;
}
public int getGrid() {
return grid;
}
public void setGrid(int grid) {
this.grid = grid;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public Color getGridColor() {
return gridColor;
}
public void setGridColor(Color gridColor) {
this.gridColor = gridColor;
}
public Color getRulerColor() {
return rulerColor;
}
public void setRulerColor(Color rulerColor) {
this.rulerColor = rulerColor;
}
public Color getTextColor() {
return textColor;
}
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
public int getStepH() {
return stepH;
}
public void setStepH(int stepH) {
this.stepH = stepH;
}
public int getStepW() {
return stepW;
}
public void setStepW(int stepW) {
this.stepW = stepW;
}
public int getStartH() {
return startH;
}
public void setStartH(int startH) {
this.startH = startH;
}
public int getStartW() {
return startW;
}
public void setStartW(int startW) {
this.startW = startW;
}
public int getEndH() {
return endH;
}
public void setEndH(int endH) {
this.endH = endH;
}
public int getEndW() {
return endW;
}
public void setEndW(int endW) {
this.endW = endW;
}
public Font getDataFont() {
return dataFont;
}
public void setDataFont(Font dataFont) {
this.dataFont = dataFont;
}
public Graphics2D getG() {
return g;
}
public void setG(Graphics2D g) {
this.g = g;
}
public Font getCommnetsFont() {
return commentsFont;
}
public void setCommnetsFont(Font commnetsFont) {
this.commentsFont = commnetsFont;
}
public int getDotSize() {
return dotSize;
}
public ChromaticityDiagram setDotSize(int dotSize) {
this.dotSize = dotSize;
return this;
}
public boolean isIsLine() {
return isLine;
}
public ChromaticityDiagram setIsLine(boolean isLine) {
this.isLine = isLine;
return this;
}
public boolean isShow2Degree() {
return show2Degree;
}
public void setShow2Degree(boolean show2Degree) {
this.show2Degree = show2Degree;
}
public boolean isShow10Degree() {
return show10Degree;
}
public void setShow10Degree(boolean show10Degree) {
this.show10Degree = show10Degree;
}
public File getDataSourceFile() {
return dataSourceFile;
}
public void setDataSourceFile(File dataSourceFile) {
this.dataSourceFile = dataSourceFile;
}
public boolean isShowDataSource() {
return showDataSource;
}
public void setShowDataSource(boolean showDataSource) {
this.showDataSource = showDataSource;
}
public void setTitle(String title) {
this.title = title;
}
public LinkedHashMap<DataType, Boolean> getShow() {
return show;
}
public void setShow(LinkedHashMap<DataType, Boolean> show) {
this.show = show;
}
public Color getBgColor() {
return bgColor;
}
public ChromaticityDiagram setBgColor(Color bgColor) {
this.bgColor = bgColor;
return this;
}
public double getCalculateX() {
return calculateX;
}
public ChromaticityDiagram setCalculateX(double calculateX) {
this.calculateX = calculateX;
return this;
}
public double getCalculateY() {
return calculateY;
}
public ChromaticityDiagram setCalculateY(double calculateY) {
this.calculateY = calculateY;
return this;
}
public Color getCalculateColor() {
return calculateColor;
}
public ChromaticityDiagram setCalculateColor(Color calculateColor) {
this.calculateColor = calculateColor;
return this;
}
public String getDataSourceTexts() {
return dataSourceTexts;
}
public ChromaticityDiagram setDataSourceTexts(String dataSourceTexts) {
this.dataSourceTexts = dataSourceTexts;
return this;
}
public int getFontSize() {
return fontSize;
}
public ChromaticityDiagram setFontSize(int fontSize) {
this.fontSize = fontSize;
return this;
}
public Font getCommentsFont() {
return commentsFont;
}
public void setCommentsFont(Font commentsFont) {
this.commentsFont = commentsFont;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/Illuminant.java | alpha/MyBox/src/main/java/mara/mybox/color/Illuminant.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*
* Reference: * http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
* http://brucelindbloom.com/index.html?ColorCalculator.html
* https://ww2.mathworks.cn/help/images/ref/whitepoint.html
* http://www.thefullwiki.org/Standard_illuminant
* http://www.wikizero.biz/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvU3RhbmRhcmRfaWxsdW1pbmFudA
*/
public class Illuminant extends CIEData {
public IlluminantType type;
public Observer observer;
public String name, comments, whitePointValues;
public int temperature;
public Illuminant(IlluminantType illuminant) {
this.type = illuminant;
init1931(illuminant);
}
public Illuminant(IlluminantType illuminant, Observer observer) {
this.type = illuminant;
if (observer == null || observer == Observer.CIE1931) {
init1931(illuminant);
} else if (observer == Observer.CIE1964) {
init1964(illuminant);
}
}
public final void init1931(IlluminantType illuminant) {
this.type = illuminant;
switch (illuminant) {
case A:
init("A", Observer.CIE1931, Illuminant1931A, Illuminant1931A_Temperature, Illuminant1931A_Comments);
break;
case B:
init("B", Observer.CIE1931, Illuminant1931B, Illuminant1931B_Temperature, Illuminant1931B_Comments);
break;
case C:
init("C", Observer.CIE1931, Illuminant1931C, Illuminant1931C_Temperature, Illuminant1931C_Comments);
break;
case D50:
init("D50", Observer.CIE1931, Illuminant1931D50, Illuminant1931D50_Temperature, Illuminant1931D50_Comments);
break;
case D55:
init("D55", Observer.CIE1931, Illuminant1931D55, Illuminant1931D55_Temperature, Illuminant1931D55_Comments);
break;
case D65:
init("D65", Observer.CIE1931, Illuminant1931D65, Illuminant1931D65_Temperature, Illuminant1931D65_Comments);
break;
case D75:
init("D75", Observer.CIE1931, Illuminant1931D75, Illuminant1931D75_Temperature, Illuminant1931D75_Comments);
break;
case E:
init("E", Observer.CIE1931, Illuminant1931E, Illuminant1931E_Temperature, Illuminant1931E_Comments);
break;
case F1:
init("F1", Observer.CIE1931, Illuminant1931F1, Illuminant1931F1_Temperature, Illuminant1931F1_Comments);
break;
case F2:
init("F2", Observer.CIE1931, Illuminant1931F2, Illuminant1931F2_Temperature, Illuminant1931F2_Comments);
break;
case F3:
init("F3", Observer.CIE1931, Illuminant1931F3, Illuminant1931F3_Temperature, Illuminant1931F3_Comments);
break;
case F4:
init("F4:", Observer.CIE1931, Illuminant1931F4, Illuminant1931F4_Temperature, Illuminant1931F4_Comments);
break;
case F5:
init("F5", Observer.CIE1931, Illuminant1931F5, Illuminant1931F5_Temperature, Illuminant1931F5_Comments);
break;
case F6:
init("F6", Observer.CIE1931, Illuminant1931F6, Illuminant1931F6_Temperature, Illuminant1931F6_Comments);
break;
case F7:
init("F7", Observer.CIE1931, Illuminant1931F7, Illuminant1931F7_Temperature, Illuminant1931F7_Comments);
break;
case F8:
init("F8", Observer.CIE1931, Illuminant1931F8, Illuminant1931F8_Temperature, Illuminant1931F8_Comments);
break;
case F9:
init("F9", Observer.CIE1931, Illuminant1931F9, Illuminant1931F9_Temperature, Illuminant1931F9_Comments);
break;
case F10:
init("F10", Observer.CIE1931, Illuminant1931F10, Illuminant1931F10_Temperature, Illuminant1931F10_Comments);
break;
case F11:
init("F11", Observer.CIE1931, Illuminant1931F11, Illuminant1931F11_Temperature, Illuminant1931F11_Comments);
break;
case F12:
init("F12", Observer.CIE1931, Illuminant1931F12, Illuminant1931F12_Temperature, Illuminant1931F12_Comments);
break;
case ICC:
init("ICC", Observer.CIE1931, IlluminantICC, IlluminantICC_Temperature, IlluminantICC_Comments);
break;
}
}
public final void init1964(IlluminantType illuminant) {
this.type = illuminant;
switch (illuminant) {
case A:
init("A", Observer.CIE1964, Illuminant1964A, Illuminant1964A_Temperature, Illuminant1964A_Comments);
break;
case B:
init("B", Observer.CIE1964, Illuminant1964B, Illuminant1964B_Temperature, Illuminant1964B_Comments);
break;
case C:
init("C", Observer.CIE1964, Illuminant1964C, Illuminant1964C_Temperature, Illuminant1964C_Comments);
break;
case D50:
init("D50", Observer.CIE1964, Illuminant1964D50, Illuminant1964D50_Temperature, Illuminant1964D50_Comments);
break;
case D55:
init("D55", Observer.CIE1964, Illuminant1964D55, Illuminant1964D55_Temperature, Illuminant1964D55_Comments);
break;
case D65:
init("D65", Observer.CIE1964, Illuminant1964D65, Illuminant1964D65_Temperature, Illuminant1964D65_Comments);
break;
case D75:
init("D75", Observer.CIE1964, Illuminant1964D75, Illuminant1964D75_Temperature, Illuminant1964D75_Comments);
break;
case E:
init("E", Observer.CIE1964, Illuminant1964E, Illuminant1964E_Temperature, Illuminant1964E_Comments);
break;
case F1:
init("F1", Observer.CIE1964, Illuminant1964F1, Illuminant1964F1_Temperature, Illuminant1964F1_Comments);
break;
case F2:
init("F2", Observer.CIE1964, Illuminant1964F2, Illuminant1964F2_Temperature, Illuminant1964F2_Comments);
break;
case F3:
init("F3", Observer.CIE1964, Illuminant1964F3, Illuminant1964F3_Temperature, Illuminant1964F3_Comments);
break;
case F4:
init("F4:", Observer.CIE1964, Illuminant1964F4, Illuminant1964F4_Temperature, Illuminant1964F4_Comments);
break;
case F5:
init("F5", Observer.CIE1964, Illuminant1964F5, Illuminant1964F5_Temperature, Illuminant1964F5_Comments);
break;
case F6:
init("F6", Observer.CIE1964, Illuminant1964F6, Illuminant1964F6_Temperature, Illuminant1964F6_Comments);
break;
case F7:
init("F7", Observer.CIE1964, Illuminant1964F7, Illuminant1964F7_Temperature, Illuminant1964F7_Comments);
break;
case F8:
init("F8", Observer.CIE1964, Illuminant1964F8, Illuminant1964F8_Temperature, Illuminant1964F8_Comments);
break;
case F9:
init("F9", Observer.CIE1964, Illuminant1964F9, Illuminant1964F9_Temperature, Illuminant1964F9_Comments);
break;
case F10:
init("F10", Observer.CIE1964, Illuminant1964F10, Illuminant1964F10_Temperature, Illuminant1964F10_Comments);
break;
case F11:
init("F11", Observer.CIE1964, Illuminant1964F11, Illuminant1964F11_Temperature, Illuminant1964F11_Comments);
break;
case F12:
init("F12", Observer.CIE1964, Illuminant1964F12, Illuminant1964F12_Temperature, Illuminant1964F12_Comments);
break;
case ICC:
init("ICC", Observer.CIE1964, Illuminant1964D50, IlluminantICC_Temperature, IlluminantICC_Comments);
break;
}
}
public final void init(String name, Observer observer,
double[] xy, int temperature, String comments) {
this.name = name;
this.observer = observer;
this.temperature = temperature;
if (comments != null) {
this.comments = Languages.message(comments);
}
setNormalziedXY(xy);
}
public double[][] whitePoint() {
return DoubleMatrixTools.columnVector(relativeX, relativeY, relativeZ);
}
/*
Static methods
*/
public static List<Illuminant> all() {
List<Illuminant> data = new ArrayList<>();
for (IlluminantType type : IlluminantType.values()) {
data.add(new Illuminant(type, Observer.CIE1931));
data.add(new Illuminant(type, Observer.CIE1964));
}
return data;
}
public static List<Illuminant> all(int scale) {
List<Illuminant> data = all();
for (Illuminant d : data) {
d.scaleValues(scale);
}
return data;
}
public static List<String> names() {
List<String> data = new ArrayList<>();
for (IlluminantType type : IlluminantType.values()) {
data.add(type + " - " + Observer.CIE1931);
data.add(type + " - " + Observer.CIE1964);
}
return data;
}
public static StringTable table(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("Illuminant"), Languages.message("Observer"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"),
Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ"),
Languages.message("ColorTemperature"), Languages.message("Comments")
));
StringTable table = new StringTable(names, Languages.message("Illuminants"));
for (Illuminant d : all(8)) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(d.name, d.observer.name(),
d.getNormalizedX() + "", d.getNormalizedY() + "", d.getNormalizedZ() + "",
d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + "",
d.temperature + "", d.comments
));
table.add(row);
}
return table;
}
public static String string() {
StringBuilder s = new StringBuilder();
String sp = "\t";
s.append(Languages.message("Illuminant")).append(sp).append(Languages.message("Observer")).append(sp).
append(Languages.message("NormalizedX")).append(sp).append(Languages.message("NormalizedY")).append(sp).append(Languages.message("NormalizedZ")).append(sp).
append(Languages.message("RelativeX")).append(sp).append(Languages.message("RelativeY")).append(sp).append(Languages.message("RelativeZ")).append(sp).
append(Languages.message("ColorTemperature")).append(sp).append(Languages.message("Comments")).append("\n");
List<Illuminant> data = all(8);
for (Illuminant d : data) {
s.append(d.name).append(sp).append(d.observer).append(sp).
append(d.getNormalizedX()).append(sp).
append(d.getNormalizedY()).append(sp).
append(d.getNormalizedZ()).append(sp).
append(d.getRelativeX()).append(sp).
append(d.getRelativeY()).append(sp).
append(d.getRelativeZ()).append(sp).
append(d.temperature).append("K").append(sp).
append(d.comments).append(sp).append("\n");
}
return s.toString();
}
public static IlluminantType type(String name) {
switch (name) {
case "A":
return IlluminantType.A;
case "B":
return IlluminantType.B;
case "C":
return IlluminantType.C;
case "D50":
return IlluminantType.D50;
case "D55":
return IlluminantType.D55;
case "D65":
return IlluminantType.D65;
case "D75":
return IlluminantType.D75;
case "E":
return IlluminantType.E;
case "F1":
return IlluminantType.F1;
case "F2":
return IlluminantType.F2;
case "F3":
return IlluminantType.F3;
case "F4":
return IlluminantType.F4;
case "F5":
return IlluminantType.F5;
case "F6":
return IlluminantType.F6;
case "F7":
return IlluminantType.F7;
case "F8":
return IlluminantType.F8;
case "F9":
return IlluminantType.F9;
case "F10":
return IlluminantType.F10;
case "F11":
return IlluminantType.F11;
case "F12":
return IlluminantType.F12;
case "ICC":
return IlluminantType.ICC;
}
return null;
}
public static double[] whitePoint1931(IlluminantType illuminant) {
switch (illuminant) {
case A:
return Illuminant1931A;
case B:
return Illuminant1931B;
case C:
return Illuminant1931C;
case D50:
return Illuminant1931D50;
case D55:
return Illuminant1931D55;
case D65:
return Illuminant1931D65;
case D75:
return Illuminant1931D65;
case E:
return Illuminant1931E;
case F1:
return Illuminant1931F1;
case F2:
return Illuminant1931F2;
case F3:
return Illuminant1931F3;
case F4:
return Illuminant1931F4;
case F5:
return Illuminant1931F5;
case F6:
return Illuminant1931F6;
case F7:
return Illuminant1931F7;
case F8:
return Illuminant1931F8;
case F9:
return Illuminant1931F9;
case F10:
return Illuminant1931F10;
case F11:
return Illuminant1931F11;
case F12:
return Illuminant1931F12;
case ICC:
return IlluminantICC;
}
return null;
}
public static double[] whitePoint1964(IlluminantType illuminant) {
switch (illuminant) {
case A:
return Illuminant1964A;
case B:
return Illuminant1964B;
case C:
return Illuminant1964C;
case D50:
return Illuminant1964D50;
case D55:
return Illuminant1964D55;
case D65:
return Illuminant1964D65;
case D75:
return Illuminant1964D65;
case E:
return Illuminant1964E;
case F1:
return Illuminant1964F1;
case F2:
return Illuminant1964F2;
case F3:
return Illuminant1964F3;
case F4:
return Illuminant1964F4;
case F5:
return Illuminant1964F5;
case F6:
return Illuminant1964F6;
case F7:
return Illuminant1964F7;
case F8:
return Illuminant1964F8;
case F9:
return Illuminant1964F9;
case F10:
return Illuminant1964F10;
case F11:
return Illuminant1964F11;
case F12:
return Illuminant1964F12;
case ICC:
return Illuminant1964D50;
}
return null;
}
/*
Data
*/
public static enum IlluminantType {
A, B, C, D50, D55, D65, D75, E, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, ICC
}
public static enum Observer {
CIE1931, CIE1964
}
// x, y
public static String Illuminant1931A_Comments = "IlluminantAComments";
public static int Illuminant1931A_Temperature = 2856;
public static double[] Illuminant1931A = {
0.44757, 0.40745
};
public static String Illuminant1931B_Comments = "IlluminantBComments";
public static int Illuminant1931B_Temperature = 4874;
public static double[] Illuminant1931B = {
0.34842, 0.35161
};
public static String Illuminant1931C_Comments = "IlluminantCComments";
public static int Illuminant1931C_Temperature = 6774;
public static double[] Illuminant1931C = {
0.31006, 0.31616
};
public static String Illuminant1931D50_Comments = "IlluminantD50Comments";
public static int Illuminant1931D50_Temperature = 5003;
public static double[] Illuminant1931D50 = {
0.34567, 0.35850
};
public static String Illuminant1931D55_Comments = "IlluminantD55Comments";
public static int Illuminant1931D55_Temperature = 5503;
public static double[] Illuminant1931D55 = {
0.33242, 0.34743
};
public static String Illuminant1931D65_Comments = "IlluminantD65Comments";
public static int Illuminant1931D65_Temperature = 6504;
public static double[] Illuminant1931D65 = {
0.31271, 0.32902
};
public static String Illuminant1931D75_Comments = "IlluminantD75Comments";
public static int Illuminant1931D75_Temperature = 7504;
public static double[] Illuminant1931D75 = {
0.29902, 0.31485
};
public static String Illuminant1931E_Comments = "IlluminantEComments";
public static int Illuminant1931E_Temperature = 5454;
public static double[] Illuminant1931E = {
0.33333, 0.33333
};
public static String Illuminant1931F1_Comments = "IlluminantF1Comments";
public static int Illuminant1931F1_Temperature = 6430;
public static double[] Illuminant1931F1 = {
0.31310, 0.33727
};
public static String Illuminant1931F2_Comments = "IlluminantF2Comments";
public static int Illuminant1931F2_Temperature = 4230;
public static double[] Illuminant1931F2 = {
0.37208, 0.37529
};
public static String Illuminant1931F3_Comments = "IlluminantF3Comments";
public static int Illuminant1931F3_Temperature = 3450;
public static double[] Illuminant1931F3 = {
0.40910, 0.39430
};
public static String Illuminant1931F4_Comments = "IlluminantF4Comments";
public static int Illuminant1931F4_Temperature = 2940;
public static double[] Illuminant1931F4 = {
0.44018, 0.40329
};
public static String Illuminant1931F5_Comments = "IlluminantF5Comments";
public static int Illuminant1931F5_Temperature = 6350;
public static double[] Illuminant1931F5 = {
0.31379, 0.34531
};
public static String Illuminant1931F6_Comments = "IlluminantF6Comments";
public static int Illuminant1931F6_Temperature = 4150;
public static double[] Illuminant1931F6 = {
0.37790, 0.38835
};
public static String Illuminant1931F7_Comments = "IlluminantF7Comments";
public static int Illuminant1931F7_Temperature = 6500;
public static double[] Illuminant1931F7 = {
0.31292, 0.32933
};
public static String Illuminant1931F8_Comments = "IlluminantF8Comments";
public static int Illuminant1931F8_Temperature = 5000;
public static double[] Illuminant1931F8 = {
0.34588, 0.35875
};
public static String Illuminant1931F9_Comments = "IlluminantF9Comments";
public static int Illuminant1931F9_Temperature = 4150;
public static double[] Illuminant1931F9 = {
0.37417, 0.37281
};
public static String Illuminant1931F10_Comments = "IlluminantF10Comments";
public static int Illuminant1931F10_Temperature = 5000;
public static double[] Illuminant1931F10 = {
0.34609, 0.35986
};
public static String Illuminant1931F11_Comments = "IlluminantF11Comments";
public static int Illuminant1931F11_Temperature = 4000;
public static double[] Illuminant1931F11 = {
0.38052, 0.37713
};
public static String Illuminant1931F12_Comments = "IlluminantF12Comments";
public static int Illuminant1931F12_Temperature = 3000;
public static double[] Illuminant1931F12 = {
0.43695, 0.40441
};
public static String IlluminantICC_Comments = "IlluminantICCComments";
public static int IlluminantICC_Temperature = 5003;
public static double[] IlluminantICC = {
0.34570, 0.35854
};
public static String Illuminant1964A_Comments = "IlluminantAComments";
public static int Illuminant1964A_Temperature = 2856;
public static double[] Illuminant1964A = {
0.45117, 0.40594
};
public static String Illuminant1964B_Comments = "IlluminantBComments";
public static int Illuminant1964B_Temperature = 4874;
public static double[] Illuminant1964B = {
0.3498, 0.3527
};
public static String Illuminant1964C_Comments = "IlluminantCComments";
public static int Illuminant1964C_Temperature = 6774;
public static double[] Illuminant1964C = {
0.31039, 0.31905
};
public static String Illuminant1964D50_Comments = "IlluminantD50Comments";
public static int Illuminant1964D50_Temperature = 5003;
public static double[] Illuminant1964D50 = {
0.34773, 0.35952
};
public static String Illuminant1964D55_Comments = "IlluminantD55Comments";
public static int Illuminant1964D55_Temperature = 5503;
public static double[] Illuminant1964D55 = {
0.33411, 0.34877
};
public static String Illuminant1964D65_Comments = "IlluminantD65Comments";
public static int Illuminant1964D65_Temperature = 6504;
public static double[] Illuminant1964D65 = {
0.31382, 0.33100
};
public static String Illuminant1964D75_Comments = "IlluminantD75Comments";
public static int Illuminant1964D75_Temperature = 7504;
public static double[] Illuminant1964D75 = {
0.29968, 0.31740
};
public static String Illuminant1964E_Comments = "IlluminantEComments";
public static int Illuminant1964E_Temperature = 5454;
public static double[] Illuminant1964E = {
0.33333, 0.33333
};
public static String Illuminant1964F1_Comments = "IlluminantF1Comments";
public static int Illuminant1964F1_Temperature = 6430;
public static double[] Illuminant1964F1 = {
0.31811, 0.33559
};
public static String Illuminant1964F2_Comments = "IlluminantF2Comments";
public static int Illuminant1964F2_Temperature = 4230;
public static double[] Illuminant1964F2 = {
0.37925, 0.36733
};
public static String Illuminant1964F3_Comments = "IlluminantF3Comments";
public static int Illuminant1964F3_Temperature = 3450;
public static double[] Illuminant1964F3 = {
0.41761, 0.38324
};
public static String Illuminant1964F4_Comments = "IlluminantF4Comments";
public static int Illuminant1964F4_Temperature = 2940;
public static double[] Illuminant1964F4 = {
0.44920, 0.39074
};
public static String Illuminant1964F5_Comments = "IlluminantF5Comments";
public static int Illuminant1964F5_Temperature = 6350;
public static double[] Illuminant1964F5 = {
0.31975, 0.34246
};
public static String Illuminant1964F6_Comments = "IlluminantF6Comments";
public static int Illuminant1964F6_Temperature = 4150;
public static double[] Illuminant1964F6 = {
0.38660, 0.37847
};
public static String Illuminant1964F7_Comments = "IlluminantF7Comments";
public static int Illuminant1964F7_Temperature = 6500;
public static double[] Illuminant1964F7 = {
0.31569, 0.32960
};
public static String Illuminant1964F8_Comments = "IlluminantF8Comments";
public static int Illuminant1964F8_Temperature = 5000;
public static double[] Illuminant1964F8 = {
0.34902, 0.35939
};
public static String Illuminant1964F9_Comments = "IlluminantF9Comments";
public static int Illuminant1964F9_Temperature = 4150;
public static double[] Illuminant1964F9 = {
0.37829, 0.37045
};
public static String Illuminant1964F10_Comments = "IlluminantF10Comments";
public static int Illuminant1964F10_Temperature = 5000;
public static double[] Illuminant1964F10 = {
0.35090, 0.35444
};
public static String Illuminant1964F11_Comments = "IlluminantF11Comments";
public static int Illuminant1964F11_Temperature = 4000;
public static double[] Illuminant1964F11 = {
0.38541, 0.37123
};
public static String Illuminant1964F12_Comments = "IlluminantF12Comments";
public static int Illuminant1964F12_Temperature = 3000;
public static double[] Illuminant1964F12 = {
0.44256, 0.39717
};
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public IlluminantType getType() {
return type;
}
public void setType(IlluminantType type) {
this.type = type;
}
public Observer getObserver() {
return observer;
}
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getWhitePointValues() {
return whitePointValues;
}
public void setWhitePointValues(String whitePointValues) {
this.whitePointValues = whitePointValues;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/CIEData.java | alpha/MyBox/src/main/java/mara/mybox/color/CIEData.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ColorSpace;
import static mara.mybox.tools.DoubleTools.scale;
/**
* @Author Mara
* @CreateDate 2019-5-20 18:51:37
* @License Apache License Version 2.0
*/
public class CIEData {
public int waveLength; // nm
public double X, Y, Z; // tristimulus values in 0~1.
public double normalizedX, normalizedY, normalizedZ; // x + y + z = 1
public double relativeX, relativeY, relativeZ; // y = 1;
public double red = -1, green = -1, blue = -1; // sRGB
public int redi = -1, greeni = -1, bluei = -1; // sRGB integer
public ColorSpace colorSpace;
public double[] channels;
public int scale = 8;
public CIEData() {
}
public CIEData(int waveLength, double X, double Y, double Z) {
this.waveLength = waveLength;
setTristimulusValues(X, Y, Z);
}
public CIEData(int waveLength, double X, double Y, double Z, ColorSpace cs) {
this.waveLength = waveLength;
setTristimulusValues(X, Y, Z);
convert(cs);
}
public CIEData(double x, double y) {
setxy(x, y);
}
public CIEData(Color color) {
double[] xyz = SRGB.SRGBtoXYZd50(color);
setTristimulusValues(xyz[0], xyz[1], xyz[2]);
}
public CIEData(javafx.scene.paint.Color color) {
double[] xyz = SRGB.SRGBtoXYZd50(new Color((float) color.getRed(), (float) color.getGreen(), (float) color.getBlue()));
setTristimulusValues(xyz[0], xyz[1], xyz[2]);
}
public final void setTristimulusValues(double X, double Y, double Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
double[] xyz = CIEDataTools.normalize(X, Y, Z);
this.normalizedX = xyz[0];
this.normalizedY = xyz[1];
this.normalizedZ = xyz[2];
xyz = CIEDataTools.relative(X, Y, Z);
this.relativeX = xyz[0];
this.relativeY = xyz[1];
this.relativeZ = xyz[2];
}
public final void setxy(double x, double y) {
setxyY(x, y, 1.0);
}
public final void setxyY(double[] xyY) {
setxyY(xyY[0], xyY[1], xyY[2]);
}
public final void setxyY(double x, double y, double Y) {
this.normalizedX = x;
this.normalizedY = y;
this.normalizedZ = 1 - x - y;
this.X = x * Y / y;
this.Y = Y;
this.Z = (1 - x - y) * Y / y;
this.relativeX = x / y;
this.relativeY = 1.0;
this.relativeZ = (1 - x - y) / y;
}
public final void setRelativeXYZ(double[] XYZ) {
setRelativeXYZ(XYZ[0], XYZ[1], XYZ[2]);
}
public final void setRelativeXYZ(double X, double Y, double Z) {
this.relativeX = X;
this.relativeY = Y;
this.relativeZ = Z;
double[] xyz = CIEDataTools.normalize(X, Y, Z);
this.normalizedX = xyz[0];
this.normalizedY = xyz[1];
this.normalizedZ = xyz[2];
this.X = relativeX * 100;
this.Y = relativeY * 100;
this.Z = relativeZ * 100;
}
public final void setNormalziedXY(double[] xy) {
setNormalziedXY(xy[0], xy[1]);
}
public final void setNormalziedXY(double x, double y) {
this.normalizedX = x;
this.normalizedY = y;
this.normalizedZ = 1 - x - y;
this.relativeX = x / y;
this.relativeY = 1;
this.relativeZ = (1 - x - y) / y;
this.X = relativeX * 100;
this.Y = relativeY * 100;
this.Z = relativeZ * 100;
}
public final double[] convert(ColorSpace cs) {
if (cs == null) {
channels = CIEDataTools.CIERGB(this);
} else {
colorSpace = cs;
if (cs.isCS_sRGB()) {
channels = CIEDataTools.sRGB65(this);
} else {
channels = CIEDataTools.convert(cs, this);
}
}
return channels;
}
public void scaleValues() {
scaleValues(this.scale);
}
public void scaleValues(int scale) {
this.scale = scale;
X = scale(X, scale);
Y = scale(Y, scale);
Z = scale(Z, scale);
normalizedX = scale(normalizedX, scale);
normalizedY = scale(normalizedY, scale);
normalizedZ = scale(normalizedZ, scale);
relativeX = scale(relativeX, scale);
relativeY = scale(relativeY, scale);
relativeZ = scale(relativeZ, scale);
if (channels != null) {
for (int i = 0; i < channels.length; ++i) {
channels[i] = scale(channels[i], scale);
}
}
}
/*
get/set
*/
public double getX() {
return X;
}
public void setX(double X) {
this.X = X;
}
public double getY() {
return Y;
}
public void setY(double Y) {
this.Y = Y;
}
public double getZ() {
return Z;
}
public void setZ(double Z) {
this.Z = Z;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public int getWaveLength() {
return waveLength;
}
public void setWaveLength(int waveLength) {
this.waveLength = waveLength;
}
public double getNormalizedX() {
return normalizedX;
}
public void setNormalizedX(double normalizedX) {
this.normalizedX = normalizedX;
}
public double getNormalizedY() {
return normalizedY;
}
public void setNormalizedY(double normalizedY) {
this.normalizedY = normalizedY;
}
public double getNormalizedZ() {
return normalizedZ;
}
public void setNormalizedZ(double normalizedZ) {
this.normalizedZ = normalizedZ;
}
public double getRed() {
if (red == -1) {
red = channels[0];
}
return red;
}
public void setRed(double red) {
this.red = red;
}
public double getGreen() {
if (green == -1) {
green = channels[1];
}
return green;
}
public void setGreen(double green) {
this.green = green;
}
public double getBlue() {
if (blue == -1) {
blue = channels[2];
}
return blue;
}
public void setBlue(double blue) {
this.blue = blue;
}
public int getRedi() {
if (redi == -1) {
redi = (int) Math.round(255 * channels[0]);
}
return redi;
}
public void setRedi(int redi) {
this.redi = redi;
}
public int getGreeni() {
if (greeni == -1) {
greeni = (int) Math.round(255 * channels[1]);
}
return greeni;
}
public void setGreeni(int greeni) {
this.greeni = greeni;
}
public int getBluei() {
if (bluei == -1) {
bluei = (int) Math.round(255 * channels[2]);
}
return bluei;
}
public void setBluei(int bluei) {
this.bluei = bluei;
}
public double getRelativeX() {
return relativeX;
}
public void setRelativeX(double relativeX) {
this.relativeX = relativeX;
}
public double getRelativeY() {
return relativeY;
}
public void setRelativeY(double relativeY) {
this.relativeY = relativeY;
}
public double getRelativeZ() {
return relativeZ;
}
public void setRelativeZ(double relativeZ) {
this.relativeZ = relativeZ;
}
public ColorSpace getColorSpace() {
return colorSpace;
}
public void setColorSpace(ColorSpace colorSpace) {
this.colorSpace = colorSpace;
}
public double[] getChannels() {
return channels;
}
public void setChannels(double[] channels) {
this.channels = channels;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/IccTagType.java | alpha/MyBox/src/main/java/mara/mybox/color/IccTagType.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccProfile.toBytes;
import mara.mybox.tools.ByteTools;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.bytesToUshort;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.shortToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2019-5-7 20:41:49
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccTagType {
// All in Big-Endian
public static String[][] IlluminantTypes = {
{"0", "Unknown"},
{"1", "D50"},
{"2", "D65"},
{"3", "D93"},
{"4", "F2"},
{"5", "D55"},
{"6", "A"},
{"7", "Equi-Power (E)"},
{"8 ", "F8"}
};
public static String[][] ObserverTypes = {
{"0", "Unknown"},
{"1", "CIE 1931 2 Degree Observer"},
{"2", "CIE 1964 10 Degree Observer"},};
public static String[][] GeometryTypes = {
{"0", "Unknown"},
{"1", "0°:45° or 45°:0°"},
{"2", "0°:d or d:0°"},};
/*
Decode values of Base Types
*/
public static int bytes4ToInt(byte[] b) {
return b[3] & 0xFF
| (b[2] & 0xFF) << 8
| (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
}
public static int uInt8Number(byte b) {
return b & 0xFF;
}
public static double u8Fixed8Number(byte[] b) {
int integer = b[0] & 0xFF;
double fractional = (b[1] & 0xFF) / 256d;
return integer + fractional;
}
public static double s15Fixed16Number(byte[] b) {
int integer = b[1] & 0xFF | b[0] << 8;
double fractional = (b[3] & 0xFF | (b[2] & 0xFF) << 8) / 65536d;
return integer + fractional;
}
public static double u16Fixed16Number(byte[] b) {
int integer = b[1] & 0xFF | (b[0] & 0xFF) << 8;
double fractional = (b[3] & 0xFF | (b[2] & 0xFF) << 8) / 65536d;
return integer + fractional;
}
public static int uInt16Number(byte[] b) {
int integer = b[1] & 0xFF | (b[0] & 0xFF) << 8;
return integer;
}
public static long uInt32Number(byte[] b) {
long v = b[3] & 0xFF
| (b[2] & 0xFF) << 8
| (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
return v;
}
public static String dateTimeString(byte[] v) {
if (v == null || v.length != 12) {
return "";
}
String d = bytesToUshort(subBytes(v, 0, 2)) + "-"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 2, 2)), 2) + "-"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 4, 2)), 2) + " "
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 6, 2)), 2) + ":"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 8, 2)), 2) + ":"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 10, 2)), 2);
return d;
}
public static double[] XYZNumber(byte[] v) {
if (v == null || v.length != 12) {
return null;
}
double[] xyz = new double[3];
xyz[0] = IccTagType.s15Fixed16Number(subBytes(v, 0, 4));
xyz[1] = IccTagType.s15Fixed16Number(subBytes(v, 4, 4));
xyz[2] = IccTagType.s15Fixed16Number(subBytes(v, 8, 4));
return xyz;
}
public static List<String> illuminantTypes() {
List<String> types = new ArrayList<>();
for (String[] item : IlluminantTypes) {
types.add(item[1]);
}
return types;
}
public static String illuminantType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : IlluminantTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
public static List<String> observerTypes() {
List<String> types = new ArrayList<>();
for (String[] item : ObserverTypes) {
types.add(item[1]);
}
return types;
}
public static String observerType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : ObserverTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
public static List<String> geometryTypes() {
List<String> types = new ArrayList<>();
for (String[] item : GeometryTypes) {
types.add(item[1]);
}
return types;
}
public static String geometryType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : GeometryTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
/*
Decode value of Tag Type
*/
public static double[][] XYZ(byte[] bytes) {
if (bytes == null || bytes.length < 12
|| !"XYZ ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int size = (bytes.length - 8) / 12;
double[][] xyzArray = new double[size][3];
for (int i = 0; i < size; ++i) {
double[] xyz = XYZNumber(subBytes(bytes, 8 + i * 12, 12));
xyzArray[i] = xyz;
}
return xyzArray;
}
public static String dateTime(byte[] bytes) {
if (bytes == null || bytes.length < 20
|| !"dtim".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
return dateTimeString(subBytes(bytes, 8, 12));
}
public static String signature(byte[] bytes) {
if (bytes == null || !"sig ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String value = new String(subBytes(bytes, 8, 4));
return value;
}
public static String text(byte[] bytes) {
if (bytes == null || !"text".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String value = new String(subBytes(bytes, 8, bytes.length - 8));
return value;
}
public static Map<String, Object> multiLocalizedUnicode(byte[] bytes) {
if (bytes == null || !"desc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String signature = new String(subBytes(bytes, 0, 4));
switch (signature) {
case "desc":
return textDescription(bytes);
case "mluc":
return multiLocalizedUnicodes(bytes);
default:
return null;
}
}
// REVISION of ICC.1:1998-09
public static Map<String, Object> textDescription(byte[] bytes) {
if (bytes == null || !"desc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
int AsciiLength = (int) uInt32Number(subBytes(bytes, 8, 4));
values.put("AsciiLength", AsciiLength);
String value = new String(subBytes(bytes, 12, AsciiLength));
values.put("Ascii", value);
try {
values.put("UnicodeCode", bytesToInt(subBytes(bytes, 12 + AsciiLength, 4)));
int UnicodeLength = (int) uInt32Number(subBytes(bytes, 16 + AsciiLength, 4));
values.put("UnicodeLength", UnicodeLength);
if (UnicodeLength == 0) {
values.put("Unicode", "");
} else {
values.put("Unicode", new String(subBytes(bytes, 20 + AsciiLength, UnicodeLength * 2), "UTF-16"));
}
values.put("ScriptCodeCode", uInt16Number(subBytes(bytes, 20 + AsciiLength + UnicodeLength * 2, 2)));
int ScriptCodeLength = uInt8Number(bytes[22 + AsciiLength + UnicodeLength * 2]);
values.put("ScriptCodeLength", ScriptCodeLength);
if (ScriptCodeLength == 0) {
values.put("ScriptCode", "");
} else {
byte[] scriptCode = subBytes(bytes, 23 + AsciiLength + UnicodeLength * 2, ScriptCodeLength);
values.put("ScriptCode", new String(scriptCode));
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return values;
}
// REVISION of ICC.1:2004-10
public static Map<String, Object> multiLocalizedUnicodes(byte[] bytes) {
MyBoxLog.debug(new String(subBytes(bytes, 0, 4)));
if (bytes == null || !"mluc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
int num = (int) uInt32Number(subBytes(bytes, 8, 4));
int size = (int) uInt32Number(subBytes(bytes, 12, 4));
values.put("number", num);
values.put("size", size);
MyBoxLog.debug(num + " " + size);
int offset = 16;
for (int i = 0; i < num; ++i) {
int languageCode = uInt16Number(subBytes(bytes, offset + i * 12, 2));
values.put("languageCode" + i, languageCode);
int countryCode = uInt16Number(subBytes(bytes, offset + i * 12 + 2, 2));
values.put("countryCode" + i, countryCode);
int length = (int) uInt32Number(subBytes(bytes, offset + i * 12 + 4, 4));
values.put("length" + i, length);
int ioffset = (int) uInt32Number(subBytes(bytes, offset + i * 12 + 8, 4));
values.put("offset" + i, ioffset);
MyBoxLog.debug(languageCode + " " + countryCode + " " + length + " " + ioffset);
}
// try {
// values.put("UnicodeCode", bytesToInt(subBytes(bytes, 12 + AsciiLength, 4)));
// int UnicodeLength = (int) uInt32Number(subBytes(bytes, 16 + AsciiLength, 4));
// MyBoxLog.debug(UnicodeLength);
// values.put("UnicodeLength", UnicodeLength);
// if (UnicodeLength == 0) {
// values.put("Unicode", "");
// } else {
// values.put("Unicode", new String(subBytes(bytes, 20 + AsciiLength, UnicodeLength)));
// }
//
// values.put("ScriptCodeCode", uInt16Number(subBytes(bytes, 20 + AsciiLength + UnicodeLength, 2)));
// int ScriptCodeLength = uInt8Number(bytes[22 + AsciiLength + UnicodeLength]);
// MyBoxLog.debug(ScriptCodeLength);
// values.put("ScriptCodeLength", ScriptCodeLength);
// if (ScriptCodeLength == 0) {
// values.put("ScriptCode", "");
// } else {
// byte[] scriptCode = subBytes(bytes, 23 + AsciiLength + UnicodeLength, ScriptCodeLength);
// values.put("ScriptCode", new String(scriptCode));
// }
// } catch (Exception e) {
// MyBoxLog.debug(e);
// }
return values;
}
public static double[] curve(byte[] bytes) {
if (bytes == null || !"curv".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int count = bytesToInt(subBytes(bytes, 8, 4));
double[] values;
switch (count) {
case 0:
values = new double[1];
values[0] = 1.0d;
break;
case 1:
values = new double[1];
values[0] = u8Fixed8Number(subBytes(bytes, 12, 2));
break;
default:
values = new double[count];
for (int i = 0; i < count; ++i) {
values[i] = uInt16Number(subBytes(bytes, 12 + i * 2, 2)) / 65535d;
}
break;
}
return values;
}
public static Map<String, Object> viewingConditions(byte[] bytes) {
if (bytes == null || !"view".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("illuminant", XYZNumber(subBytes(bytes, 8, 12)));
values.put("surround", XYZNumber(subBytes(bytes, 20, 12)));
values.put("illuminantType", illuminantType(subBytes(bytes, 32, 4)));
return values;
}
public static Map<String, Object> measurement(byte[] bytes) {
if (bytes == null || !"meas".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("observer", observerType(subBytes(bytes, 8, 4)));
values.put("tristimulus", XYZNumber(subBytes(bytes, 12, 12)));
values.put("geometry", geometryType(subBytes(bytes, 24, 4)));
values.put("flare", u16Fixed16Number(subBytes(bytes, 28, 4)));
values.put("illuminantType", illuminantType(subBytes(bytes, 32, 4)));
return values;
}
public static double[] s15Fixed16Array(byte[] bytes) {
if (bytes == null || bytes.length < 4
|| !"sf32".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int size = (bytes.length - 8) / 4;
double[] array = new double[size];
for (int i = 0; i < size; ++i) {
double v = IccTagType.s15Fixed16Number(subBytes(bytes, 8 + i * 4, 4));
array[i] = v;
}
return array;
}
public static Map<String, Object> lut(byte[] bytes, boolean normalizedLut) {
if (bytes == null) {
return null;
}
String type = new String(subBytes(bytes, 0, 4));
switch (type) {
case "mft1":
return lut8(bytes, normalizedLut);
case "mft2":
return lut16(bytes, normalizedLut);
case "mAB ":
return lutAToB(bytes, normalizedLut);
default:
return null;
}
}
public static Map<String, Object> lut8(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mft1".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("type", "lut8");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
int GridPointsNumber = uInt8Number(bytes[10]);
values.put("GridPointsNumber", GridPointsNumber);
double e1 = IccTagType.s15Fixed16Number(subBytes(bytes, 12, 4));
values.put("e1", e1);
double e2 = IccTagType.s15Fixed16Number(subBytes(bytes, 16, 4));
values.put("e2", e2);
double e3 = IccTagType.s15Fixed16Number(subBytes(bytes, 20, 4));
values.put("e3", e3);
double e4 = IccTagType.s15Fixed16Number(subBytes(bytes, 24, 4));
values.put("e4", e4);
double e5 = IccTagType.s15Fixed16Number(subBytes(bytes, 28, 4));
values.put("e5", e5);
double e6 = IccTagType.s15Fixed16Number(subBytes(bytes, 32, 4));
values.put("e6", e6);
double e7 = IccTagType.s15Fixed16Number(subBytes(bytes, 36, 4));
values.put("e7", e7);
double e8 = IccTagType.s15Fixed16Number(subBytes(bytes, 40, 4));
values.put("e8", e8);
double e9 = IccTagType.s15Fixed16Number(subBytes(bytes, 44, 4));
values.put("e9", e9);
int offset = 48;
int maxItems = UserConfig.getInt("ICCMaxDecodeNumber", 500);
List<List<Double>> InputTables = new ArrayList<>();
for (int n = 0; n < 256; n++) {
List<Double> InputTable = new ArrayList<>();
for (int i = 0; i < InputChannelsNumber; ++i) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
InputTable.add(v / 255);
} else {
InputTable.add(v);
}
}
InputTables.add(InputTable);
if (InputTables.size() >= maxItems) {
values.put("InputTablesTruncated", true);
break;
}
}
values.put("InputTables", InputTables);
List<List<Double>> CLUTTables = new ArrayList<>();
double dimensionSize = Math.pow(GridPointsNumber, InputChannelsNumber);
for (int i = 0; i < dimensionSize; ++i) {
List<Double> GridPoint = new ArrayList<>();
for (int o = 0; o < OutputChannelsNumber; o++) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
GridPoint.add(v / 255);
} else {
GridPoint.add(v);
}
}
CLUTTables.add(GridPoint);
if (CLUTTables.size() >= maxItems) {
values.put("CLUTTablesTruncated", true);
break;
}
}
values.put("CLUTTables", CLUTTables);
List<List<Double>> OutputTables = new ArrayList<>();
for (int m = 0; m < 256; m++) {
List<Double> OutputTable = new ArrayList<>();
for (int i = 0; i < OutputChannelsNumber; ++i) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
OutputTable.add(v / 255);
} else {
OutputTable.add(v);
}
}
OutputTables.add(OutputTable);
if (OutputTables.size() >= maxItems) {
values.put("OutputTablesTruncated", true);
break;
}
}
values.put("OutputTables", OutputTables);
return values;
} catch (Exception e) {
return null;
}
}
public static Map<String, Object> lut16(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mft2".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("type", "lut16");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
int GridPointsNumber = uInt8Number(bytes[10]);
values.put("GridPointsNumber", GridPointsNumber);
double e1 = IccTagType.s15Fixed16Number(subBytes(bytes, 12, 4));
values.put("e1", e1);
double e2 = IccTagType.s15Fixed16Number(subBytes(bytes, 16, 4));
values.put("e2", e2);
double e3 = IccTagType.s15Fixed16Number(subBytes(bytes, 20, 4));
values.put("e3", e3);
double e4 = IccTagType.s15Fixed16Number(subBytes(bytes, 24, 4));
values.put("e4", e4);
double e5 = IccTagType.s15Fixed16Number(subBytes(bytes, 28, 4));
values.put("e5", e5);
double e6 = IccTagType.s15Fixed16Number(subBytes(bytes, 32, 4));
values.put("e6", e6);
double e7 = IccTagType.s15Fixed16Number(subBytes(bytes, 36, 4));
values.put("e7", e7);
double e8 = IccTagType.s15Fixed16Number(subBytes(bytes, 40, 4));
values.put("e8", e8);
double e9 = IccTagType.s15Fixed16Number(subBytes(bytes, 44, 4));
values.put("e9", e9);
int InputTablesNumber = uInt16Number(subBytes(bytes, 48, 2));
values.put("InputTablesNumber", InputTablesNumber);
int OutputTablesNumber = uInt16Number(subBytes(bytes, 50, 2));
values.put("OutputTablesNumber", OutputTablesNumber);
int offset = 52;
int maxItems = UserConfig.getInt("ICCMaxDecodeNumber", 500);
List<List<Double>> InputTables = new ArrayList<>();
for (int n = 0; n < InputTablesNumber; n++) {
List<Double> InputTable = new ArrayList<>();
for (int i = 0; i < InputChannelsNumber; ++i) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
InputTable.add(v / 65535);
} else {
InputTable.add(v);
}
offset += 2;
}
InputTables.add(InputTable);
if (InputTables.size() >= maxItems) {
values.put("InputTablesTruncated", true);
break;
}
}
values.put("InputTables", InputTables);
List<List<Double>> CLUTTables = new ArrayList<>();
double dimensionSize = Math.pow(GridPointsNumber, InputChannelsNumber);
for (int i = 0; i < dimensionSize; ++i) {
List<Double> GridPoint = new ArrayList<>();
for (int o = 0; o < OutputChannelsNumber; o++) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
GridPoint.add(v / 65535);
} else {
GridPoint.add(v);
}
offset += 2;
}
CLUTTables.add(GridPoint);
if (CLUTTables.size() >= maxItems) {
values.put("CLUTTablesTruncated", true);
break;
}
}
values.put("CLUTTables", CLUTTables);
List<List<Double>> OutputTables = new ArrayList<>();
for (int m = 0; m < OutputTablesNumber; m++) {
List<Double> OutputTable = new ArrayList<>();
for (int i = 0; i < OutputChannelsNumber; ++i) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
OutputTable.add(v / 65535);
} else {
OutputTable.add(v);
}
offset += 2;
}
OutputTables.add(OutputTable);
if (OutputTables.size() >= maxItems) {
values.put("OutputTablesTruncated", true);
break;
}
}
values.put("OutputTables", OutputTables);
return values;
} catch (Exception e) {
return null;
}
}
public static Map<String, Object> lutAToB(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mAB ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("lutAToB", "lutAToB");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
long OffsetBCurve = uInt32Number(subBytes(bytes, 12, 4));
values.put("OffsetBCurve", OffsetBCurve);
long OffsetMatrix = uInt32Number(subBytes(bytes, 16, 4));
values.put("OffsetMatrix", OffsetMatrix);
long OffsetMCurve = uInt32Number(subBytes(bytes, 20, 4));
values.put("OffsetMCurve", OffsetMCurve);
long OffsetCLUT = uInt32Number(subBytes(bytes, 24, 4));
values.put("OffsetCLUT", OffsetCLUT);
long OffsetACurve = uInt32Number(subBytes(bytes, 28, 4));
values.put("OffsetACurve", OffsetACurve);
return values;
} catch (Exception e) {
return null;
}
}
/*
Encode value of Base Type
*/
public static byte[] u8Fixed8Number(double d) {
byte[] bytes = new byte[2];
int integer = (int) d;
bytes[0] = (byte) (integer & 0xFF);
int fractional = (int) Math.round((d - integer) * 256);
bytes[1] = (byte) (fractional & 0xFF);
return bytes;
}
public static byte[] uInt16Number(int d) {
return ByteTools.uShortToBytes(d);
}
public static byte[] s15Fixed16Number(double d) {
byte[] bytes = new byte[4];
short s = (short) d;
byte[] shortBytes = shortToBytes(s);
System.arraycopy(shortBytes, 0, bytes, 0, 2);
int fractional = (int) Math.round((d - s) * 65536);
byte[] fractionalBytes = intToBytes(fractional);
System.arraycopy(fractionalBytes, 2, bytes, 2, 2);
return bytes;
}
public static byte[] u16Fixed16Number(double d) {
byte[] bytes = new byte[4];
int integer = (int) d;
byte[] integerBytes = intToBytes(integer);
System.arraycopy(integerBytes, 2, bytes, 0, 2);
int fractional = (int) Math.round((d - integer) * 65536);
byte[] fractionalBytes = intToBytes(fractional);
System.arraycopy(fractionalBytes, 2, bytes, 2, 2);
return bytes;
}
public static byte[] uInt32Number(long a) {
return new byte[]{
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
public static byte[] dateTimeBytes(String v) {
try {
String d = v.trim();
if (d.length() == 17) {
d = "19" + d;
}
if (d.length() != 19
|| d.indexOf('-') != 4 || d.indexOf('-', 5) != 7
|| d.indexOf(' ') != 10
|| d.indexOf(':') != 13 || d.indexOf(':', 14) != 16) {
return null;
}
byte[] bytes = new byte[12];
int i = Integer.parseInt(d.substring(0, 4));
byte[] vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 0, 2);
i = Integer.parseInt(d.substring(5, 7));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 2, 2);
i = Integer.parseInt(d.substring(8, 10));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 4, 2);
i = Integer.parseInt(d.substring(11, 13));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 6, 2);
i = Integer.parseInt(d.substring(14, 16));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 8, 2);
i = Integer.parseInt(d.substring(17, 19));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 10, 2);
return bytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static double[] XYZNumberDoubles(String values) {
try {
String[] strings = StringTools.splitBySpace(values.replace("\n", " "));
if (strings.length < 3) {
return null;
}
double[] doubles = new double[3];
for (int i = 0; i < doubles.length; ++i) {
doubles[i] = Double.parseDouble(strings[i]);
}
return doubles;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] XYZNumber(String values) {
return XYZNumber(XYZNumberDoubles(values));
}
public static byte[] XYZNumber(double[] xyz) {
byte[] bytes = new byte[12];
byte[] xBytes = s15Fixed16Number(xyz[0]);
System.arraycopy(xBytes, 0, bytes, 0, 4);
byte[] yBytes = s15Fixed16Number(xyz[1]);
System.arraycopy(yBytes, 0, bytes, 0, 4);
byte[] zBytes = s15Fixed16Number(xyz[2]);
System.arraycopy(zBytes, 0, bytes, 8, 4);
return bytes;
}
public static byte[] illuminantType(String value) {
for (String[] item : IlluminantTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
public static byte[] observerType(String value) {
for (String[] item : ObserverTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
public static byte[] geometryType(String value) {
for (String[] item : GeometryTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
/*
Encode value of Tag Type
*/
public static byte[] text(String value) {
try {
byte[] sigBytes = toBytes("text");
byte[] valueBytes = toBytes(value);
byte[] tagBytes = new byte[valueBytes.length + 8];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, valueBytes.length);
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] signature(String value) {
try {
byte[] sigBytes = toBytes("sig ");
byte[] valueBytes = toBytes(value);
byte[] tagBytes = new byte[12];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, Math.min(4, valueBytes.length));
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] dateTime(String value) {
try {
byte[] sigBytes = toBytes("dtim");
byte[] valueBytes = dateTimeBytes(value);
byte[] tagBytes = new byte[20];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, 12);
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static double[][] XYZDoubles(String values) {
try {
String[] strings = StringTools.splitBySpace(values.replace("\n", " "));
if (strings.length % 3 != 0) {
return null;
}
double[][] doubles = new double[strings.length / 3][3];
for (int i = 0; i < doubles.length; ++i) {
doubles[i][0] = Double.parseDouble(strings[i * 3]);
doubles[i][1] = Double.parseDouble(strings[i * 3 + 1]);
doubles[i][2] = Double.parseDouble(strings[i * 3 + 2]);
}
return doubles;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] XYZ(String values) {
return XYZ(XYZDoubles(values));
}
public static byte[] XYZ(double[][] values) {
try {
byte[] sigBytes = toBytes("XYZ ");
byte[] tagBytes = new byte[12 * values.length + 8];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
for (int i = 0; i < values.length; ++i) {
double[] xyz = values[i];
byte[] xyzBytes = XYZNumber(xyz);
System.arraycopy(xyzBytes, 0, tagBytes, 8 + 12 * i, 12);
}
return tagBytes;
} catch (Exception e) {
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/AdobeRGB.java | alpha/MyBox/src/main/java/mara/mybox/color/AdobeRGB.java | package mara.mybox.color;
import static mara.mybox.color.RGBColorSpace.gamma22;
import static mara.mybox.color.RGBColorSpace.linear22;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:14:18
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class AdobeRGB {
public static double linearAdobeRGB(double v) {
return linear22(v);
}
public static double gammaAdobeRGB(double v) {
return gamma22(v);
}
public static double[] gammaAdobeRGB(double[] linearRGB) {
double[] rgb = new double[3];
rgb[0] = gamma22(linearRGB[0]);
rgb[1] = gamma22(linearRGB[1]);
rgb[2] = gamma22(linearRGB[2]);
return rgb;
}
public static double[] AdobeRGBtoXYZ(double[] adobergb) {
double linearRed = linearAdobeRGB(adobergb[0]);
double linearGreen = linearAdobeRGB(adobergb[1]);
double linearBlue = linearAdobeRGB(adobergb[2]);
double[] xyz = new double[3];
xyz[0] = 0.5767309 * linearRed + 0.1855540 * linearGreen + 0.1881852 * linearBlue;
xyz[1] = 0.2973769 * linearRed + 0.6273491 * linearGreen + 0.0752741 * linearBlue;
xyz[2] = 0.0270343 * linearRed + 0.0706872 * linearGreen + 0.9911085 * linearBlue;
return xyz;
}
public static double[] AdobeRGBtoSRGB(double[] adobergb) {
double[] xyz = AdobeRGBtoXYZ(adobergb);
return CIEColorSpace.XYZd65toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ColorBase.java | alpha/MyBox/src/main/java/mara/mybox/color/ColorBase.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @Description
* @License Apache License Version 2.0
*
* Reference http://brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html //
* http://www.easyrgb.com/en/math.php //
* http://www.color.org/registry/index.xalter //
* https://www.w3.org/Graphics/Color/sRGB.html //
* https://ninedegreesbelow.com/photography/xyz-rgb.html //
* https://stackoverflow.com/questions/40017741/mathematical-conversion-srgb-and-adobergb
* https://supportdownloads.adobe.com/detail.jsp?ftpID=3680 //
*/
public class ColorBase {
public static int colorSpaceType(String colorSpaceType) {
int csType = -1;
if (colorSpaceType != null) {
switch (colorSpaceType) {
case "sRGB":
csType = ICC_ColorSpace.CS_sRGB;
break;
case "XYZ":
csType = ICC_ColorSpace.CS_CIEXYZ;
break;
case "PYCC":
csType = ICC_ColorSpace.CS_PYCC;
break;
case "GRAY":
csType = ICC_ColorSpace.CS_GRAY;
break;
case "LINEAR_RGB":
csType = ICC_ColorSpace.CS_LINEAR_RGB;
break;
}
}
return csType;
}
/*
Methods based on JDK
*/
public static String colorSpaceType(int colorType) {
switch (colorType) {
case ColorSpace.TYPE_XYZ:
return "XYZ";
case ColorSpace.TYPE_Lab:
return "Lab";
case ColorSpace.TYPE_Luv:
return "Luv";
case ColorSpace.TYPE_YCbCr:
return "YCbCr";
case ColorSpace.TYPE_Yxy:
return "Yxy";
case ColorSpace.TYPE_RGB:
return "RGB";
case ColorSpace.TYPE_GRAY:
return "GRAY";
case ColorSpace.TYPE_HSV:
return "HSV";
case ColorSpace.TYPE_HLS:
return "HLS";
case ColorSpace.TYPE_CMYK:
return "CMYK";
case ColorSpace.TYPE_CMY:
return "CMY";
case ColorSpace.TYPE_2CLR:
return "2CLR";
case ColorSpace.TYPE_3CLR:
return "3CLR";
case ColorSpace.TYPE_4CLR:
return "4CLR";
case ColorSpace.TYPE_5CLR:
return "5CLR";
case ColorSpace.TYPE_6CLR:
return "6CLR";
case ColorSpace.TYPE_7CLR:
return "CMY";
case ColorSpace.TYPE_8CLR:
return "8CLR";
case ColorSpace.TYPE_9CLR:
return "9CLR";
case ColorSpace.TYPE_ACLR:
return "ACLR";
case ColorSpace.TYPE_BCLR:
return "BCLR";
case ColorSpace.TYPE_CCLR:
return "CCLR";
case ColorSpace.TYPE_DCLR:
return "DCLR";
case ColorSpace.TYPE_ECLR:
return "ECLR";
case ColorSpace.TYPE_FCLR:
return "FCLR";
case ColorSpace.CS_sRGB:
return "sRGB";
case ColorSpace.CS_LINEAR_RGB:
return "LINEAR_RGB";
case ColorSpace.CS_CIEXYZ:
return "CIEXYZ";
case ColorSpace.CS_PYCC:
return "PYCC";
case ColorSpace.CS_GRAY:
return "GRAY";
default:
return "Unknown";
}
}
public static String profileClass(int value) {
switch (value) {
case ICC_Profile.CLASS_INPUT:
return "InputDeviceProfile";
case ICC_Profile.CLASS_DISPLAY:
return "DisplayDeviceProfile";
case ICC_Profile.CLASS_OUTPUT:
return "OutputDeviceProfile";
case ICC_Profile.CLASS_DEVICELINK:
return "DeviceLinkProfile";
case ICC_Profile.CLASS_ABSTRACT:
return "AbstractProfile";
case ICC_Profile.CLASS_COLORSPACECONVERSION:
return "ColorSpaceConversionProfile";
case ICC_Profile.CLASS_NAMEDCOLOR:
return "NamedColorProfile";
default:
return "Unknown";
}
}
public static String profileClassSignature(int value) {
switch (value) {
case ICC_Profile.icSigInputClass:
return "InputDeviceProfile";
case ICC_Profile.icSigDisplayClass:
return "DisplayDeviceProfile";
case ICC_Profile.icSigOutputClass:
return "OutputDeviceProfile";
case ICC_Profile.icSigLinkClass:
return "DeviceLinkProfile";
case ICC_Profile.icSigAbstractClass:
return "AbstractProfile";
case ICC_Profile.icSigColorSpaceClass:
return "ColorSpaceConversionProfile";
case ICC_Profile.icSigNamedColorClass:
return "NamedColorProfile";
default:
return "Unknown";
}
}
public static double[] clipRGB(double[] rgb) {
double[] outputs = new double[rgb.length];
System.arraycopy(rgb, 0, outputs, 0, rgb.length);
// for (int i = 0; i < outputs.length; ++i) {
// if (outputs[i] < 0) {
// for (int j = 0; j < outputs.length; ++j) {
// outputs[j] = outputs[j] - outputs[i];
// }
// }
// }
for (int i = 0; i < outputs.length; ++i) {
if (outputs[i] < 0) {
outputs[i] = 0;
}
if (outputs[i] > 1) {
outputs[i] = 1;
}
}
return outputs;
}
public static double[] array(Color color) {
double[] rgb = new double[3];
rgb[0] = color.getRed() / 255d;
rgb[1] = color.getGreen() / 255d;
rgb[2] = color.getBlue() / 255d;
return rgb;
}
public static float[] array(float r, float g, float b) {
float[] rgb = new float[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static double[] array(double r, double g, double b) {
double[] rgb = new double[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static float[] arrayFloat(Color color) {
float[] rgb = new float[3];
rgb[0] = color.getRed() / 255f;
rgb[1] = color.getGreen() / 255f;
rgb[2] = color.getBlue() / 255f;
return rgb;
}
public static float[] arrayFloat(double r, double g, double b) {
float[] rgb = new float[3];
rgb[0] = (float) r;
rgb[1] = (float) g;
rgb[2] = (float) b;
return rgb;
}
public static float[] arrayFloat(double[] d) {
float[] rgb = new float[3];
rgb[0] = (float) d[0];
rgb[1] = (float) d[1];
rgb[2] = (float) d[2];
return rgb;
}
public static double[] arrayDouble(float r, float g, float b) {
double[] rgb = new double[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static double[] arrayDouble(float[] frgb) {
double[] rgb = new double[3];
rgb[0] = frgb[0];
rgb[1] = frgb[1];
rgb[2] = frgb[2];
return rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/CIEDataTools.java | alpha/MyBox/src/main/java/mara/mybox/color/CIEDataTools.java | package mara.mybox.color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static mara.mybox.color.ColorBase.array;
import static mara.mybox.color.ColorBase.arrayDouble;
import static mara.mybox.color.ColorBase.clipRGB;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-20 18:51:37
* @License Apache License Version 2.0
*/
public class CIEDataTools {
public static double[] CIERGB(CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
double[] outputs = CIEColorSpace.XYZd50toCIERGB(xyz);
return outputs;
}
public static double[][] normalize(double[][] rgb) {
double[][] n = new double[3][3];
n[0] = normalize(rgb[0]);
n[1] = normalize(rgb[1]);
n[2] = normalize(rgb[2]);
return n;
}
public static double[] normalize(double[] XYZ) {
return normalize(XYZ[0], XYZ[1], XYZ[2]);
}
public static double[] normalize(double X, double Y, double Z) {
double[] xyz = new double[3];
double sum = X + Y + Z;
if (sum == 0) {
return array(X, Y, Z);
}
xyz[0] = X / sum;
xyz[1] = Y / sum;
xyz[2] = Z / sum;
return xyz;
}
public static double[][] relative(double[][] rgb) {
double[][] r = new double[3][3];
r[0] = relative(rgb[0]);
r[1] = relative(rgb[1]);
r[2] = relative(rgb[2]);
return r;
}
public static double[] relative(double[] xyz) {
return relative(xyz[0], xyz[1], xyz[2]);
}
public static double[] relative(double x, double y, double z) {
if (y == 0) {
return array(x, y, z);
}
double[] xyz = new double[3];
xyz[0] = x / y;
xyz[1] = 1.0;
xyz[2] = z / y;
return xyz;
}
public static List<CIEData> cie1931Observer2Degree1nmData() {
return read(cie1931Observer2Degree1nmFile());
}
public static List<CIEData> cie1931Observer2Degree1nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1931Observer2Degree1nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> cie1931Observer2Degree5nmData() {
return read(cie1931Observer2Degree5nmFile());
}
public static List<CIEData> cie1931Observer2Degree5nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1931Observer2Degree5nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(String texts) {
try {
String[] lines = texts.split("\n");
List<CIEData> data = new ArrayList<>();
for (String line : lines) {
CIEData d = readLine(line);
if (d != null) {
data.add(d);
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(File file) {
try {
List<CIEData> data = new ArrayList<>();
File validFile = FileTools.removeBOM(null, file);
try (final BufferedReader reader = new BufferedReader(new FileReader(validFile))) {
String line;
while ((line = reader.readLine()) != null) {
CIEData d = readLine(line);
if (d != null) {
data.add(d);
}
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(File file, ColorSpace cs) {
try {
List<CIEData> data = read(file);
for (CIEData d : data) {
d.convert(cs);
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static StringTable cieTable(List<CIEData> data, ColorSpace cs, String title) {
try {
if (data == null || data.isEmpty()) {
return null;
}
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("WaveLength"), Languages.message("TristimulusX"), Languages.message("TristimulusY"), Languages.message("TristimulusZ"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"), Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ")));
int num = 0;
if (cs != null) {
num = cs.getNumComponents();
for (int i = 0; i < num; ++i) {
names.add(Languages.message(cs.getName(i)));
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int i = 0; i < num; ++i) {
names.add(Languages.message(cs.getName(i)) + "-" + Languages.message("Integer"));
}
}
}
StringTable table = new StringTable(names, title);
double[] channels;
for (int i = 0; i < data.size(); ++i) {
CIEData d = data.get(i);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(d.getWaveLength() + "", d.X + "", d.Y + "", d.Z + "", d.getNormalizedX() + "", d.getNormalizedX() + "", d.getNormalizedX() + "", d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + ""));
if (cs != null) {
channels = d.getChannels();
for (int j = 0; j < num; ++j) {
row.add(channels[j] + "");
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int j = 0; j < num; ++j) {
row.add(Math.round(channels[j] * 255) + "");
}
}
}
table.add(row);
}
return table;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static File cie1964Observer10Degree1nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1964-10-degree-1nm.txt", "CIE", "CIE1964-10-degree-1nm.txt", false);
return f;
}
public static File cie1931Observer2Degree5nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1931-2-degree-5nm.txt", "CIE", "CIE1931-2-degree-5nm.txt", false);
return f;
}
/*
Source data: CIE standard Observer functions and CIE D50 Reference Illuminant
*/
public static File cie1931Observer2Degree1nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1931-2-degree-1nm.txt", "CIE", "CIE1931-2-degree-1nm.txt", false);
return f;
}
public static CIEData readLine(String line) {
try {
String DataIgnoreChars = "\t|,|\uff0c|\\||\\{|\\}|\\[|\\]|\\\"|\\'";
line = line.replaceAll(DataIgnoreChars, " ");
String[] values = line.split("\\s+");
List<Double> dList = new ArrayList<>();
for (String v : values) {
try {
double d = Double.parseDouble(v);
dList.add(d);
if (dList.size() >= 4) {
CIEData data = new CIEData((int) Math.round(dList.get(0)), dList.get(1), dList.get(2), dList.get(3));
data.scaleValues();
return data;
}
} catch (Exception e) {
break;
}
}
return null;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static File cie1964Observer10Degree5nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1964-10-degree-5nm.txt", "CIE", "CIE1964-10-degree-5nm.txt", false);
return f;
}
public static List<CIEData> cie1964Observer10Degree1nmData() {
return read(cie1964Observer10Degree1nmFile());
}
public static List<CIEData> cie1964Observer10Degree1nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1964Observer10Degree1nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String cieString(String texts) {
return cieString(read(texts), null, null);
}
public static String cieString(List<CIEData> data, ColorSpace cs, String title) {
try {
if (data == null || data.isEmpty()) {
return null;
}
String sp = "\t";
StringBuilder s = new StringBuilder();
if (title != null) {
s.append(title).append("\n\n");
}
s.append(Languages.message("WaveLength")).append(sp).append(Languages.message("TristimulusX")).append(sp).append(Languages.message("TristimulusY")).append(sp).append(Languages.message("TristimulusZ")).append(sp).append(Languages.message("NormalizedX")).append(sp).append(Languages.message("NormalizedY")).append(sp).append(Languages.message("NormalizedZ")).append(sp).append(Languages.message("RelativeX")).append(sp).append(Languages.message("RelativeY")).append(sp).append(Languages.message("RelativeZ")).append(sp);
int num = 0;
if (cs != null) {
num = cs.getNumComponents();
for (int i = 0; i < num; ++i) {
s.append(Languages.message(cs.getName(i))).append(sp);
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int i = 0; i < num; ++i) {
s.append(Languages.message(cs.getName(i))).append("-").append(Languages.message("Integer")).append(sp);
}
}
}
s.append("\n");
double[] channels;
for (int i = 0; i < data.size(); ++i) {
CIEData d = data.get(i);
s.append(d.getWaveLength()).append(sp).append(d.X).append(sp).append(d.Y).append(sp).append(d.Z).append(sp).append(d.getNormalizedX()).append(sp).append(d.getNormalizedY()).append(sp).append(d.getNormalizedZ()).append(sp).append(d.getRelativeX()).append(sp).append(d.getRelativeY()).append(sp).append(d.getRelativeZ()).append(sp);
if (cs != null) {
channels = d.getChannels();
for (int j = 0; j < num; ++j) {
s.append(channels[j]).append(sp);
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int j = 0; j < num; ++j) {
s.append(Math.round(channels[j] * 255)).append(sp);
}
}
}
s.append("\n");
}
return s.toString();
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> cie1964Observer10Degree5nmData() {
return read(cie1964Observer10Degree5nmFile());
}
public static List<CIEData> cie1964Observer10Degree5nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1964Observer10Degree5nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static float[] convert(CIEData d, String iccProfile) {
try {
ICC_ColorSpace cs = new ICC_ColorSpace(ICC_Profile.getInstance(iccProfile));
return convert(d, cs);
} catch (Exception e) {
return null;
}
}
public static float[] convert(CIEData d, ICC_Profile iccProfile) {
try {
ICC_ColorSpace cs = new ICC_ColorSpace(iccProfile);
return convert(d, cs);
} catch (Exception e) {
return null;
}
}
public static float[] convert(CIEData d, ICC_ColorSpace cs) {
float[] fxyz = new float[3];
float[] outputs;
fxyz[0] = (float) d.getRelativeX();
fxyz[1] = (float) d.getRelativeY();
fxyz[2] = (float) d.getRelativeZ();
outputs = cs.fromCIEXYZ(fxyz);
return outputs;
}
// https://www.w3.org/TR/css-color-4/#lab-to-rgb
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
/*
Source data: CIE standard Observer functions and CIE D50 Reference Illuminant
*/
public static double[] convert(ColorSpace cs, CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
float[] fxyz = cs.fromCIEXYZ(ColorBase.arrayFloat(xyz));
double[] outputs = clipRGB(arrayDouble(fxyz));
return outputs;
}
public static double[] sRGB65(CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
return CIEColorSpace.XYZd50toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/SRGB.java | alpha/MyBox/src/main/java/mara/mybox/color/SRGB.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import static mara.mybox.color.AppleRGB.XYZtoAppleRGB;
import static mara.mybox.color.RGBColorSpace.linearSRGB;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.image.data.ImageColorSpace;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.DoubleMatrixTools;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:07:33
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class SRGB {
/*
static methods
*/
public static double[] gammaSRGB(double[] linearRGB) {
double[] srgb = new double[3];
srgb[0] = RGBColorSpace.gammaSRGB(linearRGB[0]);
srgb[1] = RGBColorSpace.gammaSRGB(linearRGB[1]);
srgb[2] = RGBColorSpace.gammaSRGB(linearRGB[2]);
return srgb;
}
public static double[] SRGBtoLinearSRGB(double[] sRGB) {
double[] linearRGB = new double[3];
linearRGB[0] = linearSRGB(sRGB[0]);
linearRGB[1] = linearSRGB(sRGB[1]);
linearRGB[2] = linearSRGB(sRGB[2]);
return linearRGB;
}
public static double[] SRGBd50toXYZd50(double[] srgb) {
double[] linearRGB = SRGBtoLinearSRGB(srgb);
double[][] matrix = {
{0.436065673828125, 0.3851470947265625, 0.14306640625},
{0.2224884033203125, 0.7168731689453125, 0.06060791015625},
{0.013916015625, 0.097076416015625, 0.7140960693359375}
};
double[] xyz = DoubleMatrixTools.multiply(matrix, linearRGB);
return xyz;
}
public static double[] SRGBtoXYZd65(Color color) {
return SRGBd65toXYZd65(ColorBase.array(color));
}
public static double[] SRGBd65toXYZd65(double[] srgb) {
double[] linearRGB = SRGBtoLinearSRGB(srgb);
double[][] matrix = {
{0.4124564, 0.3575761, 0.1804375},
{0.2126729, 0.7151522, 0.0721750},
{0.0193339, 0.1191920, 0.9503041}
};
double[] xyz = DoubleMatrixTools.multiply(matrix, linearRGB);
return xyz;
}
public static double[] SRGBtoXYZd50(Color color) {
return SRGBd65toXYZd50(color);
}
// public static double[] SRGBd65toXYZd50(Color color) {
// ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
// float[] xyzD50 = cs.toCIEXYZ(ColorBase.arrayFloat(color));
// return ColorBase.arrayDouble(xyzD50);
// }
//
public static double[] SRGBd65toXYZd50(Color color) {
return SRGBd65toXYZd50(ColorBase.array(color));
}
public static double[] SRGBd65toXYZd50(double[] srgb) {
double[] xyzD65 = SRGBd65toXYZd65(srgb);
return ChromaticAdaptation.D65toD50(xyzD65);
}
public static double[] SRGBtoAdobeRGB(double[] srgb) {
double[] xyz = SRGBd65toXYZd65(srgb);
return CIEColorSpace.XYZd65toAdobeRGBd65(xyz);
}
public static double[] SRGBtoAppleRGB(double[] srgb) {
double[] xyz = SRGBd65toXYZd65(srgb);
return XYZtoAppleRGB(xyz);
}
public static double[] SRGBtoCIELab(Color color) {
double[] xyzD50 = SRGBd65toXYZd50(color);
return CIEColorSpace.XYZd50toCIELab(xyzD50[0], xyzD50[1], xyzD50[2]);
}
public static float[] srgb2profile(ICC_Profile profile, Color color) {
return srgb2profile(profile, ColorConvertTools.color2srgb(color));
}
public static float[] srgb2profile(ICC_Profile profile, javafx.scene.paint.Color color) {
return srgb2profile(profile, FxColorTools.color2srgb(color));
}
public static float[] srgb2profile(ICC_Profile profile, float[] srgb) {
if (profile == null) {
profile = ImageColorSpace.eciCmykProfile();
}
ICC_ColorSpace colorSpace = new ICC_ColorSpace(profile);
return colorSpace.fromRGB(srgb);
}
// http://www.easyrgb.com/en/math.php
public static double[] rgb2cmy(javafx.scene.paint.Color color) {
double[] cmy = new double[3];
cmy[0] = 1 - color.getRed();
cmy[1] = 1 - color.getGreen();
cmy[2] = 1 - color.getBlue();
return cmy;
}
public static double[] rgb2cmy(Color color) {
double[] cmy = new double[3];
cmy[0] = 1 - color.getRed() / 255d;
cmy[1] = 1 - color.getGreen() / 255d;
cmy[2] = 1 - color.getBlue() / 255d;
return cmy;
}
public static double[] rgb2cmyk(javafx.scene.paint.Color color) {
return CMYKColorSpace.cmy2cmky(rgb2cmy(color));
}
public static double[] rgb2cmyk(Color color) {
return CMYKColorSpace.cmy2cmky(rgb2cmy(color));
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/CMYKColorSpace.java | alpha/MyBox/src/main/java/mara/mybox/color/CMYKColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
/**
* @Author Mara
* @CreateDate 2019-6-7 9:38:03
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class CMYKColorSpace {
public static enum ColorSpaceType {
CMY, CMYK
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(cs + "");
}
return names;
}
public static double[] cmy2cmky(double[] cmy) {
double[] cmyk = new double[4];
cmyk[0] = cmy[0];
cmyk[1] = cmy[1];
cmyk[2] = cmy[2];
cmyk[3] = 1;
if (cmyk[0] < cmyk[3]) {
cmyk[3] = cmyk[0];
}
if (cmyk[1] < cmyk[3]) {
cmyk[3] = cmyk[1];
}
if (cmyk[2] < cmyk[3]) {
cmyk[3] = cmyk[2];
}
if (cmyk[3] == 1) {
cmyk[0] = 0;
cmyk[1] = 0;
cmyk[2] = 0;
} else {
cmyk[0] = (cmyk[0] - cmyk[3]) / (1 - cmyk[3]);
cmyk[1] = (cmyk[1] - cmyk[3]) / (1 - cmyk[3]);
cmyk[2] = (cmyk[2] - cmyk[3]) / (1 - cmyk[3]);
}
return cmyk;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ColorMatch.java | alpha/MyBox/src/main/java/mara/mybox/color/ColorMatch.java | package mara.mybox.color;
import java.awt.Color;
import java.util.List;
import static mara.mybox.color.SRGB.SRGBtoCIELab;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2025-2-7
* @License Apache License Version 2.0
*/
public class ColorMatch {
private double threshold, realThreshold;
protected double brightnessWeight, saturationWeight, hueWeight;
private boolean accurateMatch;
protected MatchAlgorithm algorithm;
public final static MatchAlgorithm DefaultAlgorithm = MatchAlgorithm.RGBRoughWeightedEuclidean;
public static enum MatchAlgorithm {
CIEDE2000, CIE94, CIE76,
HSBEuclidean, Hue, Saturation, Brightness,
RGBEuclidean, RGBRoughWeightedEuclidean, RGBWeightedEuclidean,
RGBManhattan,
Red, Green, Blue,
CMC
}
public ColorMatch() {
init();
}
public final void init() {
algorithm = DefaultAlgorithm;
setThreshold(suggestedThreshold(algorithm));
brightnessWeight = 1d;
saturationWeight = 1d;
hueWeight = 1d;
}
public ColorMatch copyTo(ColorMatch match) {
if (match == null) {
return match;
}
match.setAlgorithm(algorithm);
match.setThreshold(threshold);
match.setHueWeight(hueWeight);
match.setBrightnessWeight(brightnessWeight);
match.setSaturationWeight(saturationWeight);
return match;
}
public String info() {
return "Algorithm :" + algorithm + "\n"
+ "threshold :" + threshold + "\n"
+ "hueWeight :" + hueWeight + "\n"
+ "brightnessWeight :" + brightnessWeight + "\n"
+ "saturationWeight :" + saturationWeight;
}
/*
parameters
*/
public final ColorMatch setThreshold(double value) {
threshold = value;
accurateMatch = threshold < 1e-10;
switch (algorithm) {
case RGBRoughWeightedEuclidean:
case RGBWeightedEuclidean:
case RGBEuclidean:
case HSBEuclidean:
case CIEDE2000:
case CIE94:
case CIE76:
case CMC:
realThreshold = accurateMatch ? 1e-10 : threshold * threshold;
break;
case Red:
case Green:
case Blue:
case Hue:
case Saturation:
case Brightness:
case RGBManhattan:
realThreshold = threshold;
break;
}
return this;
}
public static double suggestedThreshold(MatchAlgorithm a) {
switch (a) {
case RGBRoughWeightedEuclidean:
return 20d;
case RGBWeightedEuclidean:
return 20d;
case RGBEuclidean:
return 20d;
case CIEDE2000:
return 5d;
case CIE94:
return 5d;
case CIE76:
return 5d;
case CMC:
return 5d;
case HSBEuclidean:
return 20d;
case Red:
case Green:
case Blue:
return 20d;
case Hue:
return 20d;
case Saturation:
return 20d;
case Brightness:
return 20d;
case RGBManhattan:
return 20d;
}
return 20d;
}
public static boolean supportWeights(MatchAlgorithm a) {
switch (a) {
case RGBRoughWeightedEuclidean:
case RGBWeightedEuclidean:
case RGBEuclidean:
case Red:
case Green:
case Blue:
case Hue:
case Saturation:
case Brightness:
case RGBManhattan:
case CIE76:
return false;
case CIEDE2000:
case CIE94:
case HSBEuclidean:
case CMC:
return true;
}
return false;
}
public static MatchAlgorithm algorithm(String as) {
try {
for (MatchAlgorithm a : MatchAlgorithm.values()) {
if (Languages.matchIgnoreCase(a.name(), as)) {
return a;
}
}
} catch (Exception e) {
}
return DefaultAlgorithm;
}
public boolean setColorWeights(String weights) {
try {
String[] values = weights.split(":");
hueWeight = Double.parseDouble(values[0]);
saturationWeight = Double.parseDouble(values[1]);
brightnessWeight = Double.parseDouble(values[2]);
return true;
} catch (Exception e) {
return false;
}
}
public String getColorWeights() {
return hueWeight + ":" + saturationWeight + ":" + brightnessWeight;
}
/*
match
*/
public boolean isMatch(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return false;
}
if (color1.getRGB() == color2.getRGB()) {
return true;
} else if (accurateMatch || color1.getRGB() == 0 || color2.getRGB() == 0) {
return false;
}
return distance(color1, color2) <= realThreshold;
}
public boolean isMatchColors(List<Color> colors, Color color, boolean excluded) {
if (colors == null || colors.isEmpty()) {
return true;
}
if (excluded) {
for (Color oColor : colors) {
if (isMatch(color, oColor)) {
return false;
}
}
return true;
} else {
for (Color oColor : colors) {
if (isMatch(color, oColor)) {
return true;
}
}
return false;
}
}
/*
distance
*/
public double distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
switch (algorithm) {
case RGBRoughWeightedEuclidean:
return rgbRoughWeightedEuclideanDistance(color1, color2);
case RGBWeightedEuclidean:
return rgbWeightEuclideanDistance(color1, color2);
case RGBEuclidean:
return rgbEuclideanDistance(color1, color2);
case Red:
return redDistance(color1, color2);
case Green:
return greenDistance(color1, color2);
case Blue:
return blueDistance(color1, color2);
case RGBManhattan:
return manhattanDistance(color1, color2);
case CIEDE2000:
return ciede2000Distance(color1, color2);
case CIE94:
return cie94Distance(color1, color2);
case CIE76:
return cie76Distance(color1, color2);
case CMC:
return cmcDistance(color1, color2);
case HSBEuclidean:
return hsbEuclideanDistance(color1, color2);
case Hue:
return hueDistance(color1, color2);
case Saturation:
return saturationDistance(color1, color2);
case Brightness:
return brightnessDistance(color1, color2);
}
return Integer.MAX_VALUE;
}
public static double rgbEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
return redDistance * redDistance
+ greenDistance * greenDistance
+ blueDistance * blueDistance;
}
// https://www.compuphase.com/cmetric.htm
public static double rgbWeightEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
int redAvg = (color1.getRed() + color2.getRed()) / 2;
return Math.round(((512 + redAvg) * redDistance * redDistance) >> 8
+ 4 * greenDistance * greenDistance
+ ((767 - redAvg) * blueDistance * blueDistance) >> 8);
}
// https://en.wikipedia.org/wiki/Color_difference
public static double rgbRoughWeightedEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
return 2 * redDistance * redDistance
+ 4 * greenDistance * greenDistance
+ 3 * blueDistance * blueDistance;
}
public static double manhattanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getRed() - color2.getRed())
+ Math.abs(color1.getGreen() - color2.getGreen())
+ Math.abs(color1.getBlue() - color2.getBlue());
}
public static double redDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getRed() - color2.getRed());
}
public static double greenDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getGreen() - color2.getGreen());
}
public static double blueDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getBlue() - color2.getBlue());
}
public double hsbEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
float[] hsb1 = ColorConvertTools.color2hsb(color1);
float[] hsb2 = ColorConvertTools.color2hsb(color2);
double hueDistance = Math.abs(hsb1[0] * 360 - hsb2[0] * 360);
hueDistance = Math.min(hueDistance, 360 - hueDistance) / 1.8;
double saturationDistance = Math.ceil(Math.abs(hsb1[1] - hsb2[1]) * 100);
double brightnessDistance = Math.ceil(Math.abs(hsb1[2] - hsb2[2]) * 100);
return hueWeight * hueDistance * hueDistance
+ saturationWeight * saturationDistance * saturationDistance
+ brightnessWeight * brightnessDistance * brightnessDistance;
}
public static double hueDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getHue(color1) - ColorConvertTools.getHue(color2)) * 360;
}
public static double saturationDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getSaturation(color1) - ColorConvertTools.getSaturation(color2)) * 100;
}
public static double brightnessDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getBrightness(color1) - ColorConvertTools.getBrightness(color2)) * 100;
}
public static double cie76Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double lDistance = lab1[0] - lab2[0];
double aDistance = lab1[1] - lab2[1];
double bDistance = lab1[2] - lab2[2];
return lDistance * lDistance + aDistance * aDistance + bDistance * bDistance;
}
public double cie94Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 计算亮度差
double deltaL = L1 - L2;
// 计算色度C
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
double deltaC = C1 - C2;
// 计算色调差ΔH
double deltaH = Math.sqrt(Math.pow(a1 - a2, 2) + Math.pow(b1 - b2, 2) - Math.pow(deltaC, 2));
// 计算权重因子
double SL = 1.0; // 亮度权重因子
double SC = 1.0 + 0.045 * (C1 + C2) / 2.0; // 色度权重因子
double SH = 1.0 + 0.015 * (C1 + C2) / 2.0; // 色调权重因子
// 计算CIE94色差
double term1 = deltaL / (brightnessWeight * SL);
double term2 = deltaC / (saturationWeight * SC);
double term3 = deltaH / (hueWeight * SH);
// Avoid "sqrt"
return term1 * term1 + term2 * term2 + term3 * term3;
}
public double ciede2000Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 步骤1: 计算色度C和色调角h
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
double C_avg = (C1 + C2) / 2.0;
// 步骤2: 计算G因子(色度非线性补偿)
double G = 0.5 * (1 - Math.sqrt(Math.pow(C_avg, 7) / (Math.pow(C_avg, 7) + Math.pow(25, 7))));
double a1_prime = a1 * (1 + G);
double a2_prime = a2 * (1 + G);
// 更新色度C'
C1 = Math.sqrt(a1_prime * a1_prime + b1 * b1);
C2 = Math.sqrt(a2_prime * a2_prime + b2 * b2);
// 步骤3: 计算色调角差Δh'
double h1 = Math.toDegrees(Math.atan2(b1, a1_prime));
if (h1 < 0) {
h1 += 360;
}
double h2 = Math.toDegrees(Math.atan2(b2, a2_prime));
if (h2 < 0) {
h2 += 360;
}
double delta_h_prime;
if (Math.abs(h2 - h1) <= 180) {
delta_h_prime = h2 - h1;
} else {
delta_h_prime = (h2 - h1 > 180) ? (h2 - h1 - 360) : (h2 - h1 + 360);
}
// 步骤4: 计算色调平均H'
double H_prime_avg = (Math.abs(h1 - h2) > 180) ? ((h1 + h2 + 360) / 2.0) : ((h1 + h2) / 2.0);
// 步骤5: 补偿因子计算
double T = 1 - 0.17 * Math.cos(Math.toRadians(H_prime_avg - 30))
+ 0.24 * Math.cos(Math.toRadians(2 * H_prime_avg))
+ 0.32 * Math.cos(Math.toRadians(3 * H_prime_avg + 6))
- 0.20 * Math.cos(Math.toRadians(4 * H_prime_avg - 63));
double delta_L_prime = L2 - L1;
double delta_C_prime = C2 - C1;
double delta_H_prime = 2 * Math.sqrt(C1 * C2) * Math.sin(Math.toRadians(delta_h_prime / 2.0));
// 步骤6: 权重因子
double SL = 1 + (0.015 * Math.pow((L1 + L2) / 2.0 - 50, 2)) / Math.sqrt(20 + Math.pow((L1 + L2) / 2.0 - 50, 2));
double SC = 1 + 0.045 * ((C1 + C2) / 2.0);
double SH = 1 + 0.015 * ((C1 + C2) / 2.0) * T;
// 步骤7: 旋转因子RT
double delta_theta = 30 * Math.exp(-Math.pow((H_prime_avg - 275) / 25, 2));
double RT = -2 * Math.sqrt(Math.pow(C_avg, 7) / (Math.pow(C_avg, 7) + Math.pow(25, 7))) * Math.sin(Math.toRadians(2 * delta_theta));
// 最终计算ΔE00
double term1 = delta_L_prime / (brightnessWeight * SL);
double term2 = delta_C_prime / (saturationWeight * SC);
double term3 = delta_H_prime / (hueWeight * SH);
// Avoid "sqrt"
return term1 * term1 + term2 * term2 + term3 * term3 + RT * term2 * term3;
}
public double cmcDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 计算 C1 和 C2
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
// 计算 ΔL, ΔC, ΔH
double deltaL = L2 - L1;
double deltaC = C2 - C1;
double deltaH = Math.sqrt(Math.pow(a2 - a1, 2) + Math.pow(b2 - b1, 2) - Math.pow(deltaC, 2));
// 计算 h1(色相)
double h1 = Math.toDegrees(Math.atan2(b1, a1));
if (h1 < 0) {
h1 += 360; // 确保色相在 [0, 360] 范围内
}
// 计算 S_L, S_C
double S_L = L1 < 16 ? 0.511 : (0.040975 * L1) / (1 + 0.01765 * L1);
double S_C = (0.0638 * C1) / (1 + 0.0131 * C1) + 0.638;
// 计算 T
double F = Math.sqrt(Math.pow(C1, 4) / (Math.pow(C1, 4) + 1900));
double T = F == 0 ? 1 : (0.56 + Math.abs(0.2 * Math.cos(Math.toRadians(h1 + 168))));
// 计算 ΔE*cmc
double termL = deltaL / (brightnessWeight * S_L);
double termC = deltaC / (saturationWeight * S_C);
double termH = deltaH / (S_C * T);
// Avoid "sqrt"
return termL * termL + termC * termC + termH * termH;
}
/*
get/set
*/
public double getThreshold() {
return threshold;
}
public double getRealThreshold() {
return realThreshold;
}
public MatchAlgorithm getAlgorithm() {
if (algorithm == null) {
algorithm = DefaultAlgorithm;
}
return algorithm;
}
public ColorMatch setAlgorithm(MatchAlgorithm algorithm) {
if (algorithm != null) {
this.algorithm = algorithm;
}
return this;
}
public double getBrightnessWeight() {
return brightnessWeight;
}
public ColorMatch setBrightnessWeight(double brightnessWeight) {
this.brightnessWeight = brightnessWeight;
return this;
}
public double getSaturationWeight() {
return saturationWeight;
}
public ColorMatch setSaturationWeight(double saturationWeight) {
this.saturationWeight = saturationWeight;
return this;
}
public double getHueWeight() {
return hueWeight;
}
public ColorMatch setHueWeight(double hueWeight) {
this.hueWeight = hueWeight;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ColorConversion.java | alpha/MyBox/src/main/java/mara/mybox/color/ColorConversion.java | package mara.mybox.color;
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 mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:26:36
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorConversion {
public enum SpaceType {
RGB, CIE, CMYK, Others
}
public enum RangeType {
Normalized, RGB, Hundred
}
public static BufferedImage sRGB(BufferedImage source, int colorSpace) {
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(ColorSpace.CS_sRGB));
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
}
public static BufferedImage convertColorSpace(BufferedImage source, int colorSpace) {
ICC_Profile profile = ICC_Profile.getInstance(colorSpace);
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(profile);
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
}
public static BufferedImage convertColorSpace(BufferedImage source, String iccFile) {
try {
ICC_Profile profile = ICC_Profile.getInstance(iccFile);
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(profile);
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static float[] fromSRGB(int colorSpace, float[] srgb) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] xyz = cs.toCIEXYZ(srgb);
cs = ColorSpace.getInstance(colorSpace);
float[] rgb = cs.fromCIEXYZ(xyz);
return rgb;
}
public static float[] toSRGB(int colorSpace, float[] rgb) {
ColorSpace cs = ColorSpace.getInstance(colorSpace);
float[] xyz = cs.toCIEXYZ(rgb);
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] srgb = cs.fromCIEXYZ(xyz);
return srgb;
}
public static float[] SRGBtoXYZ(float[] srgb) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] xyz = cs.toCIEXYZ(srgb);
return xyz;
}
public static float[] XYZtoSRGB(float[] xyz) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] srgb = cs.fromCIEXYZ(xyz);
return srgb;
}
// http://what-when-how.com/introduction-to-video-and-image-processing/conversion-between-rgb-and-yuvycbcr-introduction-to-video-and-image-processing
/*
YUV
Y: 0~255 U: -111~111 V: -157~157
*/
public static float[] RGBtoYUV(float[] rgb) {
float[] yuv = new float[3];
yuv[0] = 0.299f * rgb[0] + 0.587f * rgb[1] + 0.114f * rgb[2];
yuv[1] = 0.492f * (rgb[2] - yuv[0]);
yuv[2] = 0.877f * (rgb[0] - yuv[0]);
return yuv;
}
public static float[] YUVtoRGB(float[] yuv) {
float[] rgb = new float[3];
rgb[0] = yuv[0] + 1.140f * yuv[2];
rgb[1] = yuv[0] - 0.395f * yuv[1] - 0.581f * yuv[2];
rgb[2] = yuv[0] + 2.032f * yuv[1];
return rgb;
}
public static double[] RGBtoYUV(double[] rgb) {
double[] yuv = new double[3];
yuv[0] = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
yuv[1] = 0.492 * (rgb[2] - yuv[0]);
yuv[2] = 0.877 * (rgb[0] - yuv[0]);
return yuv;
}
public static double[] YUVtoRGB(double[] yuv) {
double[] rgb = new double[3];
rgb[0] = yuv[0] + 1.140 * yuv[2];
rgb[1] = yuv[0] - 0.395 * yuv[1] - 0.581 * yuv[2];
rgb[2] = yuv[0] + 2.032 * yuv[1];
return rgb;
}
// https://wolfcrow.com/whats-the-difference-between-yuv-yiq-ypbpr-and-ycbcr/
/*
YCbCr
Y: 0~255 Cb: 0~255 Cr: 0~255
*/
public static float[] RGBtoYCrCb(float[] rgb) {
float[] YCbCr = new float[3];
float offset = 128f / 255;
YCbCr[0] = 0.299f * rgb[0] + 0.578f * rgb[1] + 0.114f * rgb[2];
YCbCr[1] = -0.1687f * rgb[0] - 0.3313f * rgb[1] + 0.500f * rgb[2] + offset;
YCbCr[2] = 0.500f * rgb[0] - 0.4187f * rgb[1] - 0.0813f * rgb[2] + offset;
return YCbCr;
}
public static float[] YCrCbtoRGB(float[] YCbCr) {
float[] rgb = new float[3];
float offset = 128f / 255;
rgb[0] = YCbCr[0] + 1.4020f * (YCbCr[2] - offset);
rgb[1] = YCbCr[0] - 0.3441f * (YCbCr[1] - offset) - 0.7141f * (YCbCr[2] - offset);
rgb[2] = YCbCr[0] + 1.7720f * (YCbCr[1] - offset);
return rgb;
}
public static double[] RGBtoYCrCb(double[] rgb) {
double[] YCbCr = new double[3];
double offset = 128d / 255;
YCbCr[0] = 0.299 * rgb[0] + 0.578 * rgb[1] + 0.114 * rgb[2];
YCbCr[1] = -0.1687 * rgb[0] - 0.3313 * rgb[1] + 0.500 * rgb[2] + offset;
YCbCr[2] = 0.500 * rgb[0] - 0.4187 * rgb[1] - 0.0813 * rgb[2] + offset;
return YCbCr;
}
public static double[] YCrCbtoRGB(double[] YCbCr) {
double[] rgb = new double[3];
double offset = 128d / 255;
rgb[0] = YCbCr[0] + 1.4020 * (YCbCr[2] - offset);
rgb[1] = YCbCr[0] - 0.3441 * (YCbCr[1] - offset) - 0.7141 * (YCbCr[2] - offset);
rgb[2] = YCbCr[0] + 1.7720 * (YCbCr[1] - offset);
return rgb;
}
/*
Yxy
*/
public static float[] XYZtoYXY(float[] xyz) {
float x = xyz[0];
float y = xyz[1];
float z = xyz[2];
float[] Yxy = new float[3];
Yxy[0] = y;
Yxy[1] = x / (x + y + z);
Yxy[2] = y / (x + y + z);
return Yxy;
}
public static float[] YXYtoXYZ(float[] Yxy) {
float Y = Yxy[0];
float x = Yxy[1];
float y = Yxy[2];
float[] xyz = new float[3];
xyz[0] = x * (Y / y);
xyz[1] = Y;
xyz[2] = (1 - x - y) * (Y / y);
return xyz;
}
public static double[] XYZtoYXY(double[] xyz) {
double x = xyz[0];
double y = xyz[1];
double z = xyz[2];
double[] Yxy = new double[3];
Yxy[0] = y;
Yxy[1] = x / (x + y + z);
Yxy[2] = y / (x + y + z);
return Yxy;
}
public static double[] YXYtoXYZ(double[] Yxy) {
double Y = Yxy[0];
double x = Yxy[1];
double y = Yxy[2];
double[] xyz = new double[3];
xyz[0] = x * (Y / y);
xyz[1] = Y;
xyz[2] = (1 - x - y) * (Y / y);
return xyz;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/IccTag.java | alpha/MyBox/src/main/java/mara/mybox/color/IccTag.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccTagType.XYZ;
import static mara.mybox.color.IccTagType.XYZDoubles;
import static mara.mybox.color.IccTagType.XYZNumber;
import static mara.mybox.color.IccTagType.XYZNumberDoubles;
import static mara.mybox.color.IccTagType.curve;
import static mara.mybox.color.IccTagType.curveDoubles;
import static mara.mybox.color.IccTagType.dateTime;
import static mara.mybox.color.IccTagType.geometryType;
import static mara.mybox.color.IccTagType.illuminantType;
import static mara.mybox.color.IccTagType.lut;
import static mara.mybox.color.IccTagType.measurement;
import static mara.mybox.color.IccTagType.multiLocalizedUnicode;
import static mara.mybox.color.IccTagType.observerType;
import static mara.mybox.color.IccTagType.s15Fixed16Array;
import static mara.mybox.color.IccTagType.s15Fixed16ArrayDoubles;
import static mara.mybox.color.IccTagType.signature;
import static mara.mybox.color.IccTagType.text;
import static mara.mybox.color.IccTagType.u16Fixed16Number;
import static mara.mybox.color.IccTagType.viewingConditions;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-5-7 16:11:08
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccTag {
private String tag, name, description;
private int offset, size;
private Object value;
private byte[] bytes;
private TagType type;
private List<String> valueSelection, arrayNames;
private boolean isHeaderField, editable, selectionEditable, changed, first4ascii, normalizeLut;
public static enum TagType {
Text, MultiLocalizedUnicode, Int, Double, XYZ, Curve, ViewingConditions,
Measurement, Signature, S15Fixed16Array, DateTime, LUT, Boolean, Bytes, BooleanArray
}
public IccTag(String tag, int offset, byte[] bytes, boolean normalizeLut) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.normalizeLut = normalizeLut;
name = tagName(tag);
description = tagDescription(name);
type = tagType(tag);
value = tagValue(this.type, bytes, normalizeLut);
valueSelection = tagSelection(tag);
changed = false;
isHeaderField = false;
selectionEditable = false;
editable = false;
}
public IccTag(String tag, int offset, byte[] bytes,
TagType type, Object value) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.name = tag;
this.description = tag;
this.type = type;
this.value = value;
this.valueSelection = null;
this.selectionEditable = false;
this.isHeaderField = true;
this.editable = true;
changed = false;
}
public IccTag(String tag, int offset, byte[] bytes,
TagType type, Object value,
List<String> valueSelection, boolean selectionEditable) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.name = tag;
this.description = tag;
this.type = type;
this.value = value;
this.valueSelection = valueSelection;
this.selectionEditable = selectionEditable;
this.isHeaderField = true;
this.editable = true;
changed = false;
}
public String display() {
try {
if (valueSelection != null) {
String v = (String) value;
for (String s : valueSelection) {
if (s.startsWith(v)) {
return s;
}
}
}
return tagDisplay(type, value);
} catch (Exception e) {
return null;
}
}
public boolean update(String newValue) {
return update(this, newValue);
}
public boolean update(String key, String newValue) {
if (key == null) {
return update(newValue);
}
switch (type) {
case ViewingConditions:
switch (key.toLowerCase()) {
case "illuminant":
return updateViewingConditionsIlluminant(this, newValue);
case "surround":
return updateViewingConditionsSurround(this, newValue);
case "illuminanttype":
return updateViewingConditionsType(this, newValue);
}
case Measurement:
switch (key.toLowerCase()) {
case "observer":
return updateMeasurementObserver(this, newValue);
case "tristimulus":
return updateMeasurementTristimulus(this, newValue);
case "geometry":
return updateMeasurementGeometry(this, newValue);
case "flare":
return updateMeasurementFlare(this, newValue);
case "illuminanttype":
return updateMeasurementType(this, newValue);
}
}
return update(this, newValue);
}
/*
Decode tag
*/
public static String tagName(String tag) {
for (String[] item : tagNames) {
if (item[0].equals(tag)) {
return item[1];
}
}
return tag;
}
public static String tagDescription(String tagName) {
for (String[] item : tagDescriptions) {
if (item[0].equals(tagName)) {
return item[1];
}
}
return "";
}
public static TagType tagType(String tag) {
if (tag == null) {
return null;
}
switch (tag) {
case "desc":
case "dmnd":
case "dmdd":
case "vued":
return TagType.MultiLocalizedUnicode;
case "cprt":
return TagType.Text;
case "wtpt":
case "bkpt":
case "rXYZ":
case "gXYZ":
case "bXYZ":
case "lumi":
return TagType.XYZ;
case "rTRC":
case "gTRC":
case "bTRC":
case "kTRC":
return TagType.Curve;
case "view":
return TagType.ViewingConditions;
case "meas":
return TagType.Measurement;
case "tech":
return TagType.Signature;
case "chad":
return TagType.S15Fixed16Array;
case "calt":
return TagType.DateTime;
case "A2B0":
case "A2B1":
case "A2B2":
case "B2A0":
case "B2A1":
case "B2A2":
case "gamt":
return TagType.LUT;
}
return null;
}
public static Object tagValue(TagType type, byte[] bytes, boolean normalizeLut) {
if (type == null || bytes == null) {
return null;
}
switch (type) {
case MultiLocalizedUnicode:
return multiLocalizedUnicode(bytes);
case Text:
return text(bytes);
case XYZ:
return XYZ(bytes);
case Curve:
return curve(bytes);
case ViewingConditions:
return viewingConditions(bytes);
case Measurement:
return measurement(bytes);
case Signature:
return signature(bytes);
case S15Fixed16Array:
return s15Fixed16Array(bytes);
case DateTime:
return dateTime(bytes);
case LUT:
return lut(bytes, normalizeLut);
}
return null;
}
public static List<String> tagSelection(String tag) {
switch (tag) {
case "tech":
return technologyTypes();
}
return null;
}
public static String tagDisplay(TagType type, Object value) {
if (type == null || value == null) {
return "";
}
String display;
try {
switch (type) {
case Text:
case Signature:
case DateTime:
display = value + "";
break;
case MultiLocalizedUnicode:
display = IccTagType.textDescriptionDisplay((Map<String, Object>) value);
break;
case XYZ:
display = IccTagType.XYZNumberDisplay((double[][]) value);
break;
case Curve:
display = IccTagType.curveDisplay((double[]) value);
break;
case ViewingConditions:
display = IccTagType.viewingConditionsDisplay((Map<String, Object>) value);
break;
case Measurement:
display = IccTagType.measurementDisplay((Map<String, Object>) value);
break;
case S15Fixed16Array:
display = IccTagType.s15Fixed16ArrayDisplay((double[]) value);
break;
case LUT:
display = IccTagType.lutDisplay((Map<String, Object>) value);
break;
default:
display = value + "";
}
} catch (Exception e) {
display = value + "";
}
return display;
}
/*
Encode tag
*/
public static boolean update(IccTag tag, String newValue) {
try {
byte[] bytes = null;
Object value = null;
switch (tag.getType()) {
case Text: {
value = newValue;
bytes = text(newValue);
break;
}
case MultiLocalizedUnicode:
bytes = multiLocalizedUnicode(tag, newValue);
value = multiLocalizedUnicode(bytes);
break;
case Signature:
bytes = signature(newValue);
value = signature(bytes);
break;
case DateTime:
bytes = dateTime(newValue);
value = dateTime(bytes);
break;
case XYZ: {
double[][] doubles = XYZDoubles(newValue);
bytes = XYZ(doubles);
value = doubles;
break;
}
case Curve: {
double[] doubles = curveDoubles(newValue);
bytes = curve(doubles);
value = doubles;
break;
}
case S15Fixed16Array: {
double[] doubles = s15Fixed16ArrayDoubles(newValue);
bytes = s15Fixed16Array(doubles);
value = doubles;
break;
}
}
if (value == null || bytes == null) {
return false;
}
tag.setValue(value);
tag.setBytes(bytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsIlluminant(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminant", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] illuminantBytes = XYZNumber(doubles);
System.arraycopy(illuminantBytes, 0, tagBytes, 8, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsSurround(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("surround", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] surroundBytes = XYZNumber(doubles);
System.arraycopy(surroundBytes, 0, tagBytes, 20, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsType(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminantType", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] typeBytes = illuminantType(newValue);
System.arraycopy(typeBytes, 0, tagBytes, 32, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementObserver(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("observer", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] observerBytes = observerType(newValue);
System.arraycopy(observerBytes, 0, tagBytes, 8, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementTristimulus(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("tristimulus", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] tristimulusBytes = XYZNumber(doubles);
System.arraycopy(tristimulusBytes, 0, tagBytes, 12, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementGeometry(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("geometry", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] geometryBytes = geometryType(newValue);
System.arraycopy(geometryBytes, 0, tagBytes, 24, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementFlare(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
double flare = Double.parseDouble(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("flare", flare);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] flareBytes = u16Fixed16Number(flare);
System.arraycopy(flareBytes, 0, tagBytes, 28, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementType(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminantType", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] typeBytes = illuminantType(newValue);
System.arraycopy(typeBytes, 0, tagBytes, 32, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
/*
Values
*/
// https://sno.phy.queensu.ca/~phil/exiftool/TagNames/ICC_Profile.html
public static String[][] tagNames = {
{"A2B0", "AToB0"},
{"A2B1", "AToB1"},
{"A2B2", "AToB2"},
{"B2A0", "BToA0"},
{"B2A1", "BToA1"},
{"B2A2", "BToA2"},
{"B2D0", "BToD0"},
{"B2D1", "BToD1"},
{"B2D2", "BToD2"},
{"B2D3", "BToD3"},
{"D2B0", "DToB0"},
{"D2B1", "DToB1"},
{"D2B2", "DToB2"},
{"D2B3", "DToB3"},
{"Header", "ProfileHeader"},
{"MS00", "WCSProfiles"},
{"bTRC", "BlueTRC"},
{"bXYZ", "BlueMatrixColumn"},
{"bfd", "UCRBG"},
{"bkpt", "MediaBlackPoint"},
{"calt", "CalibrationDateTime"},
{"chad", "ChromaticAdaptation"},
{"chrm", "Chromaticity"},
{"ciis", "ColorimetricIntentImageState"},
{"clot", "ColorantTableOut"},
{"clro", "ColorantOrder"},
{"clrt", "ColorantTable"},
{"cprt", "ProfileCopyright"},
{"crdi", "CRDInfo"},
{"desc", "ProfileDescription"},
{"devs", "DeviceSettings"},
{"dmdd", "DeviceModelDesc"},
{"dmnd", "DeviceMfgDesc"},
{"dscm", "ProfileDescriptionML"},
{"fpce", "FocalPlaneColorimetryEstimates"},
{"gTRC", "GreenTRC"},
{"gXYZ", "GreenMatrixColumn"},
{"gamt", "Gamut"},
{"kTRC", "GrayTRC"},
{"lumi", "Luminance"},
{"meas", "Measurement"},
{"meta", "Metadata"},
{"mmod", "MakeAndModel"},
{"ncl2", "NamedColor2"},
{"ncol", "NamedColor"},
{"ndin", "NativeDisplayInfo"},
{"pre0", "Preview0"},
{"pre1", "Preview1"},
{"pre2", "Preview2"},
{"ps2i", "PS2RenderingIntent"},
{"ps2s", "PostScript2CSA"},
{"psd0", "PostScript2CRD0"},
{"psd1", "PostScript2CRD1"},
{"psd2", "PostScript2CRD2"},
{"psd3", "PostScript2CRD3"},
{"pseq", "ProfileSequenceDesc"},
{"psid", "ProfileSequenceIdentifier"},
{"psvm", "PS2CRDVMSize"},
{"rTRC", "RedTRC"},
{"rXYZ", "RedMatrixColumn"},
{"resp", "OutputResponse"},
{"rhoc", "ReflectionHardcopyOrigColorimetry"},
{"rig0", "PerceptualRenderingIntentGamut"},
{"rig2", "SaturationRenderingIntentGamut"},
{"rpoc", "ReflectionPrintOutputColorimetry"},
{"sape", "SceneAppearanceEstimates"},
{"scoe", "SceneColorimetryEstimates"},
{"scrd", "ScreeningDesc"},
{"scrn", "Screening"},
{"targ", "CharTarget"},
{"tech", "Technology"},
{"vcgt", "VideoCardGamma"},
{"view", "ViewingConditions"},
{"vued", "ViewingCondDesc"},
{"wtpt", "MediaWhitePoint"}
};
public static String[][] tagDescriptions = {
{"AToB0", "Multi-dimensional transformation structure"},
{"AToB1", "Multi-dimensional transformation structure"},
{"AToB2", "Multi-dimensional transformation structure"},
{"BlueMatrixColumn", "The third column in the matrix used in matrix/TRC transforms. (This column is combined with the linear blue channel during the matrix multiplication)."},
{"BlueTRC", "Blue channel tone reproduction curve"},
{"BToA0", "Multi-dimensional transformation structure"},
{"BToA1", "Multi-dimensional transformation structure"},
{"BToA2", "Multi-dimensional transformation structure"},
{"BToD0", "Multi-dimensional transformation structure"},
{"BToD1", "Multi-dimensional transformation structure"},
{"BToD2", "Multi-dimensional transformation structure"},
{"BToD3", "Multi-dimensional transformation structure"},
{"CalibrationDateTime", "Profile calibration date and time"},
{"CharTarget", "Characterization target such as IT8/7.2"},
{"ChromaticAdaptation", "Converts an nCIEXYZ colour relative to the actual adopted white to the nCIEXYZ colour relative to the PCS adopted white. Required only if the chromaticity of the actual adopted white is different from that of the PCS adopted white."},
{"Chromaticity", "Set of phosphor/colorant chromaticity"},
{"ColorantOrder", "Identifies the laydown order of colorants"},
{"ColorantTable", "Identifies the colorants used in the profile. Required for N-component based Output profiles and DeviceLink profiles only if the data colour space field is xCLR (e.g. 3CLR)"},
{"ColorantTableOut", "Identifies the output colorants used in the profile, required only if the PCS Field is xCLR (e.g. 3CLR)"},
{"ColorimetricIntentImageState", "Indicates the image state of PCS colorimetry produced using the colorimetric intent transforms"},
{"ProfileCopyright", "Profile copyright information"},
{"DeviceMfgDesc", "Displayable description of device manufacturer"},
{"DeviceModelDesc", "Displayable description of device model"},
{"DToB0", "Multi-dimensional transformation structure"},
{"DToB1", "Multi-dimensional transformation structure"},
{"DToB2", "Multi-dimensional transformation structure"},
{"DToB3", "Multi-dimensional transformation structure"},
{"Gamut", "Out of gamut: 8-bit or 16-bit data"},
{"GrayTRC", "Grey tone reproduction curve"},
{"GreenMatrixColumn", "The second column in the matrix used in matrix/TRC transforms (This column is combined with the linear green channel during the matrix multiplication)."},
{"GreenTRC", "Green channel tone reproduction curve"},
{"Luminance", "Absolute luminance for emissive device"},
{"Measurement", "Alternative measurement specification information"},
{"MediaBlackPoint", "nCIEXYZ of Media black point"},
{"MediaWhitePoint", "nCIEXYZ of media white point"},
{"NamedColor2", "PCS and optional device representation for named colours"},
{"OutputResponse", "Description of the desired device response"},
{"PerceptualRenderingIntentGamut", "When present, the specified gamut is defined to be the reference medium gamut for the PCS side of both the A2B0 and B2A0 tags"},
{"Preview0", "Preview transformation: 8-bit or 16-bit data"},
{"Preview1", "Preview transformation: 8-bit or 16-bit data"},
{"Preview2", "Preview transformation: 8-bit or 16-bit data"},
{"ProfileDescription", "Structure containing invariant and localizable versions of the profile name for displays"},
{"ProfileSequenceDesc", "An array of descriptions of the profile sequence"},
{"RedMatrixColumn", "The first column in the matrix used in matrix/TRC transforms. (This column is combined with the linear red channel during the matrix multiplication)."},
{"RedTRC", "Red channel tone reproduction curve"},
{"SaturationRenderingIntentGamut", "When present, the specified gamut is defined to be the reference medium gamut for the PCS side of both the A2B2 and B2A2 tags"},
{"Technology", "Device technology information such as LCD, CRT, Dye Sublimation, etc."},
{"ViewingCondDesc", "Viewing condition description"},
{"ViewingConditions", "Viewing condition parameters"}
};
public static String[][] Technology = {
{"fscn", "Film scanner"},
{"dcam", "Digital camera"},
{"rscn", "Reflective scanner"},
{"ijet", "Ink jet printer"},
{"twax", "Thermal wax printer"},
{"epho", "Electrophotographic printer"},
{"esta", "Electrostatic printer"},
{"dsub", "Dye sublimation printer"},
{"rpho", "Photographic paper printer"},
{"fprn", "Film writer"},
{"vidm", "Video monitor"},
{"vidc", "Video camera"},
{"pjtv", "Projection television"},
{"CRT ", "Cathode ray tube display"},
{"PMD ", "Passive matrix display"},
{"AMD ", "Active matrix display"},
{"KPCD", "Photo CD"},
{"imgs", "Photographic image setter"},
{"grav", "Gravure"},
{"offs", "Offset lithography"},
{"silk", "Silkscreen"},
{"flex", "Flexography"},
{"mpfs", "Motion picture film scanner"},
{"mpfr", "Motion picture film recorder"},
{"dmpc", "Digital motion picture camera"},
{"dcpj", "Digital cinema projector"}
};
public static String technology(String value) {
for (String[] item : Technology) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static List<String> technologyTypes() {
List<String> types = new ArrayList<>();
for (String[] item : Technology) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
/*
Set/Get
*/
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@SuppressWarnings("unchecked")
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public TagType getType() {
return type;
}
public void setType(TagType type) {
this.type = type;
}
public List<String> getValueSelection() {
return valueSelection;
}
public void setValueSelection(List<String> valueSelection) {
this.valueSelection = valueSelection;
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public boolean isIsHeaderField() {
return isHeaderField;
}
public void setIsHeaderField(boolean isHeaderField) {
this.isHeaderField = isHeaderField;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public boolean isSelectionEditable() {
return selectionEditable;
}
public void setSelectionEditable(boolean selectionEditable) {
this.selectionEditable = selectionEditable;
}
public List<String> getArrayNames() {
return arrayNames;
}
public void setArrayNames(List<String> arrayNames) {
this.arrayNames = arrayNames;
}
public int getSize() {
size = bytes.length;
return size;
}
public void setSize(int size) {
this.size = size;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/IccHeader.java | alpha/MyBox/src/main/java/mara/mybox/color/IccHeader.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import mara.mybox.color.IccTag.TagType;
import static mara.mybox.color.IccXML.iccHeaderXml;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.ByteTools;
import static mara.mybox.tools.ByteTools.bytesToHex;
import static mara.mybox.tools.ByteTools.bytesToHexFormat;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-12
* @Description
* @License Apache License Version 2.0
*/
public class IccHeader {
private byte[] header;
private LinkedHashMap<String, IccTag> fields;
private boolean isValid;
private String error;
public IccHeader(byte[] data) {
try {
this.header = ByteTools.subBytes(data, 0, 128);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public LinkedHashMap<String, IccTag> readFields() {
if (header == null) {
return null;
}
if (fields == null) {
fields = iccHeaderFields(header);
}
return fields;
}
public IccTag field(String name) {
try {
return getFields().get(name);
} catch (Exception e) {
return null;
}
}
public Object value(String name) {
try {
IccTag tag = getFields().get(name);
return tag.getValue();
} catch (Exception e) {
return null;
}
}
public String hex(int offset, int size) {
try {
return bytesToHexFormat(subBytes(header, offset, size));
} catch (Exception e) {
return null;
}
}
public String xml() {
try {
return iccHeaderXml(getFields());
} catch (Exception e) {
return null;
}
}
public boolean update(byte[] newHeader) {
if (newHeader == null || newHeader.length != 128) {
return false;
}
LinkedHashMap<String, IccTag> newFields = iccHeaderFields(newHeader);
if (newFields == null) {
return false;
}
this.header = newHeader;
fields = newFields;
return true;
}
/*
Methods based on bytes
*/
public static LinkedHashMap<String, IccTag> iccHeaderFields(byte[] header) {
try {
LinkedHashMap<String, IccTag> fields = new LinkedHashMap<>();
fields.put("ProfileSize",
new IccTag("ProfileSize", 0, subBytes(header, 0, 4), TagType.Int,
bytesToInt(subBytes(header, 0, 4))));
fields.put("CMMType",
new IccTag("CMMType", 4, subBytes(header, 4, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 4, 4)), DeviceManufacturers(), true));
fields.put("ProfileVersion",
new IccTag("ProfileVersion", 8, subBytes(header, 8, 2), TagType.Text,
profileVersion(subBytes(header, 8, 2))));
fields.put("ProfileDeviceClass",
new IccTag("ProfileDeviceClass", 12, subBytes(header, 12, 4), TagType.Text,
profileDeviceClassDisplay(subBytes(header, 12, 4)), ProfileDeviceClasses(), false));
fields.put("ColorSpaceType",
new IccTag("ColorSpaceType", 16, subBytes(header, 16, 4), TagType.Text,
colorSpaceType(subBytes(header, 16, 4)), ColorSpaceTypes(), true));
fields.put("PCSType",
new IccTag("PCSType", 20, subBytes(header, 20, 4), TagType.Text,
new String(subBytes(header, 20, 4)), PCSTypes(), false));
fields.put("CreateTime",
new IccTag("CreateTime", 24, subBytes(header, 24, 12), TagType.Text,
IccTagType.dateTimeString(subBytes(header, 24, 12))));
fields.put("ProfileFile",
new IccTag("ProfileFile", 36, subBytes(header, 36, 4), TagType.Text,
new String(subBytes(header, 36, 4))));
fields.put("PrimaryPlatform",
new IccTag("PrimaryPlatform", 40, subBytes(header, 40, 4), TagType.Text,
primaryPlatformDisplay(subBytes(header, 40, 4)), PrimaryPlatforms(), false));
boolean[] profileFlags = IccHeader.profileFlags(header[47]);
byte[] bytes = subBytes(header, 44, 4);
fields.put("ProfileFlagEmbedded",
new IccTag("ProfileFlagEmbedded", 44, bytes, TagType.Boolean,
profileFlags[0]));
fields.put("ProfileFlagIndependently",
new IccTag("ProfileFlagIndependently", 44, bytes, TagType.Boolean,
!profileFlags[1]));
fields.put("ProfileFlagMCSSubset",
new IccTag("ProfileFlagMCSSubset", 44, bytes, TagType.Boolean,
profileFlags[2]));
fields.put("DeviceManufacturer",
new IccTag("DeviceManufacturer", 48, subBytes(header, 48, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 48, 4)), DeviceManufacturers(), true));
fields.put("DeviceModel",
new IccTag("DeviceModel", 52, subBytes(header, 52, 4), TagType.Text,
new String(subBytes(header, 52, 4))));
bytes = subBytes(header, 56, 8);
boolean[] deviceAttributes = IccHeader.deviceAttributes(header[63]);
fields.put("DeviceAttributeTransparency",
new IccTag("DeviceAttributeTransparency", 56, bytes, TagType.Boolean,
deviceAttributes[0]));
fields.put("DeviceAttributeMatte",
new IccTag("DeviceAttributeMatte", 56, bytes, TagType.Boolean,
deviceAttributes[1]));
fields.put("DeviceAttributeNegative",
new IccTag("DeviceAttributeNegative", 56, bytes, TagType.Boolean,
deviceAttributes[2]));
fields.put("DeviceAttributeBlackOrWhite",
new IccTag("DeviceAttributeBlackOrWhite", 56, bytes, TagType.Boolean,
deviceAttributes[3]));
fields.put("DeviceAttributePaperBased",
new IccTag("DeviceAttributePaperBased", 56, bytes, TagType.Boolean,
!deviceAttributes[4]));
fields.put("DeviceAttributeTextured",
new IccTag("DeviceAttributeTextured", 56, bytes, TagType.Boolean,
deviceAttributes[5]));
fields.put("DeviceAttributeIsotropic",
new IccTag("DeviceAttributeIsotropic", 56, bytes, TagType.Boolean,
!deviceAttributes[6]));
fields.put("DeviceAttributeSelfLuminous",
new IccTag("DeviceAttributeSelfLuminous", 56, bytes, TagType.Boolean,
deviceAttributes[7]));
fields.put("RenderingIntent",
new IccTag("RenderingIntent", 64, subBytes(header, 64, 4), TagType.Text,
renderingIntentDisplay(subBytes(header, 64, 4)), RenderingIntents(), true));
double[] xyz = IccTagType.XYZNumber(subBytes(header, 68, 12));
fields.put("PCCIlluminantX",
new IccTag("PCCIlluminantX", 68, subBytes(header, 68, 4), TagType.Double,
xyz[0]));
fields.put("PCCIlluminantY",
new IccTag("PCCIlluminantY", 72, subBytes(header, 72, 4), TagType.Double,
xyz[1]));
fields.put("PCCIlluminantZ",
new IccTag("PCCIlluminantZ", 76, subBytes(header, 76, 4), TagType.Double,
xyz[2]));
fields.put("Creator",
new IccTag("Creator", 80, subBytes(header, 80, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 80, 4)), DeviceManufacturers(), true));
fields.put("ProfileID",
new IccTag("ProfileID", 84, subBytes(header, 84, 16), TagType.Bytes,
bytesToHexFormat(subBytes(header, 84, 16))));
fields.put("SpectralPCS",
new IccTag("SpectralPCS", 100, subBytes(header, 100, 4), TagType.Text,
new String(subBytes(header, 100, 4))));
fields.put("SpectralPCSWaveLengthRange",
new IccTag("SpectralPCSWaveLengthRange", 104, subBytes(header, 104, 6), TagType.Bytes,
bytesToHexFormat(subBytes(header, 104, 6))));
fields.put("BispectralPCSWaveLengthRange",
new IccTag("BispectralPCSWaveLengthRange", 110, subBytes(header, 110, 6), TagType.Bytes,
bytesToHexFormat(subBytes(header, 110, 6))));
fields.put("MCS",
new IccTag("MCS", 116, subBytes(header, 116, 4), TagType.Bytes,
bytesToHexFormat(subBytes(header, 116, 4))));
fields.put("ProfileDeviceSubclass",
new IccTag("ProfileDeviceSubclass", 120, subBytes(header, 120, 4), TagType.Text,
new String(subBytes(header, 120, 4))));
fields.put("ProfileSubclassVersion",
new IccTag("ProfileSubclassVersion", 104, subBytes(header, 104, 6), TagType.Double,
Float.parseFloat((int) (header[10]) + "." + (int) (header[11]))));
return fields;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
Decode values of Header Fields
*/
public static String profileVersion(byte[] value) {
int major = (int) value[0];
int minor = (value[1] & 0xff) >>> 4;
int bug = value[1] & 0x0f;
return major + "." + minor + "." + bug + ".0";
}
public static boolean[] profileFlags(byte value) {
boolean[] values = new boolean[3];
values[0] = (value & 0x01) == 0x01;
values[1] = (value & 0x02) == 0x02;
values[2] = (value & 0x04) == 0x04;
return values;
}
public static boolean[] deviceAttributes(byte value) {
boolean[] values = new boolean[8];
values[0] = (value & 0x01) == 0x01;
values[1] = (value & 0x02) == 0x02;
values[2] = (value & 0x04) == 0x04;
values[3] = (value & 0x08) == 0x08;
values[4] = (value & 0x10) == 0x10;
values[5] = (value & 0x20) == 0x20;
values[6] = (value & 0x40) == 0x40;
values[7] = (value & 0x80) == 0x80;
return values;
}
public static String colorSpaceType(byte[] value) {
String cs = new String(value);
if (cs.startsWith("nc")) {
cs = "nc" + bytesToHex(subBytes(value, 2, 2)).toUpperCase();
}
return cs;
}
public static String renderingIntent(byte[] value) {
int intv = bytesToInt(value);
switch (intv) {
case 0:
return "Perceptual";
case 1:
return "MediaRelativeColorimetric";
case 2:
return "Saturation";
case 3:
return "ICCAbsoluteColorimetric";
default:
return bytesToHex(value);
}
}
/*
Display of Header Fields
*/
public static String deviceManufacturerDisplay(byte[] value) {
return deviceManufacturerDisplay(new String(value));
}
public static String deviceManufacturerDisplay(String value) {
for (String[] item : DeviceManufacturers) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static String profileDeviceClassDisplay(byte[] value) {
return profileDeviceClassDisplay(new String(value));
}
public static String profileDeviceClassDisplay(String value) {
for (String[] item : ProfileDeviceClasses) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + Languages.message(item[1]);
}
}
return value;
}
public static String primaryPlatformDisplay(byte[] value) {
return primaryPlatformDisplay(new String(value));
}
public static String primaryPlatformDisplay(String value) {
for (String[] item : PrimaryPlatforms) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static String renderingIntentDisplay(byte[] value) {
int intv = bytesToInt(value);
switch (intv) {
case 0:
return Languages.message("Perceptual");
case 1:
return Languages.message("MediaRelativeColorimetric");
case 2:
return Languages.message("Saturation");
case 3:
return Languages.message("ICCAbsoluteColorimetric");
default:
return bytesToHex(value);
}
}
/*
Encode values of Header Fields
*/
public static byte[] profileVersion(String value) {
byte[] bytes = new byte[4];
try {
String[] values = value.split(".");
if (values.length > 0) {
bytes[0] = ByteTools.intSmallByte(Integer.parseInt(values[0]));
if (values.length > 1) {
Byte b = ByteTools.intSmallByte(Integer.parseInt(values[1]));
bytes[1] = (byte) (b << 4);
if (values.length > 2) {
b = ByteTools.intSmallByte(Integer.parseInt(values[2]));
bytes[1] = (byte) (bytes[1] & b);
}
}
}
} catch (Exception e) {
}
return bytes;
}
public static byte[] colorSpaceType(String value) {
if (!value.startsWith("nc")) {
return IccProfile.first4ASCII(value);
}
byte[] bytes = new byte[4];
try {
if (value.length() < 6) {
return bytes;
}
byte[] vBytes = IccProfile.toBytes("nc");
System.arraycopy(vBytes, 0, bytes, 0, 2);
vBytes = ByteTools.hexToBytes(value.substring(2, 6));
System.arraycopy(vBytes, 0, bytes, 2, 2);
} catch (Exception e) {
}
return bytes;
}
public static byte[] profileFlags(boolean Embedded,
boolean Independently, boolean MCSSubset) {
int v = Embedded ? 0x01 : 0;
v = v | (Independently ? 0 : 0x02);
v = v | (MCSSubset ? 0x04 : 0);
return intToBytes(v);
}
public static byte[] deviceAttributes(
boolean Transparency, boolean Matte, boolean Negative, boolean BlackOrWhite,
boolean PaperBased, boolean Textured, boolean Isotropic, boolean SelfLuminous) {
int v = Transparency ? 0x01 : 0;
v = v | (Matte ? 0x02 : 0);
v = v | (Negative ? 0x04 : 0);
v = v | (BlackOrWhite ? 0x08 : 0);
v = v | (PaperBased ? 0 : 0x10);
v = v | (Textured ? 0x20 : 0);
v = v | (Isotropic ? 0 : 0x40);
v = v | (SelfLuminous ? 0x80 : 0);
byte[] bytes = intToBytes(v);
byte[] bytes8 = new byte[8];
System.arraycopy(bytes, 0, bytes8, 4, 4);
return bytes8;
}
public static byte[] RenderingIntent(String value) {
byte[] bytes = new byte[4];
if ("Perceptual".equals(value)
|| Languages.message("Perceptual").equals(value)) {
bytes[3] = 0;
} else if ("MediaRelativeColorimetric".equals(value)
|| Languages.message("MediaRelativeColorimetric").equals(value)) {
bytes[3] = 1;
} else if ("Saturation".equals(value)
|| Languages.message("Saturation").equals(value)) {
bytes[3] = 2;
} else if ("ICCAbsoluteColorimetric".equals(value)
|| Languages.message("ICCAbsoluteColorimetric").equals(value)) {
bytes[3] = 3;
}
return bytes;
}
/*
Data
*/
public static List<String> ProfileDeviceClasses() {
List<String> types = new ArrayList<>();
for (String[] item : ProfileDeviceClasses) {
types.add(item[0] + AppValues.Indent + Languages.message(item[1]));
}
return types;
}
public static String[][] ProfileDeviceClasses = {
{"scnr", "InputDeviceProfile"},
{"mntr", "DisplayDeviceProfile"},
{"prtr", "OutputDeviceProfile"},
{"link", "DeviceLinkProfile"},
{"abst", "AbstractProfile"},
{"spac", "ColorSpaceConversionProfile"},
{"nmcl", "NamedColorProfile"},
{"cenc", "ColorEncodingSpaceProfile"},
{"mid ", "MultiplexIdentificationProfile"},
{"mlnk", "MultiplexLinkProfile"},
{"mvis", "MultiplexVisualizationProfile"}
};
public static List<String> PrimaryPlatforms() {
List<String> types = new ArrayList<>();
for (String[] item : PrimaryPlatforms) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
public static String[][] PrimaryPlatforms = {
{"APPL", "Apple Computer Inc."},
{"MSFT", "Microsoft Corporation"},
{"SGI ", "Silicon Graphics Inc."},
{"SUNW", "Sun Microsystems Inc."},
{"TGNT", "Taligent Inc."}
};
public static List<String> ColorSpaceTypes() {
return Arrays.asList(ColorSpaceTypes);
}
public static String[] ColorSpaceTypes = {
"XYZ ", "Lab ", "Luv ", "YCbr", "Yxy ", "LMS ", "RGB ", "GRAY", "HSV ", "HLS ", "CMYK", "CMY ",
"2CLR", "3CLR", "4CLR", "5CLR", "6CLR", "7CLR", "8CLR", "9CLR",
"ACLR", "BCLR", "CCLR", "DCLR", "ECLR", "FCLR"
};
public static List<String> PCSTypes() {
return Arrays.asList(PCSTypes);
}
public static String[] PCSTypes = {
"XYZ ", "Lab ", " "
};
public static List<String> RenderingIntents() {
return Arrays.asList(RenderingIntents);
}
public static String[] RenderingIntents = {
"Perceptual", "MediaRelativeColorimetric", "Saturation", "ICCAbsoluteColorimetric"
};
public static List<String> DeviceManufacturers() {
List<String> types = new ArrayList<>();
for (String[] item : DeviceManufacturers) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
public static String[][] DeviceManufacturers = {
{"4d2p", "Erdt Systems GmbH & Co KG"},
{"AAMA", "Aamazing Technologies, Inc."},
{"ACER", "Acer Peripherals"},
{"ACLT", "Acolyte Color Research"},
{"ACTI", "Actix Sytems, Inc."},
{"ADAR", "Adara Technology, Inc."},
{"ADBE", "Adobe Systems Inc."},
{"ADI ", "ADI Systems, Inc."},
{"AGFA", "Agfa Graphics N.V."},
{"ALMD", "Alps Electric USA, Inc."},
{"ALPS", "Alps Electric USA, Inc."},
{"ALWN", "Alwan Color Expertise"},
{"AMTI", "Amiable Technologies, Inc."},
{"AOC ", "AOC International (U.S.A), Ltd."},
{"APAG", "Apago"},
{"APPL", "Apple Computer Inc."},
{"AST ", "AST"},
{"AT&T", "AT&T Computer Systems"},
{"BAEL", "BARBIERI electronic"},
{"BRCO", "Barco NV"},
{"BRKP", "Breakpoint Pty Limited"},
{"BROT", "Brother Industries, LTD"},
{"BULL", "Bull"},
{"BUS ", "Bus Computer Systems"},
{"C-IT", "C-Itoh"},
{"CAMR", "Intel Corporation"},
{"CANO", "Canon, Inc. (Canon Development Americas, Inc.)"},
{"CARR", "Carroll Touch"},
{"CASI", "Casio Computer Co., Ltd."},
{"CBUS", "Colorbus PL"},
{"CEL ", "Crossfield"},
{"CELx", "Crossfield"},
{"CGS ", "CGS Publishing Technologies International GmbH"},
{"CHM ", "Rochester Robotics"},
{"CIGL", "Colour Imaging Group, London"},
{"CITI", "Citizen"},
{"CL00", "Candela, Ltd."},
{"CLIQ", "Color IQ"},
{"CMCO", "Chromaco, Inc."},
{"CMiX", "CHROMiX"},
{"COLO", "Colorgraphic Communications Corporation"},
{"COMP", "COMPAQ Computer Corporation"},
{"COMp", "Compeq USA/Focus Technology"},
{"CONR", "Conrac Display Products"},
{"CORD", "Cordata Technologies, Inc."},
{"CPQ ", "Compaq Computer Corporation"},
{"CPRO", "ColorPro"},
{"CRN ", "Cornerstone"},
{"CTX ", "CTX International, Inc."},
{"CVIS", "ColorVision"},
{"CWC ", "Fujitsu Laboratories, Ltd."},
{"DARI", "Darius Technology, Ltd."},
{"DATA", "Dataproducts"},
{"DCP ", "Dry Creek Photo"},
{"DCRC", "Digital Contents Resource Center, Chung-Ang University"},
{"DELL", "Dell Computer Corporation"},
{"DIC ", "Dainippon Ink and Chemicals"},
{"DICO", "Diconix"},
{"DIGI", "Digital"},
{"DL&C", "Digital Light & Color"},
{"DPLG", "Doppelganger, LLC"},
{"DS ", "Dainippon Screen"},
{"DSOL", "DOOSOL"},
{"DUPN", "DuPont"},
{"EPSO", "Epson"},
{"ESKO", "Esko-Graphics"},
{"ETRI", "Electronics and Telecommunications Research Institute"},
{"EVER", "Everex Systems, Inc."},
{"EXAC", "ExactCODE GmbH"},
{"Eizo", "EIZO NANAO CORPORATION"},
{"FALC", "Falco Data Products, Inc."},
{"FF ", "Fuji Photo Film Co.,LTD"},
{"FFEI", "FujiFilm Electronic Imaging, Ltd."},
{"FNRD", "fnord software"},
{"FORA", "Fora, Inc."},
{"FORE", "Forefront Technology Corporation"},
{"FP ", "Fujitsu"},
{"FPA ", "WayTech Development, Inc."},
{"FUJI", "Fujitsu"},
{"FX ", "Fuji Xerox Co., Ltd."},
{"GCC ", "GCC Technologies, Inc."},
{"GGSL", "Global Graphics Software Limited"},
{"GMB ", "Gretagmacbeth"},
{"GMG ", "GMG GmbH & Co. KG"},
{"GOLD", "GoldStar Technology, Inc."},
{"GOOG", "Google"},
{"GPRT", "Giantprint Pty Ltd"},
{"GTMB", "Gretagmacbeth"},
{"GVC ", "WayTech Development, Inc."},
{"GW2K", "Sony Corporation"},
{"HCI ", "HCI"},
{"HDM ", "Heidelberger Druckmaschinen AG"},
{"HERM", "Hermes"},
{"HITA", "Hitachi America, Ltd."},
{"HP ", "Hewlett-Packard"},
{"HTC ", "Hitachi, Ltd."},
{"HiTi", "HiTi Digital, Inc."},
{"IBM ", "IBM Corporation"},
{"IDNT", "Scitex Corporation, Ltd."},
{"IEC ", "Hewlett-Packard"},
{"IIYA", "Iiyama North America, Inc."},
{"IKEG", "Ikegami Electronics, Inc."},
{"IMAG", "Image Systems Corporation"},
{"IMI ", "Ingram Micro, Inc."},
{"INTC", "Intel Corporation"},
{"INTL", "N/A (INTL)"},
{"INTR", "Intra Electronics USA, Inc."},
{"IOCO", "Iocomm International Technology Corporation"},
{"IPS ", "InfoPrint Solutions Company"},
{"IRIS", "Scitex Corporation, Ltd."},
{"ISL ", "Ichikawa Soft Laboratory"},
{"ITNL", "N/A (ITNL)"},
{"IVM ", "IVM"},
{"IWAT", "Iwatsu Electric Co., Ltd."},
{"Idnt", "Scitex Corporation, Ltd."},
{"Inca", "Inca Digital Printers Ltd."},
{"Iris", "Scitex Corporation, Ltd."},
{"JPEG", "Joint Photographic Experts Group"},
{"JSFT", "Jetsoft Development"},
{"JVC ", "JVC Information Products Co."},
{"KART", "Scitex Corporation, Ltd."},
{"KFC ", "KFC Computek Components Corporation"},
{"KLH ", "KLH Computers"},
{"KMHD", "Konica Minolta Holdings, Inc."},
{"KNCA", "Konica Corporation"},
{"KODA", "Kodak"},
{"KYOC", "Kyocera"},
{"Kart", "Scitex Corporation, Ltd."},
{"LCAG", "Leica Camera AG"},
{"LCCD", "Leeds Colour"},
{"LDAK", "Left Dakota"},
{"LEAD", "Leading Technology, Inc."},
{"LEXM", "Lexmark International, Inc."},
{"LINK", "Link Computer, Inc."},
{"LINO", "Linotronic"},
{"LITE", "Lite-On, Inc."},
{"Leaf", "Leaf"},
{"Lino", "Linotronic"},
{"MAGC", "Mag Computronic (USA) Inc."},
{"MAGI", "MAG Innovision, Inc."},
{"MANN", "Mannesmann"},
{"MICN", "Micron Technology, Inc."},
{"MICR", "Microtek"},
{"MICV", "Microvitec, Inc."},
{"MINO", "Minolta"},
{"MITS", "Mitsubishi Electronics America, Inc."},
{"MITs", "Mitsuba Corporation"},
{"MNLT", "Minolta"},
{"MODG", "Modgraph, Inc."},
{"MONI", "Monitronix, Inc."},
{"MONS", "Monaco Systems Inc."},
{"MORS", "Morse Technology, Inc."},
{"MOTI", "Motive Systems"},
{"MSFT", "Microsoft Corporation"},
{"MUTO", "MUTOH INDUSTRIES LTD."},
{"Mits", "Mitsubishi Electric Corporation Kyoto Works"},
{"NANA", "NANAO USA Corporation"},
{"NEC ", "NEC Corporation"},
{"NEXP", "NexPress Solutions LLC"},
{"NISS", "Nissei Sangyo America, Ltd."},
{"NKON", "Nikon Corporation"},
{"NONE", "none"},
{"OCE ", "Oce Technologies B.V."},
{"OCEC", "OceColor"},
{"OKI ", "Oki"},
{"OKID", "Okidata"},
{"OKIP", "Okidata"},
{"OLIV", "Olivetti"},
{"OLYM", "OLYMPUS OPTICAL CO., LTD"},
{"ONYX", "Onyx Graphics"},
{"OPTI", "Optiquest"},
{"PACK", "Packard Bell"},
{"PANA", "Matsushita Electric Industrial Co., Ltd."},
{"PANT", "Pantone, Inc."},
{"PBN ", "Packard Bell"},
{"PFU ", "PFU Limited"},
{"PHIL", "Philips Consumer Electronics Co."},
{"PNTX", "HOYA Corporation PENTAX Imaging Systems Division"},
{"POne", "Phase One A/S"},
{"PREM", "Premier Computer Innovations"},
{"PRIN", "Princeton Graphic Systems"},
{"PRIP", "Princeton Publishing Labs"},
{"QLUX", "Hong Kong"},
{"QMS ", "QMS, Inc."},
{"QPCD", "QPcard AB"},
{"QUAD", "QuadLaser"},
{"QUME", "Qume Corporation"},
{"RADI", "Radius, Inc."},
{"RDDx", "Integrated Color Solutions, Inc."},
{"RDG ", "Roland DG Corporation"},
{"REDM", "REDMS Group, Inc."},
{"RELI", "Relisys"},
{"RGMS", "Rolf Gierling Multitools"},
{"RICO", "Ricoh Corporation"},
{"RNLD", "Edmund Ronald"},
{"ROYA", "Royal"},
{"RPC ", "Ricoh Printing Systems,Ltd."},
{"RTL ", "Royal Information Electronics Co., Ltd."},
{"SAMP", "Sampo Corporation of America"},
{"SAMS", "Samsung, Inc."},
{"SANT", "Jaime Santana Pomares"},
{"SCIT", "Scitex Corporation, Ltd."},
{"SCRN", "Dainippon Screen"},
{"SDP ", "Scitex Corporation, Ltd."},
{"SEC ", "SAMSUNG ELECTRONICS CO.,LTD"},
{"SEIK", "Seiko Instruments U.S.A., Inc."},
{"SEIk", "Seikosha"},
{"SGUY", "ScanGuy.com"},
{"SHAR", "Sharp Laboratories"},
{"SICC", "International Color Consortium"},
{"SONY", "SONY Corporation"},
{"SPCL", "SpectraCal"},
{"STAR", "Star"},
{"STC ", "Sampo Technology Corporation"},
{"Scit", "Scitex Corporation, Ltd."},
{"Sdp ", "Scitex Corporation, Ltd."},
{"Sony", "Sony Corporation"},
{"TALO", "Talon Technology Corporation"},
{"TAND", "Tandy"},
{"TATU", "Tatung Co. of America, Inc."},
{"TAXA", "TAXAN America, Inc."},
{"TDS ", "Tokyo Denshi Sekei K.K."},
{"TECO", "TECO Information Systems, Inc."},
{"TEGR", "Tegra"},
{"TEKT", "Tektronix, Inc."},
{"TI ", "Texas Instruments"},
{"TMKR", "TypeMaker Ltd."},
{"TOSB", "TOSHIBA corp."},
{"TOSH", "Toshiba, Inc."},
{"TOTK", "TOTOKU ELECTRIC Co., LTD"},
{"TRIU", "Triumph"},
{"TSBT", "TOSHIBA TEC CORPORATION"},
{"TTX ", "TTX Computer Products, Inc."},
{"TVM ", "TVM Professional Monitor Corporation"},
{"TW ", "TW Casper Corporation"},
{"ULSX", "Ulead Systems"},
{"UNIS", "Unisys"},
{"UTZF", "Utz Fehlau & Sohn"},
{"VARI", "Varityper"},
{"VIEW", "Viewsonic"},
{"VISL", "Visual communication"},
{"VIVO", "Vivo Mobile Communication Co., Ltd"},
{"WANG", "Wang"},
{"WLBR", "Wilbur Imaging"},
{"WTG2", "Ware To Go"},
{"WYSE", "WYSE Technology"},
{"XERX", "Xerox Corporation"},
{"XRIT", "X-Rite"},
{"Z123", "Lavanya's test Company"},
{"ZRAN", "Zoran Corporation"},
{"Zebr", "Zebra Technologies Inc"},
{"appl", "Apple Computer Inc."},
{"bICC", "basICColor GmbH"},
{"berg", "bergdesign incorporated"},
{"ceyd", "Integrated Color Solutions, Inc."},
{"clsp", "MacDermid ColorSpan, Inc."},
{"ds ", "Dainippon Screen"},
{"dupn", "DuPont"},
{"ffei", "FujiFilm Electronic Imaging, Ltd."},
{"flux", "FluxData Corporation"},
{"iris", "Scitex Corporation, Ltd."},
{"kart", "Scitex Corporation, Ltd."},
{"lcms", "Little CMS"},
{"lino", "Linotronic"},
{"none", "none"},
{"ob4d", "Erdt Systems GmbH & Co KG"},
{"obic", "Medigraph GmbH"},
{"quby", "Qubyx Sarl"},
{"scit", "Scitex Corporation, Ltd."},
{"scrn", "Dainippon Screen"},
{"sdp ", "Scitex Corporation, Ltd."},
{"siwi", "SIWI GRAFIKA CORPORATION"},
{"yxym", "YxyMaster GmbH"}
};
/*
Get/Set
*/
public byte[] getHeader() {
return header;
}
public void setHeader(byte[] header) {
this.header = header;
}
public LinkedHashMap<String, IccTag> getFields() {
if (fields == null) {
readFields();
}
return fields;
}
public void setFields(LinkedHashMap<String, IccTag> fields) {
this.fields = fields;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ChromaticAdaptation.java | alpha/MyBox/src/main/java/mara/mybox/color/ChromaticAdaptation.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
// https://ww2.mathworks.cn/help/images/ref/whitepoint.html
// http://www.thefullwiki.org/Standard_illuminant
public class ChromaticAdaptation {
public String source, target;
public String BradfordMethod, XYZScalingMethod, VonKriesMethod;
public ChromaticAdaptation() {
}
public ChromaticAdaptation(String source, String target,
String BradfordMethod, String XYZScalingMethod, String VonKriesMethod) {
this.source = source;
this.target = target;
this.BradfordMethod = BradfordMethod;
this.XYZScalingMethod = XYZScalingMethod;
this.VonKriesMethod = VonKriesMethod;
}
/*
Generation of Chromatic Adaptation matrices
*/
public static List<ChromaticAdaptation> all(int scale) {
List<ChromaticAdaptation> data = new ArrayList<>();
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
double[][] m1 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.Bradford, -1);
double[][] m2 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.XYZScaling, -1);
double[][] m3 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.VonKries, -1);
ChromaticAdaptation ca = new ChromaticAdaptation();
ca.setSource(sourceIlluminant + " - " + sourceObserver);
ca.setTarget(targetIlluminant + " - " + targetObserver);
ca.setBradfordMethod(DoubleMatrixTools.print(m1, 0, scale));
ca.setXYZScalingMethod(DoubleMatrixTools.print(m2, 0, scale));
ca.setVonKriesMethod(DoubleMatrixTools.print(m3, 0, scale));
data.add(ca);
}
}
}
}
return data;
}
public static StringTable table(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("Source"), Languages.message("Target"),
"Bradford", "XYZ", "Von Kries"
));
StringTable table = new StringTable(names, Languages.message("ChromaticAdaptationMatrix"));
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
double[][] m1 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.Bradford, -1);
double[][] m2 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.XYZScaling, -1);
double[][] m3 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.VonKries, -1);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(sourceIlluminant.name() + " - " + sourceObserver.name(),
targetIlluminant.name() + " - " + targetObserver.name(),
DoubleMatrixTools.html(m1, scale),
DoubleMatrixTools.html(m2, scale),
DoubleMatrixTools.html(m3, scale)
));
table.add(row);
}
}
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
for (ChromaticAdaptationAlgorithm a : ChromaticAdaptationAlgorithm.values()) {
double[][] m = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, a, -1);
s.append(Languages.message("Source")).append(": ").append(sourceIlluminant).append(" - ").
append(sourceObserver).append("\n");
s.append(Languages.message("Target")).append(": ").append(targetIlluminant).append(" - ").
append(targetObserver).append("\n");
s.append(Languages.message("Algorithm")).append(": ").append(a).append("\n");
s.append(Languages.message("ChromaticAdaptationMatrix")).append(": ").append("\n");
s.append(DoubleMatrixTools.print(m, 20, scale)).append("\n\n");
}
}
}
}
}
return s.toString();
}
public static double[] adapt(double[] xyz,
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], fromType, fromObserver, toType, toObserver, algorithm);
}
public static double[] adapt(double x, double y, double z,
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm) {
Illuminant from = new Illuminant(fromType, fromObserver);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType, toObserver);
double[][] targetWhitePoint = to.whitePoint();
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static double[] adapt(double[] xyz,
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], fromType, toType, algorithm);
}
public static double[] adapt(double x, double y, double z,
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm) {
Illuminant from = new Illuminant(fromType);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType);
double[][] targetWhitePoint = to.whitePoint();
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static Object adapt(double x, double y, double z,
double sourceWhitePointX, double sourceWhitePointY, double sourceWhitePointZ,
double targetWhitePointX, double targetWhitePointY, double targetWhitePointZ,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
double[][] sourceWhitePoint
= DoubleMatrixTools.columnVector(sourceWhitePointX, sourceWhitePointY, sourceWhitePointZ);
double[][] targetWhitePoint
= DoubleMatrixTools.columnVector(targetWhitePointX, targetWhitePointY, targetWhitePointZ);
return adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
}
public static double[] adapt(double[] xyz,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], sourceWhitePoint, targetWhitePoint, algorithm);
}
public static double[] adapt(double x, double y, double z,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm) {
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static Object adapt(double[] xyz,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
return adapt(xyz[0], xyz[1], xyz[2], sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
}
public static Object adapt(double x, double y, double z,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
if (DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
double[] result = {x, y, z};
if (isDemo) {
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", Languages.message("NeedNotAdaptChromatic"));
ret.put("matrix", DoubleMatrixTools.identityDouble(3));
ret.put("adaptedColor", result);
return ret;
} else {
return result;
}
}
double[][] adaptMatrix;
String adaptString = null;
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
Map<String, Object> adapt = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) adapt.get("adpatMatrix");
adaptString = (String) adapt.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] sourceColor = DoubleMatrixTools.columnVector(x, y, z);
double[][] adaptedColor = DoubleMatrixTools.multiply(adaptMatrix, sourceColor);
double[] result = DoubleMatrixTools.columnValues(adaptedColor, 0);
if (isDemo) {
String s = "";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptationMatrix") + " aaaaaaaaaaaaa\n\n";
s += adaptString + "\n";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n\n";
s += "SourceColor = \n";
s += DoubleMatrixTools.print(sourceColor, 20, scale);
s += "\nAdaptedColor = M * SourceColor = \n";
s += DoubleMatrixTools.print(adaptedColor, 20, scale);
Map<String, Object> ret = new HashMap<>();
ret.put("matrix", adaptMatrix);
ret.put("procedure", s);
ret.put("adaptedColor", result);
return ret;
} else {
return result;
}
} catch (Exception e) {
return null;
}
}
public static double[][] matrix(
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm, int scale) {
Illuminant from = new Illuminant(fromType);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType);
double[][] targetWhitePoint = to.whitePoint();
return matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static double[][] matrix(
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm, int scale) {
Illuminant from = new Illuminant(fromType, fromObserver);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType, toObserver);
double[][] targetWhitePoint = to.whitePoint();
return matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static double[][] matrix(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale) {
return (double[][]) matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, false);
}
public static Map<String, Object> matrixDemo(
double sourceWhitePointX, double sourceWhitePointY, double sourceWhitePointZ,
double targetWhitePointX, double targetWhitePointY, double targetWhitePointZ,
ChromaticAdaptationAlgorithm algorithm, int scale) {
double[][] sourceWhitePoint = DoubleMatrixTools.columnVector(sourceWhitePointX, sourceWhitePointY, sourceWhitePointZ);
double[][] targetWhitePoint = DoubleMatrixTools.columnVector(targetWhitePointX, targetWhitePointY, targetWhitePointZ);
return ChromaticAdaptation.matrixDemo(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static Map<String, Object> matrixDemo(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale) {
return (Map<String, Object>) matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, true);
}
public static Object matrix(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
if (targetWhitePoint == null || DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", Languages.message("NeedNotAdaptChromatic"));
ret.put("adpatMatrix", DoubleMatrixTools.identityDouble(3));
return ret;
} else {
return DoubleMatrixTools.identityDouble(3);
}
}
double[][] MA, MAI;
if (algorithm == null) {
algorithm = ChromaticAdaptationAlgorithm.Bradford;
}
switch (algorithm) {
case Bradford:
MA = Bradford;
MAI = BradfordInversed;
break;
case XYZScaling:
MA = XYZScaling;
MAI = XYZScalingInversed;
break;
case VonKries:
MA = VonKries;
MAI = VonKriesInversed;
break;
default:
return null;
}
double[][] sourceCone = DoubleMatrixTools.multiply(MA, sourceWhitePoint);
double[][] targetCone = DoubleMatrixTools.multiply(MA, targetWhitePoint);
double[][] ratioMatrix = new double[3][3];
ratioMatrix[0][0] = targetCone[0][0] / sourceCone[0][0];
ratioMatrix[1][1] = targetCone[1][0] / sourceCone[1][0];
ratioMatrix[2][2] = targetCone[2][0] / sourceCone[2][0];
double[][] M = DoubleMatrixTools.multiply(MAI, ratioMatrix);
M = DoubleMatrixTools.multiply(M, MA);
if (scale >= 0) {
M = DoubleMatrixTools.scale(M, scale);
} else {
scale = 8;
}
if (isDemo) {
String s = "";
s += "SourceWhitePoint = \n";
s += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
s += "TargetWhitePoint = \n";
s += DoubleMatrixTools.print(targetWhitePoint, 20, scale);
s += "\n" + Languages.message("Algorithm") + ": " + algorithm + "\n";
s += "MA = \n";
s += DoubleMatrixTools.print(MA, 20, scale);
s += "MA_Inversed =\n";
s += DoubleMatrixTools.print(MAI, 20, scale);
s += "\n" + "SourceCone = MA * SourceWhitePoint =\n";
s += DoubleMatrixTools.print(sourceCone, 20, scale);
s += "\n" + "TargetCone = MA * TargetWhitePoint =\n";
s += DoubleMatrixTools.print(targetCone, 20, scale);
s += "\n" + "RatioMatrix = TargetCone / SourceCone =\n";
s += DoubleMatrixTools.print(ratioMatrix, 20, scale);
s += "\n" + "Adaptation_Matrix = MA_Inversed * RatioMatrix * MA =\n";
s += DoubleMatrixTools.print(M, 20, scale);
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", s);
ret.put("adpatMatrix", M);
return ret;
} else {
return M;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Chromatic Adaptation matrix
Algorithm: Bradford
*/
public static double[] AtoD50(double[] a) {
double[][] matrix = {
{0.8779529, -0.0915288, 0.2566181},
{-0.1117372, 1.0924325, 0.0851788},
{0.0502012, -0.0837636, 2.3994031}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, a);
return d50;
}
public static double[] BtoD50(double[] b) {
double[][] matrix = {
{0.9850292, -0.0093910, -0.0026720},
{-0.0147751, 1.0146711, -0.0000389},
{-0.0017035, 0.0035957, 0.9660561}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, b);
return d50;
}
public static double[] CtoD50(double[] c) {
double[][] matrix = {
{1.0376976, 0.0153932, -0.0582624},
{0.0170675, 1.0056038, -0.0188973},
{-0.0120126, 0.0204361, 0.6906380}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, c);
return d50;
}
public static double[] EtoD65(double[] e) {
double[][] matrix = {
{0.9531874, -0.0265906, 0.0238731},
{-0.0382467, 1.0288406, 0.0094060},
{0.0026068, -0.0030332, 1.0892565}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, e);
return d65;
}
public static double[] EtoD50(double[] e) {
double[][] matrix = {
{0.9977545, -0.0041632, -0.0293713},
{-0.0097677, 1.0183168, -0.0085490},
{-0.0074169, 0.0134416, 0.8191853}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, e);
return d65;
}
public static double[] D50toE(double[] d50) {
double[][] matrix = {
{1.0025535, 0.0036238, 0.0359837},
{0.0096914, 0.9819125, 0.0105947},
{0.0089181, -0.0160789, 1.2208770}
};
double[] e = DoubleMatrixTools.multiply(matrix, d50);
return e;
}
public static double[] D50toD65(double[] d50) {
double[][] matrix = {
{0.9555766, -0.0230393, 0.0631636},
{-0.0282895, 1.0099416, 0.0210077},
{0.0122982, -0.0204830, 1.3299098}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, d50);
return d65;
}
public static double[] D55toD50(double[] d55) {
double[][] matrix = {
{1.0184567, 0.0093864, -0.0213199},
{0.0120291, 0.9951460, -0.0072228},
{-0.0039673, 0.0064899, 0.8925936}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, d55);
return d50;
}
public static double[] D65toE(double[] d65) {
double[][] matrix = {
{1.0502616, 0.0270757, -0.0232523},
{0.0390650, 0.9729502, -0.0092579},
{-0.0024047, 0.0026446, 0.9180873}
};
double[] e = DoubleMatrixTools.multiply(matrix, d65);
return e;
}
public static double[] D65toD50(double[] d65) {
double[][] matrix = {
{1.0478112, 0.0228866, -0.0501270},
{0.0295424, 0.9904844, -0.0170491},
{-0.0092345, 0.0150436, 0.7521316}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, d65);
return d50;
}
/*
Data
*/
public static enum ChromaticAdaptationAlgorithm {
Bradford, XYZScaling, VonKries
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ChromaticAdaptationAlgorithm c : ChromaticAdaptationAlgorithm.values()) {
names.add(c + "");
}
return names;
}
// Chromatic Adaptation Algorithms
public static double[][] XYZScaling = {
{1.0000000, 0.0000000, 0.0000000},
{0.0000000, 1.0000000, 0.0000000},
{0.0000000, 0.0000000, 1.0000000}
};
public static double[][] XYZScalingInversed = {
{1.0000000, 0.0000000, 0.0000000},
{0.0000000, 1.0000000, 0.0000000},
{0.0000000, 0.0000000, 1.0000000}
};
public static double[][] Bradford = {
{0.8951000, 0.2664000, -0.1614000},
{-0.7502000, 1.7135000, 0.0367000},
{0.0389000, -0.0685000, 1.0296000}
};
public static double[][] BradfordInversed = {
{0.9869929, -0.1470543, 0.1599627},
{0.4323053, 0.5183603, 0.0492912},
{-0.0085287, 0.0400428, 0.9684867}
};
public static double[][] VonKries = {
{0.4002400, 0.7076000, -0.0808100},
{-0.2263000, 1.1653200, 0.0457000},
{0.0000000, 0.0000000, 0.9182200}
};
public static double[][] VonKriesInversed = {
{1.8599364, -1.1293816, 0.2198974},
{0.3611914, 0.6388125, -0.0000064},
{0.0000000, 0.0000000, 1.0890636}
};
/*
get/set
*/
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getBradfordMethod() {
return BradfordMethod;
}
public void setBradfordMethod(String BradfordMethod) {
this.BradfordMethod = BradfordMethod;
}
public String getXYZScalingMethod() {
return XYZScalingMethod;
}
public void setXYZScalingMethod(String XYZScalingMethod) {
this.XYZScalingMethod = XYZScalingMethod;
}
public String getVonKriesMethod() {
return VonKriesMethod;
}
public void setVonKriesMethod(String VonKriesMethod) {
this.VonKriesMethod = VonKriesMethod;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ColorValue.java | alpha/MyBox/src/main/java/mara/mybox/color/ColorValue.java | package mara.mybox.color;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-5-24 7:59:40
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorValue {
public static enum ColorType {
CIEXYZ, CIExyY, CIELab, CIELCH, CIELuv,
sRGB, AdobeRGB, AppleRGB, CIERGB, PALRGB, NTSCRGB, ColorMatchRGB, ProPhotoRGB, SMPTECRGB,
HSB, CMYK
}
private ColorType type;
private double d1, d2, d3, d4;
private int i1 = -1, i2 = -1, i3 = -1, i4 = -1;
private String colorSpace, conditions, values,
gamma, illuminant, v1, v2, v3, v4;
public ColorValue(String colorSpace, String conditions, double[] values) {
this.colorSpace = colorSpace;
d1 = DoubleTools.scale(values[0], 2);
d2 = DoubleTools.scale(values[1], 2);
d3 = DoubleTools.scale(values[2], 2);
this.values = d1 + " " + d2 + " " + d3;
if (values.length == 4) {
d4 = DoubleTools.scale(values[3], 2);
this.values += " " + d4;
}
this.conditions = conditions;
}
public ColorValue(String colorSpace, String conditions, double[] values, int scale) {
this.colorSpace = colorSpace;
d1 = Math.round(values[0] * scale);
d2 = Math.round(values[1] * scale);
d3 = Math.round(values[2] * scale);
this.values = (int) d1 + " " + (int) d2 + " " + (int) d3;
if (values.length == 4) {
d4 = Math.round(values[3] * scale);
this.values += " " + (int) d4;
}
this.conditions = conditions;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double[] values) {
this.colorSpace = colorSpace;
d1 = DoubleTools.scale(values[0], 8);
d2 = DoubleTools.scale(values[1], 8);
d3 = DoubleTools.scale(values[2], 8);
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double[] values, int scale) {
this.colorSpace = colorSpace;
d1 = Math.round(values[0] * scale);
d2 = Math.round(values[1] * scale);
d3 = Math.round(values[2] * scale);
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double v1, double v2, double v3) {
this.colorSpace = colorSpace;
d1 = v1;
d2 = v2;
d3 = v3;
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double v1, double v2, double v3, double v4) {
this.colorSpace = colorSpace;
d1 = v1;
d2 = v2;
d3 = v3;
d4 = v4;
this.gamma = gamma;
this.illuminant = illuminant;
}
public final void scale() {
if (type == null) {
return;
}
int ratio = 0;
switch (type) {
case CIEXYZ:
case CMYK:
ratio = 100;
break;
case sRGB:
case AdobeRGB:
case AppleRGB:
case CIERGB:
case PALRGB:
case NTSCRGB:
case ColorMatchRGB:
case ProPhotoRGB:
case SMPTECRGB:
ratio = 255;
break;
default:
return;
}
i1 = (int) Math.round(ratio * d1);
i2 = (int) Math.round(ratio * d2);
i3 = (int) Math.round(ratio * d3);
i4 = (int) Math.round(ratio * d4);
}
/*
get/set
*/
public ColorType getType() {
return type;
}
public void setType(ColorType type) {
this.type = type;
}
public double getD1() {
return d1;
}
public void setD1(double d1) {
this.d1 = d1;
}
public double getD2() {
return d2;
}
public void setD2(double d2) {
this.d2 = d2;
}
public double getD3() {
return d3;
}
public void setD3(double d3) {
this.d3 = d3;
}
public double getD4() {
return d4;
}
public void setD4(double d4) {
this.d4 = d4;
}
public int getI1() {
return i1;
}
public void setI1(int i1) {
this.i1 = i1;
}
public int getI2() {
return i2;
}
public void setI2(int i2) {
this.i2 = i2;
}
public int getI3() {
return i3;
}
public void setI3(int i3) {
this.i3 = i3;
}
public int getI4() {
return i4;
}
public void setI4(int i4) {
this.i4 = i4;
}
public String getGamma() {
return gamma;
}
public void setGamma(String gamma) {
this.gamma = gamma;
}
public String getIlluminant() {
return illuminant;
}
public void setIlluminant(String illuminant) {
this.illuminant = illuminant;
}
public String getColorSpace() {
return colorSpace;
}
public void setColorSpace(String colorSpace) {
this.colorSpace = colorSpace;
}
public String getConditions() {
return conditions;
}
public void setConditions(String conditions) {
this.conditions = conditions;
}
public String getValues() {
return values;
}
public void setValues(String values) {
this.values = values;
}
public String getV1() {
return v1;
}
public void setV1(String v1) {
this.v1 = v1;
}
public String getV2() {
return v2;
}
public void setV2(String v2) {
this.v2 = v2;
}
public String getV3() {
return v3;
}
public void setV3(String v3) {
this.v3 = v3;
}
public String getV4() {
return v4;
}
public void setV4(String v4) {
this.v4 = v4;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/AppleRGB.java | alpha/MyBox/src/main/java/mara/mybox/color/AppleRGB.java | package mara.mybox.color;
import static mara.mybox.color.RGBColorSpace.gamma18;
import static mara.mybox.color.RGBColorSpace.linear18;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:17:46
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class AppleRGB {
public static double linearAppleRGB(double v) {
return linear18(v);
}
public static double gammaAppleRGB(double v) {
return gamma18(v);
}
public static double[] gammaAppleRGB(double[] linearRGB) {
double[] rgb = new double[3];
rgb[0] = gamma18(linearRGB[0]);
rgb[1] = gamma18(linearRGB[1]);
rgb[2] = gamma18(linearRGB[2]);
return rgb;
}
public static double[] AppleRGBtoXYZ(double[] applergb) {
double linearRed = linearAppleRGB(applergb[0]);
double linearGreen = linearAppleRGB(applergb[1]);
double linearBlue = linearAppleRGB(applergb[2]);
double[] xyz = new double[3];
xyz[0] = 0.4497288 * linearRed + 0.3162486 * linearGreen + 0.1844926 * linearBlue;
xyz[1] = 0.2446525 * linearRed + 0.6720283 * linearGreen + 0.0833192 * linearBlue;
xyz[2] = 0.0251848 * linearRed + 0.1411824 * linearGreen + 0.9224628 * linearBlue;
return xyz;
}
public static double[] XYZtoAppleRGB(double[] xyz) {
double linearRed = 2.9515373 * xyz[0] - 1.2894116 * xyz[1] - 0.4738445 * xyz[2];
double linearGreen = -1.0851093 * xyz[0] + 1.9908566 * xyz[1] + 0.0372026 * xyz[2];
double linearBlue = 0.0854934 * xyz[0] - 0.2694964 * xyz[1] + 1.0912975 * xyz[2];
double[] applergb = new double[3];
applergb[0] = gammaAppleRGB(linearRed);
applergb[1] = gammaAppleRGB(linearGreen);
applergb[2] = gammaAppleRGB(linearBlue);
return applergb;
}
public static double[] AppleRGBtoSRGB(double[] applergb) {
double[] xyz = AppleRGBtoXYZ(applergb);
return CIEColorSpace.XYZd65toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/IccTags.java | alpha/MyBox/src/main/java/mara/mybox/color/IccTags.java | package mara.mybox.color;
import java.awt.color.ICC_Profile;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.color.IccProfile.toBytes;
import static mara.mybox.color.IccXML.iccTagsXml;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2019-5-6
* @Description
* @License Apache License Version 2.0
*/
public class IccTags {
private byte[] data; // all bytes in the profile, including 128 bytes of header
private List<IccTag> tags;
private String xml;
private boolean isValid, normalizeLut;
private String error;
public IccTags(byte[] data, boolean normalizeLut) {
try {
this.data = data;
this.normalizeLut = normalizeLut;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public List<IccTag> readTags() {
if (data == null) {
return null;
}
if (tags == null) {
tags = iccTagsValues(data, normalizeLut);
}
return tags;
}
public IccTag getTag(String tag) {
if (tags == null) {
tags = iccTagsValues(data, normalizeLut);
}
return getTag(tags, tag);
}
public byte[] update() {
data = encodeTags(tags);
return data;
}
/*
Static methods
*/
public static List<IccTag> iccTagsValues(ICC_Profile profile, boolean normalizedLut) {
if (profile == null) {
return null;
}
byte[] data = profile.getData();
return IccTags.iccTagsValues(data, normalizedLut);
}
public static List<IccTag> iccTagsValues(byte[] data, boolean normalizedLut) {
List<IccTag> tags = new ArrayList<>();
try {
if (data == null || data.length < 132) {
return tags;
}
int number = bytesToInt(subBytes(data, 128, 4));
for (int i = 0; i < number; ++i) {
int offset = bytesToInt(subBytes(data, 136 + i * 12, 4));
int size = bytesToInt(subBytes(data, 140 + i * 12, 4));
IccTag tag = new IccTag(new String(subBytes(data, 132 + i * 12, 4)),
offset, subBytes(data, offset, size), normalizedLut);
tags.add(tag);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return tags;
}
public static IccTag getTag(List<IccTag> tags, String tag) {
if (tags == null || tag == null || tag.trim().isEmpty()) {
return null;
}
for (IccTag iccTag : tags) {
if (iccTag.getTag().equals(tag)) {
return iccTag;
}
}
return null;
}
/*
Encode data
*/
public static byte[] encodeTags(List<IccTag> tags) {
try {
if (tags == null) {
return null;
}
int number = tags.size();
int size = 132 + 12 * number;
for (IccTag tag : tags) {
size += tag.getBytes().length;
int m = size % 4;
if (m > 0) {
size += 4 - m;
}
}
byte[] data = new byte[size];
System.arraycopy(intToBytes(size), 0, data, 0, 4);
System.arraycopy(intToBytes(number), 0, data, 128, 4);
int offset = 132 + 12 * number;
for (int i = 0; i < number; ++i) {
IccTag tag = tags.get(i);
size = tag.getBytes().length;
// Item in Tags Table
byte[] tagBytes = toBytes(tag.getTag());
System.arraycopy(tagBytes, 0, data, 132 + i * 12, 4);
byte[] offsetBytes = intToBytes(offset);
System.arraycopy(offsetBytes, 0, data, 136 + i * 12, 4);
byte[] sizeBytes = intToBytes(size);
System.arraycopy(sizeBytes, 0, data, 140 + i * 12, 4);
// Tag data
System.arraycopy(tag.getBytes(), 0, data, offset, size);
offset += size;
int m = offset % 4;
if (m > 0) {
offset += 4 - m;
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Get/Set
*/
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getXml() {
if (xml == null) {
xml = iccTagsXml(getTags());
}
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
public List<IccTag> getTags() {
if (tags == null) {
readTags();
}
return tags;
}
public void setTags(List<IccTag> tags) {
this.tags = tags;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public boolean isNormalizeLut() {
return normalizeLut;
}
public void setNormalizeLut(boolean normalizeLut) {
this.normalizeLut = normalizeLut;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/RGB2RGBConversionMatrix.java | alpha/MyBox/src/main/java/mara/mybox/color/RGB2RGBConversionMatrix.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import mara.mybox.color.RGBColorSpace.ColorSpaceType;
import static mara.mybox.color.RGBColorSpace.primariesTristimulus;
import static mara.mybox.color.RGBColorSpace.whitePointMatrix;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
// http://brucelindbloom.com/index.html?WorkingSpaceInfo.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
public class RGB2RGBConversionMatrix {
public String source, sourceWhite, target, targetWhite;
public String algorithm, source2target;
public RGB2RGBConversionMatrix() {
}
/*
Generation of Conversion matrices
*/
public static List<RGB2RGBConversionMatrix> all(int scale) {
List<RGB2RGBConversionMatrix> data = new ArrayList<>();
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] source2target = rgb2rgb(source, target, algorithm);
RGB2RGBConversionMatrix c = new RGB2RGBConversionMatrix();
c.setSource(RGBColorSpace.name(source));
c.setSourceWhite(sourceWhite + "");
c.setTarget(RGBColorSpace.name(target));
c.setTargetWhite(RGBColorSpace.illuminantType(target) + "");
c.setAlgorithm(algorithm + "");
c.setSource2target(DoubleMatrixTools.print(source2target, 0, scale));
data.add(c);
}
}
}
return data;
}
public static StringTable allTable(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("SourceColorSpace"),
Languages.message("SourceReferenceWhite"), Languages.message("TargetColorSpace"), Languages.message("TargetReferenceWhite"),
"Bradford", "XYZ", "Von Kries"
));
StringTable table = new StringTable(names, Languages.message("LinearRGB2RGBMatrix"));
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
double[][] m1 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.Bradford);
double[][] m2 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.XYZScaling);
double[][] m3 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.VonKries);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(source), sourceWhite.name(), RGBColorSpace.name(target),
RGBColorSpace.illuminantType(target).name(),
DoubleMatrixTools.html(m1, scale),
DoubleMatrixTools.html(m2, scale),
DoubleMatrixTools.html(m3, scale)
));
table.add(row);
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] source2target = rgb2rgb(source, target, algorithm);
s.append(Languages.message("SourceColorSpace")).append(": ").
append(RGBColorSpace.name(source)).append("\n");
s.append(Languages.message("SourceReferenceWhite")).append(": ").
append(sourceWhite).append("\n");
s.append(Languages.message("TargetColorSpace")).append(": ").
append(RGBColorSpace.name(target)).append("\n");
s.append(Languages.message("TargetReferenceWhite")).append(": ").
append(RGBColorSpace.illuminantType(target)).append("\n");
s.append(Languages.message("AdaptationAlgorithm")).append(": ").
append(algorithm).append("\n");
s.append(Languages.message("LinearRGB2RGBMatrix")).append(": \n");
s.append(DoubleMatrixTools.print(source2target, 20, scale)).append("\n");
}
}
}
return s.toString();
}
public static double[][] rgb2rgb(ColorSpaceType source, ColorSpaceType target) {
return rgb2rgb(source, target, ChromaticAdaptationAlgorithm.Bradford);
}
public static double[][] rgb2rgb(ColorSpaceType source, ColorSpaceType target,
ChromaticAdaptationAlgorithm algorithm) {
return rgb2rgb(primariesTristimulus(source), whitePointMatrix(source),
primariesTristimulus(target), whitePointMatrix(target),
algorithm, -1);
}
public static double[][] rgb2rgb(
double[][] sourcePrimaries, double[][] sourceWhitePoint,
double[][] targetPrimaries, double[][] targetWhitePoint,
ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm, int scale) {
return (double[][]) rgb2rgb(sourcePrimaries, sourceWhitePoint, targetPrimaries, targetWhitePoint,
algorithm, scale, false);
}
public static Object rgb2rgb(
double[][] sourcePrimaries, double[][] sourceWhitePoint,
double[][] targetPrimaries, double[][] targetWhitePoint,
ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
Map<String, Object> map;
Object rgb2xyzObject = RGB2XYZConversionMatrix.rgb2xyz(sourcePrimaries, sourceWhitePoint,
targetWhitePoint, algorithm, scale, isDemo);
double[][] rgb2xyzMatrix;
String rgb2xyzString = null;
if (isDemo) {
map = (Map<String, Object>) rgb2xyzObject;
rgb2xyzMatrix = (double[][]) map.get("conversionMatrix");
rgb2xyzString = (String) map.get("procedure");
} else {
rgb2xyzMatrix = (double[][]) rgb2xyzObject;
}
Object xyz2rgbObject = RGB2XYZConversionMatrix.xyz2rgb(targetPrimaries, targetWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
double[][] xyz2rgbMatrix;
String xyz2rgbString = null;
if (isDemo) {
map = (Map<String, Object>) xyz2rgbObject;
xyz2rgbMatrix = (double[][]) map.get("conversionMatrix");
xyz2rgbString = (String) map.get("procedure");
} else {
xyz2rgbMatrix = (double[][]) xyz2rgbObject;
}
double[][] conversionMatrix = DoubleMatrixTools.multiply(xyz2rgbMatrix, rgb2xyzMatrix);
Object ret;
if (isDemo) {
String s = "ccccccccccccc " + Languages.message("Step") + " - Source Linear RGB -> XYZ ccccccccccccc\n";
s += rgb2xyzString + "\n";
s += "\nccccccccccccc " + Languages.message("Step") + " - XYZ -> target Linear RGB ccccccccccccc\n";
s += xyz2rgbString + "\n";
s += "\nccccccccccccc " + Languages.message("Step") + " - Source Linear RGB -> target Linear RGB ccccccccccccc\n";
s += "\nRGB_to_RGB_Matrix = XYZ_to_RGB_Matrix * RGB_to_XYZ_Matrix =\n";
s += DoubleMatrixTools.print(conversionMatrix, 20, scale);
map = new HashMap<>();
map.put("procedure", s);
map.put("conversionMatrix", conversionMatrix);
ret = map;
} else {
ret = conversionMatrix;
}
return ret;
} catch (Exception e) {
return null;
}
}
/*
get/set
*/
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSourceWhite() {
return sourceWhite;
}
public void setSourceWhite(String sourceWhite) {
this.sourceWhite = sourceWhite;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getTargetWhite() {
return targetWhite;
}
public void setTargetWhite(String targetWhite) {
this.targetWhite = targetWhite;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getSource2target() {
return source2target;
}
public void setSource2target(String source2target) {
this.source2target = source2target;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/IccXML.java | alpha/MyBox/src/main/java/mara/mybox/color/IccXML.java | package mara.mybox.color;
import java.awt.color.ICC_Profile;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccHeader.renderingIntent;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-5-14 10:21:53
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccXML {
public static String iccXML(IccHeader header, IccTags tags) {
try {
StringBuilder s = new StringBuilder();
s.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
s.append("<IccProfile>\n");
String headerXml = iccHeaderXml(header.getFields());
if (headerXml == null) {
return null;
}
s.append(headerXml);
s.append("\n");
String tagesXml = iccTagsXml(tags.getTags());
if (tagesXml == null) {
return null;
}
s.append(tagesXml);
s.append("</IccProfile>\n");
return s.toString();
} catch (Exception e) {
return null;
}
}
public static String iccHeaderXml(ICC_Profile profile) {
if (profile == null) {
return null;
}
return iccHeaderXml(subBytes(profile.getData(), 0, 128));
}
public static String iccHeaderXml(byte[] header) {
return iccHeaderXml(IccHeader.iccHeaderFields(header));
}
public static String iccHeaderXml(LinkedHashMap<String, IccTag> fields) {
if (fields == null) {
return null;
}
try {
StringBuilder s = new StringBuilder();
s.append(AppValues.Indent).append("<Header>\n");
for (String key : fields.keySet()) {
IccTag field = fields.get(key);
switch (key) {
case "ProfileFlagIndependently":
case "ProfileFlagMCSSubset":
case "DeviceAttributeMatte":
case "DeviceAttributeNegative":
case "DeviceAttributeBlackOrWhite":
case "DeviceAttributePaperBased":
case "DeviceAttributeTextured":
case "DeviceAttributeIsotropic":
case "DeviceAttributeSelfLuminous":
case "PCCIlluminantY":
case "PCCIlluminantZ":
continue;
case "CMMType":
case "ProfileDeviceClass":
case "PrimaryPlatform":
case "DeviceManufacturer":
case "Creator":
String v = (String) field.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(v.substring(0, 4)).append("</").append(key).append(">\n");
break;
case "RenderingIntent":
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(renderingIntent(field.getBytes())).append("</").append(key).append(">\n");
break;
case "ProfileFlagEmbedded":
s.append(AppValues.Indent).append(AppValues.Indent).append("<ProfileFlags>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Embedded>")
.append(field.getValue()).append("</Embedded>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Independently>")
.append(fields.get("ProfileFlagIndependently").getValue()).append("</Independently>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<MCSSubset>")
.append(fields.get("ProfileFlagMCSSubset").getValue()).append("</MCSSubset>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</ProfileFlags>\n");
break;
case "DeviceAttributeTransparency":
s.append(AppValues.Indent).append(AppValues.Indent).append("<DeviceAttributes>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Transparency>")
.append(field.getValue()).append("</Transparency>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Matte>")
.append(fields.get("DeviceAttributeMatte").getValue()).append("</Matte>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Negative>")
.append(fields.get("DeviceAttributeNegative").getValue()).append("</Negative>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<BlackOrWhite>")
.append(fields.get("DeviceAttributeBlackOrWhite").getValue()).append("</BlackOrWhite>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<PaperBased>")
.append(fields.get("DeviceAttributePaperBased").getValue()).append("</PaperBased>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Textured>")
.append(fields.get("DeviceAttributeTextured").getValue()).append("</Textured>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Isotropic>")
.append(fields.get("DeviceAttributeIsotropic").getValue()).append("</Isotropic>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<SelfLuminous>")
.append(fields.get("DeviceAttributeSelfLuminous").getValue()).append("</SelfLuminous>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</DeviceAttributes>\n");
break;
case "PCCIlluminantX":
s.append(AppValues.Indent).append(AppValues.Indent).append("<ConnectionSpaceIlluminant>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<X>")
.append(field.getValue()).append("</X>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Y>")
.append(fields.get("PCCIlluminantY").getValue()).append("</Y>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Z>")
.append(fields.get("PCCIlluminantZ").getValue()).append("</Z>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</ConnectionSpaceIlluminant>\n");
break;
default:
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(field.getValue()).append("</").append(key).append(">\n");
break;
}
}
s.append(AppValues.Indent).append("</Header>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String iccTagsXml(List<IccTag> tags) {
if (tags == null || tags.isEmpty()) {
return null;
}
try {
StringBuilder s = new StringBuilder();
s.append(AppValues.Indent).append("<Tags>\n");
for (IccTag tag : tags) {
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(tag.getName())
.append(" tag=\"").append(tag.getTag()).append("\" offset=\"")
.append(tag.getOffset()).append("\" size=\"").append(tag.getBytes().length);
if (tag.getType() != null) {
s.append("\" type=\"").append(tag.getType()).append("\">\n");
if (tag.getValue() != null) {
switch (tag.getType()) {
case Text:
case Signature: {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<value>").append(tag.getValue()).append("</value>\n");
break;
}
case MultiLocalizedUnicode: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<ASCII length=\"").append(values.get("AsciiLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("Ascii")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</ASCII>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<Unicode code=\"").append(values.get("UnicodeCode")).
append("\" length=\"").append(values.get("UnicodeLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("Unicode")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</Unicode>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<ScriptCode code=\"").append(values.get("ScriptCodeCode")).
append("\" length=\"").append(values.get("ScriptCodeLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("ScriptCode")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</ScriptCode>\n");
break;
}
case XYZ: {
double[][] values = (double[][]) tag.getValue();
for (double[] xyz : values) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<XYZ x=\"").append(xyz[0]).append("\" y=\"").
append(xyz[1]).append("\" z=\"").append(xyz[2]).append("\"/>\n");
}
break;
}
case Curve: {
double[] values = (double[]) tag.getValue();
int count = 1;
for (double value : values) {
if (count % 6 == 1) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
}
s.append(value).append(" ");
if (count % 6 == 0 && count < values.length) {
s.append("\n");
}
count++;
}
s.append("\n");
break;
}
case Measurement: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<observer>").append(values.get("observer")).append("</observer>\n");
double[] tristimulus = (double[]) values.get("tristimulus");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<tristimulus x=\"").append(tristimulus[0]).append("\" y=\"").
append(tristimulus[1]).append("\" z=\"").append(tristimulus[2]).append("\"/>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<geometry>").append(values.get("geometry")).append("</geometry>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<flare>").append((double) values.get("flare")).append("</flare>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(values.get("illuminantType")).append("</type>\n");
break;
}
case ViewingConditions: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
double[] illuminant = (double[]) values.get("illuminant");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<illuminant x=\"").append(illuminant[0]).append("\" y=\"").
append(illuminant[1]).append("\" z=\"").append(illuminant[2]).append("\"/>\n");
double[] surround = (double[]) values.get("surround");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<surround x=\"").append(surround[0]).append("\" y=\"").
append(surround[1]).append("\" z=\"").append(surround[2]).append("\"/>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(values.get("illuminantType")).append("</type>\n");
break;
}
case S15Fixed16Array: {
double[] values = (double[]) tag.getValue();
for (int i = 0; i < values.length; ++i) {
if (i % 3 == 0) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
if (i > 0 && i < values.length - 1) {
s.append("\n");
}
}
s.append(values[i]).append(" ");
}
s.append("\n");
break;
}
case DateTime: {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(tag.getValue()).append("\n");
break;
}
case LUT: {
try {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<InputChannelsNumber>").append(values.get("InputChannelsNumber")).
append("</InputChannelsNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OutputChannelsNumber>").append(values.get("OutputChannelsNumber")).
append("</OutputChannelsNumber>\n");
if (values.get("type") != null) {
String type = (String) values.get("type");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(type).append("</type>\n");
if (type.equals("lut8") || type.equals("lut16")) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<GridPointsNumber>").append(values.get("GridPointsNumber")).
append("</GridPointsNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Matrix>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e1")).append(AppValues.Indent).
append(values.get("e2")).append(AppValues.Indent).
append(values.get("e3")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e4")).append(AppValues.Indent).
append(values.get("e5")).append(AppValues.Indent).
append(values.get("e6")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e7")).append(AppValues.Indent).
append(values.get("e8")).append(AppValues.Indent).
append(values.get("e9")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</Matrix>\n");
if (type.equals("lut16")) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<InputTablesNumber>").append(values.get("InputTablesNumber")).
append("</InputTablesNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OutputTablesNumber>").append(values.get("OutputTablesNumber")).
append("</OutputTablesNumber>\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<InputTables>\n");
List<List<Double>> InputTables = (List<List<Double>>) values.get("InputTables");
for (List<Double> input : InputTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double i : input) {
s.append(i).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("InputTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</InputTables>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<CLUTTables>\n");
List<List<Double>> CLUTTables = (List<List<Double>>) values.get("CLUTTables");
for (List<Double> GridPoint : CLUTTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double p : GridPoint) {
s.append(p).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("CLUTTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</CLUTTables>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<OutputTables>\n");
List<List<Double>> OutputTables = (List<List<Double>>) values.get("OutputTables");
for (List<Double> output : OutputTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double o : output) {
s.append(o).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("OutputTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</OutputTables>\n");
} else {
MyBoxLog.debug("OffsetBCurve:" + values.get("OffsetBCurve"));
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetBCurve>").append(values.get("OffsetBCurve")).append("</OffsetBCurve>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetMatrix>").append(values.get("OffsetMatrix")).append("</OffsetMatrix>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetMCurve>").append(values.get("OffsetMCurve")).append("</OffsetMCurve>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetCLUT>").append(values.get("OffsetCLUT")).append("</OffsetCLUT>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetACurve>").append(values.get("OffsetACurve")).append("</OffsetACurve>\n");
}
} else {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
} catch (Exception e) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
break;
}
}
} else {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
} else {
s.append("\" type=\"Not Decoded\">\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append("</").append(tag.getName()).append(">\n");
}
s.append(AppValues.Indent).append("</Tags>\n");
return s.toString();
} 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/alpha/MyBox/src/main/java/mara/mybox/color/IccProfile.java | alpha/MyBox/src/main/java/mara/mybox/color/IccProfile.java | package mara.mybox.color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.File;
import java.nio.charset.StandardCharsets;
import static mara.mybox.color.IccXML.iccXML;
import mara.mybox.tools.StringTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.ByteFileTools;
import mara.mybox.tools.MessageDigestTools;
/**
* @Author Mara
* @CreateDate 2019-5-6
* @Description
* @License Apache License Version 2.0
*/
public class IccProfile {
private ICC_Profile profile;
private File file;
private ColorSpace colorSpace;
private int predefinedColorSpaceType;
private byte[] data;
private IccHeader header;
private IccTags tags;
private boolean isValid, normalizeLut;
private String error;
public IccProfile(int colorSpaceType) {
try {
profile = ICC_Profile.getInstance(colorSpaceType);
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(String colorSpaceType) {
try {
predefinedColorSpaceType = ColorBase.colorSpaceType(colorSpaceType);
if (predefinedColorSpaceType < 0) {
return;
}
profile = ICC_Profile.getInstance(predefinedColorSpaceType);
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(File profileFile) {
try {
if (profileFile == null || !profileFile.exists()) {
return;
}
this.file = profileFile;
predefinedColorSpaceType = -1;
profile = ICC_Profile.getInstance(profileFile.getAbsolutePath());
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(byte[] data) {
try {
if (data == null) {
return;
}
this.data = data;
predefinedColorSpaceType = -1;
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
private void init() {
try {
if (profile == null) {
return;
}
if (predefinedColorSpaceType < 0) {
colorSpace = new ICC_ColorSpace(profile);
} else {
colorSpace = ColorSpace.getInstance(predefinedColorSpaceType);
}
isValid = colorSpace != null;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public byte[] readData() {
if (data == null) {
if (file != null) {
data = ByteFileTools.readBytes(file);
} else if (profile != null) {
data = profile.getData();
}
}
return data;
}
public String readXML() {
return iccXML(getHeader(), getTags());
}
public boolean update(byte[] newHeader) {
if (newHeader == null || newHeader.length != 128) {
return false;
}
header.update(newHeader);
data = tags.update();
System.arraycopy(newHeader, 4, data, 4, 124);
return setProfileID();
}
public boolean setProfileID() {
try {
byte[] bytes44 = new byte[4];
System.arraycopy(data, 44, bytes44, 0, 4);
byte[] bytes64 = new byte[4];
System.arraycopy(data, 64, bytes64, 0, 4);
byte[] bytes84 = new byte[16];
System.arraycopy(data, 84, bytes84, 0, 16);
byte[] blank = new byte[4];
System.arraycopy(blank, 0, data, 44, 4);
System.arraycopy(blank, 0, data, 64, 4);
blank = new byte[16];
System.arraycopy(blank, 0, data, 84, 16);
byte[] digest = MessageDigestTools.MD5(data);
System.arraycopy(bytes44, 0, data, 44, 4);
System.arraycopy(bytes64, 0, data, 64, 4);
System.arraycopy(digest, 0, data, 84, 16);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
// public boolean write(File file) {
// return FileTools.writeFile(file, data);
// }
public boolean write(File file, byte[] newHeader) {
if (!update(newHeader)) {
return false;
}
return ByteFileTools.writeFile(file, data) != null;
}
public float[] calculateXYZ(float[] color) {
if (profile == null) {
return null;
}
if (colorSpace == null) {
colorSpace = new ICC_ColorSpace(profile);
}
if (colorSpace == null) {
return null;
}
return colorSpace.toCIEXYZ(color);
}
public float[] calculateCoordinate(float[] xyz) {
if (xyz == null) {
return null;
}
float x = xyz[0];
float y = xyz[1];
float z = xyz[2];
float sum = x + y + z;
float[] xy = new float[2];
xy[0] = x / sum;
xy[1] = y / sum;
return xy;
}
/*
Encode
*/
public static byte[] toBytes(String value) {
try {
return value.getBytes(StandardCharsets.US_ASCII);
} catch (Exception e) {
return null;
}
}
public static byte[] first4ASCII(String value) {
byte[] bytes = new byte[4];
try {
String vString = value;
if (value.length() > 4) {
vString = value.substring(0, 4);
} else if (value.length() < 4) {
vString = StringTools.fillRightBlank(value, 4);
}
byte[] vBytes = toBytes(vString);
System.arraycopy(vBytes, 0, bytes, 0, 4);
} catch (Exception e) {
}
return bytes;
}
/*
Get/Set
*/
public ICC_Profile getProfile() {
return profile;
}
public void setProfile(ICC_Profile profile) {
this.profile = profile;
}
public byte[] getData() {
if (data == null) {
readData();
}
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public ColorSpace getColorSpace() {
if (profile == null) {
return null;
}
if (colorSpace == null) {
if (predefinedColorSpaceType < 0) {
colorSpace = new ICC_ColorSpace(profile);
} else {
colorSpace = ColorSpace.getInstance(predefinedColorSpaceType);
}
}
return colorSpace;
}
public void setColorSpace(ColorSpace iccColorSpace) {
this.colorSpace = iccColorSpace;
}
public IccHeader getHeader() {
if (header == null) {
header = new IccHeader(getData());
}
return header;
}
public void setHeader(IccHeader header) {
this.header = header;
}
public IccTags getTags() {
if (tags == null) {
tags = new IccTags(getData(), normalizeLut);
}
return tags;
}
public void setTags(IccTags tags) {
this.tags = tags;
}
public boolean isNormalizeLut() {
return normalizeLut;
}
public void setNormalizeLut(boolean normalizeLut) {
this.normalizeLut = normalizeLut;
}
public int getPredefinedColorSpaceType() {
return predefinedColorSpaceType;
}
public void setPredefinedColorSpaceType(int predefinedColorSpaceType) {
this.predefinedColorSpaceType = predefinedColorSpaceType;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/RGB2XYZConversionMatrix.java | alpha/MyBox/src/main/java/mara/mybox/color/RGB2XYZConversionMatrix.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import static mara.mybox.color.ChromaticAdaptation.matrix;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.color.RGBColorSpace.ColorSpaceType;
import static mara.mybox.color.RGBColorSpace.primariesTristimulus;
import static mara.mybox.color.RGBColorSpace.whitePointMatrix;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
// http://brucelindbloom.com/index.html?WorkingSpaceInfo.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
public class RGB2XYZConversionMatrix {
public String rgb, rgbWhite, xyzWhite, algorithm;
public String rgb2xyz, xyz2rgb;
public RGB2XYZConversionMatrix() {
}
/*
Generation of Conversion matrices
*/
public static List<RGB2XYZConversionMatrix> all(int scale) {
List<RGB2XYZConversionMatrix> data = new ArrayList<>();
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
RGB2XYZConversionMatrix c = new RGB2XYZConversionMatrix();
c.setRgb(RGBColorSpace.name(colorSpace));
c.setRgbWhite(csWhite + " - " + Observer.CIE1931);
c.setXyzWhite(targetIlluminant + " - " + targetObserver);
c.setAlgorithm(algorithm + "");
c.setRgb2xyz(DoubleMatrixTools.print(adpatedC, 0, scale));
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
c.setXyz2rgb(DoubleMatrixTools.print(xyz2rgb, 0, scale));
data.add(c);
}
} else {
RGB2XYZConversionMatrix c = new RGB2XYZConversionMatrix();
c.setRgb(RGBColorSpace.name(colorSpace));
c.setRgbWhite(csWhite + " - " + Observer.CIE1931);
c.setXyzWhite(targetIlluminant + " - " + targetObserver);
c.setAlgorithm("");
c.setRgb2xyz(DoubleMatrixTools.print(rgb2xyz, 0, scale));
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
c.setXyz2rgb(DoubleMatrixTools.print(xyz2rgb, 0, scale));
data.add(c);
}
}
}
}
}
return data;
}
public static StringTable allTable(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("RGBColorSpace"),
Languages.message("RGBReferenceWhite"), Languages.message("XYZReferenceWhite"), Languages.message("Algorithm"),
"Linear RGB -> XYZ", "XYZ -> Linear RGB"
));
StringTable table = new StringTable(names, Languages.message("LinearRGB2XYZMatrix"));
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(colorSpace),
csWhite + " - " + Observer.CIE1931,
targetIlluminant + " - " + targetObserver,
algorithm.name(),
DoubleMatrixTools.html(adpatedC, scale),
DoubleMatrixTools.html(xyz2rgb, scale)
));
table.add(row);
}
} else {
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(colorSpace),
csWhite + " - " + Observer.CIE1931,
targetIlluminant + " - " + targetObserver,
"",
DoubleMatrixTools.html(rgb2xyz, scale),
DoubleMatrixTools.html(xyz2rgb, scale)
));
table.add(row);
}
}
}
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
s.append(Languages.message("RGBColorSpace")).append(": ").
append(RGBColorSpace.name(colorSpace)).append("\n");
s.append(Languages.message("RGBReferenceWhite")).append(": ").
append(csWhite).append(" - ").append(Observer.CIE1931).append("\n");
s.append(Languages.message("XYZReferenceWhite")).append(": ").
append(targetIlluminant).append(" - ").append(targetObserver).append("\n");
s.append(Languages.message("AdaptationAlgorithm")).append(": ").
append(algorithm).append("\n");
s.append("Linear RGB -> XYZ: ").append("\n");
s.append(DoubleMatrixTools.print(adpatedC, 20, scale));
s.append("XYZ -> Linear RGB: ").append("\n");
s.append(DoubleMatrixTools.print(xyz2rgb, 20, scale)).append("\n");
}
} else {
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
s.append(Languages.message("RGBColorSpace")).append(": ").
append(RGBColorSpace.name(colorSpace)).append("\n");
s.append(Languages.message("RGBReferenceWhite")).append(": ").
append(csWhite).append(" - ").append(Observer.CIE1931).append("\n");
s.append(Languages.message("XYZReferenceWhite")).append(": ").
append(targetIlluminant).append(" - ").append(targetObserver).append("\n");
s.append("Linear RGB -> XYZ: ").append("\n");
s.append(DoubleMatrixTools.print(rgb2xyz, 20, scale));
s.append("XYZ -> Linear RGB: ").append("\n");
s.append(DoubleMatrixTools.print(xyz2rgb, 20, scale)).append("\n");
}
}
}
}
}
return s.toString();
}
public static double[][] rgb2xyz(ColorSpaceType colorSpace) {
return rgb2xyz(primariesTristimulus(colorSpace), whitePointMatrix(colorSpace));
}
public static double[][] rgb2xyz(double[][] primaries, double[][] sourceWhitePoint) {
return (double[][]) rgb2xyz(primaries, sourceWhitePoint, null, null, -1, false);
}
public static double[][] xyz2rgb(ColorSpaceType colorSpace) {
return DoubleMatrixTools.inverse(rgb2xyz(colorSpace));
}
public static double[][] xyz2rgb(double[][] primaries, double[][] sourceWhitePoint) {
return DoubleMatrixTools.inverse(rgb2xyz(primaries, sourceWhitePoint));
}
public static Object rgb2xyz(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
double[][] t = DoubleMatrixTools.transpose(primaries);
double[][] i = DoubleMatrixTools.inverse(t);
double[][] s = DoubleMatrixTools.multiply(i, sourceWhitePoint);
double[][] conversionMatrix = new double[3][3];
conversionMatrix[0][0] = s[0][0] * t[0][0];
conversionMatrix[1][0] = s[0][0] * t[1][0];
conversionMatrix[2][0] = s[0][0] * t[2][0];
conversionMatrix[0][1] = s[1][0] * t[0][1];
conversionMatrix[1][1] = s[1][0] * t[1][1];
conversionMatrix[2][1] = s[1][0] * t[2][1];
conversionMatrix[0][2] = s[2][0] * t[0][2];
conversionMatrix[1][2] = s[2][0] * t[1][2];
conversionMatrix[2][2] = s[2][0] * t[2][2];
Object ret;
String d = "";
Map<String, Object> map;
if (isDemo) {
d += "WhitePoint =\n";
d += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
d += "\nRGB Primaires = (Each primary color is one row)\n";
d += DoubleMatrixTools.print(primaries, 20, scale);
d += "\nRGB_Transposed_Primaires = (Each primary color is one column)\n";
d += DoubleMatrixTools.print(t, 20, scale);
d += "\nInversed = inverse(RGB_Transposed_Primaires) = \n";
d += DoubleMatrixTools.print(i, 20, scale);
d += "\nSrgb = Inversed * RGB_WhitePoint = \n";
d += DoubleMatrixTools.print(s, 20, scale);
d += "\nRGB_to_XYZ_Matrix = (Column in Srgb) * (columns in RGB_Transposed_Primaires) =\n";
d += DoubleMatrixTools.print(conversionMatrix, 20, scale);
d += Languages.message("XYZSameWhiteRGB") + "\n";
}
if (targetWhitePoint == null || DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
d = "ccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ ccccccccccccc\n\n" + d;
map = new HashMap<>();
map.put("procedure", d);
map.put("conversionMatrix", conversionMatrix);
ret = map;
} else {
ret = conversionMatrix;
}
return ret;
}
double[][] adaptMatrix;
String adaptString = null;
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
map = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) map.get("adpatMatrix");
adaptString = (String) map.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] adaptedConversionMatrix = DoubleMatrixTools.multiply(adaptMatrix, conversionMatrix);
if (scale >= 0) {
adaptedConversionMatrix = DoubleMatrixTools.scale(adaptedConversionMatrix, scale);
} else {
scale = 8;
}
if (isDemo) {
d = "ccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ , "
+ Languages.message("RGBXYZsameWhite") + " ccccccccccccc\n\n" + d;
d += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n\n";
d += adaptString + "\n";
d += "\nccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ , "
+ Languages.message("RGBXYZdifferentWhite") + " ccccccccccccc\n";
d += "\nRGB Primaires = (Each primary color is one row)\n";
d += DoubleMatrixTools.print(primaries, 20, scale);
d += "\nRGB_WhitePoint =\n";
d += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
d += "\nXYZ_WhitePoint =\n";
d += DoubleMatrixTools.print(targetWhitePoint, 20, scale);
d += "\nRGB_to_XYZ_Matrix_different_WhitePoint = Adaptation_Matrix * RGB_to_XYZ_Matrix_same_WhitePoint\n";
d += DoubleMatrixTools.print(adaptedConversionMatrix, 20, scale);
map = new HashMap<>();
map.put("procedure", d);
map.put("conversionMatrix", adaptedConversionMatrix);
ret = map;
} else {
ret = adaptedConversionMatrix;
}
return ret;
} catch (Exception e) {
return null;
}
}
public static Object xyz2rgb(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
Object rgb2xyz = rgb2xyz(primaries, sourceWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
double[][] conversionMatrix;
Object rgb2xyzObject = rgb2xyz(primaries, sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
Map<String, Object> map = (Map<String, Object>) rgb2xyzObject;
conversionMatrix = (double[][]) map.get("conversionMatrix");
conversionMatrix = DoubleMatrixTools.inverse(conversionMatrix);
map.put("conversionMatrix", conversionMatrix);
String s = (String) map.get("procedure");
s += "\nccccccccccccc " + Languages.message("Step") + " - XYZ -> Linear RGB ccccccccccccc\n\n";
s += "\nXYZ_to_RGB_Matrix = inverse( RGB_to_XYZ_Matrix ) = \n";
s += DoubleMatrixTools.print(conversionMatrix, 20, scale);
map.put("procedure", s);
return map;
} else {
conversionMatrix = (double[][]) rgb2xyzObject;
conversionMatrix = DoubleMatrixTools.inverse(conversionMatrix);
return conversionMatrix;
}
}
/*
get/set
*/
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getXyzWhite() {
return xyzWhite;
}
public void setXyzWhite(String xyzWhite) {
this.xyzWhite = xyzWhite;
}
public String getRgb() {
return rgb;
}
public void setRgb(String rgb) {
this.rgb = rgb;
}
public String getRgbWhite() {
return rgbWhite;
}
public void setRgbWhite(String rgbWhite) {
this.rgbWhite = rgbWhite;
}
public String getRgb2xyz() {
return rgb2xyz;
}
public void setRgb2xyz(String rgb2xyz) {
this.rgb2xyz = rgb2xyz;
}
public String getXyz2rgb() {
return xyz2rgb;
}
public void setXyz2rgb(String xyz2rgb) {
this.xyz2rgb = xyz2rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/CIEColorSpace.java | alpha/MyBox/src/main/java/mara/mybox/color/CIEColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.color.AdobeRGB.gammaAdobeRGB;
import static mara.mybox.color.AppleRGB.gammaAppleRGB;
import static mara.mybox.color.ColorBase.clipRGB;
import static mara.mybox.color.SRGB.gammaSRGB;
import mara.mybox.tools.DoubleMatrixTools;
/**
* @Author Mara
* @CreateDate 2019-5-24 8:44:35
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class CIEColorSpace {
public static enum ColorSpaceType {
CIEXYZ, CIExyY, CIELuv, CIELab, LCHab, LCHuv
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(cs + "");
}
return names;
}
public static double[] XYZd50toCIERGB(double[] xyz) {
double[][] matrix = {
{2.3706743, -0.9000405, -0.4706338},
{-0.5138850, 1.4253036, 0.0885814},
{0.0052982, -0.0146949, 1.0093968}
};
double[] cieRGB = DoubleMatrixTools.multiply(matrix, xyz);
return cieRGB;
}
public static double[] XYZd50toCIELab(double X, double Y, double Z) {
return XYZtoCIELab(0.96422, 1, 0.82521, X, Y, Z);
}
// http://brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html
public static double[] XYZtoCIELab(
double rX, double rY, double rZ,
double X, double Y, double Z) {
double xr = X / rX;
double yr = Y / rY;
double zr = Z / rZ;
double threshold = 0.008856;
double d3 = 0.333333;
double p1 = 7.787069;
double p2 = 0.137931;
if (xr > threshold) {
xr = Math.pow(xr, d3);
} else {
xr = p1 * xr + p2;
}
if (yr > threshold) {
yr = Math.pow(yr, d3);
} else {
yr = p1 * yr + p2;
}
if (zr > threshold) {
zr = Math.pow(zr, d3);
} else {
zr = p1 * zr + p2;
}
double[] CIELab = new double[3];
CIELab[0] = 116 * yr - 16;
CIELab[1] = 500 * (xr - yr);
CIELab[2] = 200 * (yr - zr);
return CIELab;
}
public static double[] XYZd50toCIELuv(double X, double Y, double Z) {
return XYZtoCIELuv(0.96422, 1, 0.82521, X, Y, Z);
}
// http://brucelindbloom.com/index.html?Eqn_XYZ_to_Luv.html
public static double[] XYZtoCIELuv(
double rX, double rY, double rZ,
double X, double Y, double Z) {
if (X == 0 && Y == 0 && Z == 0) {
return new double[3];
}
double yr = Y / rY;
double u = (4 * X) / (X + 15 * Y + 3 * Z);
double v = (9 * Y) / (X + 15 * Y + 3 * Z);
double ru = (4 * rX) / (rX + 15 * rY + 3 * rZ);
double rv = (9 * rY) / (rX + 15 * rY + 3 * rZ);
double[] CIELuv = new double[3];
if (yr > 0.008856) {
CIELuv[0] = 116 * Math.pow(yr, 1d / 3) - 16;
} else {
CIELuv[0] = 903.3 * yr;
}
CIELuv[1] = 13 * CIELuv[0] * (u - ru);
CIELuv[2] = 13 * CIELuv[0] * (v - rv);
return CIELuv;
}
public static double[] LabtoLCHab(double[] Lab) {
return LabtoLCHab(Lab[0], Lab[1], Lab[2]);
}
public static double[] LabtoLCHab(double L, double a, double b) {
double[] LCH = new double[3];
LCH[0] = L;
LCH[1] = Math.sqrt(a * a + b * b);
double d = Math.atan2(b, a) * 180 / Math.PI;
if (d >= 0) {
LCH[2] = d;
} else {
LCH[2] = d + 360;
}
return LCH;
}
public static double[] LuvtoLCHuv(double[] Luv) {
return LuvtoLCHuv(Luv[0], Luv[1], Luv[2]);
}
public static double[] LuvtoLCHuv(double L, double u, double v) {
double[] LCH = new double[3];
LCH[0] = L;
LCH[1] = Math.sqrt(u * u + v * v);
double d = Math.atan2(v, u) * 180 / Math.PI;
if (d >= 0) {
LCH[2] = d;
} else {
LCH[2] = d + 360;
}
return LCH;
}
/*
sRGB
*/
public static double[] XYZd50toSRGBd65(double X, double Y, double Z) {
return XYZd50toSRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toSRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toSRGBd65(xyzD65);
}
public static double[] XYZd50toSRGBd65Linear(double X, double Y, double Z) {
return XYZd50toSRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toSRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toSRGBd65Linear(xyzD65);
}
public static double[] XYZd50toSRGBd50(double[] xyz) {
double[][] matrix = {
{3.1338561, -1.6168667, -0.4906146},
{-0.9787684, 1.9161415, 0.0334540},
{0.0719453, -0.2289914, 1.4052427}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyz);
linearRGB = clipRGB(linearRGB);
double[] srgb = gammaSRGB(linearRGB);
return srgb;
}
public static double[] XYZd65toSRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toSRGBd65Linear(xyzd65);
double[] srgb = gammaSRGB(linearRGB);
return srgb;
}
public static double[] XYZd65toSRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{3.2409699419045235, -1.5373831775700944, -0.49861076029300355},
{-0.9692436362808797, 1.8759675015077204, 0.0415550574071756},
{0.05563007969699365, -0.20397695888897652, 1.0569715142428786}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
/*
Adobe RGB
*/
public static double[] XYZd50toAdobeRGBd65(double X, double Y, double Z) {
return XYZd50toAdobeRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAdobeRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAdobeRGBd65(xyzD65);
}
public static double[] XYZd50toAdobeRGBd65Linear(double X, double Y, double Z) {
return XYZd50toAdobeRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAdobeRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAdobeRGBd65Linear(xyzD65);
}
public static double[] XYZd65toAdobeRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toAdobeRGBd65Linear(xyzd65);
double[] rgb = gammaAdobeRGB(linearRGB);
return rgb;
}
public static double[] XYZd65toAdobeRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{2.0413690, -0.5649464, -0.3446944},
{-0.9692660, 1.8760108, 0.0415560},
{0.0134474, -0.1183897, 1.0154096}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
public static double[] XYZd50toAdobeRGBd50(double[] xyzD50) {
double[][] matrix = {
{1.9624274, -0.6105343, -0.3413404},
{-0.9787684, 1.9161415, 0.0334540},
{0.0286869, -0.1406752, 1.3487655}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzD50);
linearRGB = clipRGB(linearRGB);
double[] rgb = gammaAdobeRGB(linearRGB);
return rgb;
}
/*
Apple RGB
*/
public static double[] XYZd50toAppleRGBd65(double X, double Y, double Z) {
return XYZd50toAppleRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAppleRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAppleRGBd65(xyzD65);
}
public static double[] XYZd50toAppleRGBd65Linear(double X, double Y, double Z) {
return XYZd50toAppleRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAppleRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAppleRGBd65Linear(xyzD65);
}
public static double[] XYZd65toAppleRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toAppleRGBd65Linear(xyzd65);
double[] rgb = gammaAppleRGB(linearRGB);
return rgb;
}
public static double[] XYZd65toAppleRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{2.9515373, -1.2894116, -0.4738445},
{-1.0851093, 1.9908566, 0.0372026},
{0.0854934, -0.2694964, 1.09129756}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
public static double[] XYZd50toAppleRGBd50(double[] xyzD50) {
double[][] matrix = {
{2.8510695, -1.3605261, -0.4708281},
{-1.0927680, 2.0348871, 0.0227598},
{0.1027403, -0.2964984, 1.4510659}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzD50);
linearRGB = clipRGB(linearRGB);
double[] rgb = gammaAppleRGB(linearRGB);
return rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/color/ColorStatistic.java | alpha/MyBox/src/main/java/mara/mybox/color/ColorStatistic.java | package mara.mybox.color;
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.scene.paint.Color;
import mara.mybox.tools.FloatTools;
/**
* @Author Mara
* @CreateDate 2019-2-11 12:53:19
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorStatistic {
private String type;
private Color color;
private int number;
private float percentage;
public ColorStatistic() {
}
public ColorStatistic(String type, Color color, int number, float percentage) {
this.type = type;
this.color = color;
this.number = number;
this.percentage = percentage;
}
public static List<ColorStatistic> newSort(List<ColorStatistic> values) {
if (values == null) {
return null;
}
List<ColorStatistic> sorted = new ArrayList<>();
sorted.addAll(values);
Collections.sort(sorted, new Comparator<ColorStatistic>() {
@Override
public int compare(ColorStatistic p1, ColorStatistic p2) {
return p1.getNumber() - p2.getNumber();
}
});
return sorted;
}
public static void sort(List<ColorStatistic> values) {
if (values == null) {
return;
}
Collections.sort(values, new Comparator<ColorStatistic>() {
@Override
public int compare(ColorStatistic p1, ColorStatistic p2) {
return p1.getNumber() - p2.getNumber();
}
});
}
public static Map<String, Object> statistic(List<ColorStatistic> values) {
Map<String, Object> statistic = new HashMap<>();
if (values == null) {
return statistic;
}
statistic.put("data", values);
int sum = 0;
for (ColorStatistic s : values) {
sum += s.getNumber();
}
statistic.put("sum", new ColorStatistic("Sum", null, sum, 100.0f));
statistic.put("average", new ColorStatistic("Average", null, sum / values.size(),
FloatTools.roundFloat5(100.0f / values.size())));
List<ColorStatistic> newList = ColorStatistic.newSort(values);
ColorStatistic s = newList.get(0);
statistic.put("minimum", new ColorStatistic("Minimum", s.getColor(), s.getNumber(), s.getPercentage()));
s = newList.get(newList.size() - 1);
statistic.put("maximum", new ColorStatistic("Maximum", s.getColor(), s.getNumber(), s.getPercentage()));
ColorStatistic median = new ColorStatistic();
median.setType("Median");
if (newList.size() % 2 == 0) {
ColorStatistic m1 = newList.get(newList.size() / 2);
ColorStatistic m2 = newList.get(newList.size() / 2 + 1);
median.setColor(m1.getColor());
median.setNumber((m1.getNumber() + m2.getNumber()) / 2);
} else {
ColorStatistic m = newList.get(newList.size() / 2);
median.setColor(m.getColor());
median.setNumber(m.getNumber());
}
median.setPercentage(FloatTools.roundFloat5(median.getNumber() * 100.0f / sum));
statistic.put("median", median);
return statistic;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public float getPercentage() {
return percentage;
}
public void setPercentage(float percentage) {
this.percentage = percentage;
}
}
| 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/thridparty/CoordinateConverter.java | released/MyBox/src/main/java/thridparty/CoordinateConverter.java | package thridparty;
import mara.mybox.tools.DoubleTools;
/**
* @Author https://www.jianshu.com/p/c39a2c72dc65?from=singlemessage
*
* Changed by Mara
*/
public class CoordinateConverter {
public static boolean outOfChina(double lon, double lat) {
return lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271;
}
public static double[] offsets(double lon, double lat) {
double a = 6378245.0;
double ee = 0.00669342162296594323;
double x = lon - 105.0, y = lat - 35.0;
double dLon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1
* Math.sqrt(Math.abs(x));
dLon += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
dLon += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
dLon += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0
* Math.PI)) * 2.0 / 3.0;
double dLat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y
+ 0.2 * Math.sqrt(Math.abs(x));
dLat += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
dLat += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
dLat += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
double radLat = lat / 180.0 * Math.PI;
double magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
double[] offsets = {dLon, dLat};
return offsets;
}
public static double[] GCJ02ToWGS84(double lon, double lat) {
double longitude, latitude;
if (outOfChina(lon, lat)) {
longitude = lon;
latitude = lat;
} else {
double[] offsets = offsets(lon, lat);
longitude = lon - offsets[0];
latitude = lat - offsets[1];
}
double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)};
return coordinate;
}
public static double[] WGS84ToGCJ02(double lon, double lat) {
double longitude, latitude;
if (outOfChina(lon, lat)) {
longitude = lon;
latitude = lat;
} else {
double[] offsets = offsets(lon, lat);
longitude = lon + offsets[0];
latitude = lat + offsets[1];
}
double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)};
return coordinate;
}
public static double[] BD09ToGCJ02(double bd_lon, double bd_lat) {
double x = bd_lon - 0.0065, y = bd_lat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta);
double latitude = z * Math.sin(theta);
double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)};
return coordinate;
}
public static double[] GCJ02ToBD09(double gg_lon, double gg_lat) {
double x = gg_lon, y = gg_lat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta) + 0.0065;
double latitude = z * Math.sin(theta) + 0.006;
double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)};
return coordinate;
}
}
| 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/thridparty/QRCodeWriter.java | released/MyBox/src/main/java/thridparty/QRCodeWriter.java | package thridparty;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;
import java.util.Map;
/**
* Original class: com.google.zxing.qrcode.QRCodeWriter
*
* @Author dswitkin@google.com (Daniel Switkin)
* @License Apache License Version 2.0
*
* Updated by Mara
* Update Date 2019-9-26
* ===> Original class is final so I have to modify it by copying all codes here
*/
public class QRCodeWriter implements Writer {
protected static final int QUIET_ZONE_SIZE = 4;
protected QRCode code;
protected int leftPadding, topPadding;
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
throws WriterException {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType, ?> hints) throws WriterException {
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if (format != BarcodeFormat.QR_CODE) {
throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x'
+ height);
}
ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
int quietZone = QUIET_ZONE_SIZE;
if (hints != null) {
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.MARGIN)) {
quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
}
code = Encoder.encode(contents, errorCorrectionLevel, hints);
return renderResult(width, height, quietZone);
}
// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
// 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
public BitMatrix renderResult(int width, int height, int quietZone) {
ByteMatrix input = code.getMatrix();
if (input == null) {
throw new IllegalStateException();
}
int inputWidth = input.getWidth();
int inputHeight = input.getHeight();
int qrWidth = inputWidth + (quietZone * 2);
int qrHeight = inputHeight + (quietZone * 2);
int outputWidth = Math.max(width, qrWidth);
int outputHeight = Math.max(height, qrHeight);
int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
topPadding = (outputHeight - (inputHeight * multiple)) / 2;
BitMatrix output = new BitMatrix(outputWidth, outputHeight);
for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) == 1) {
output.setRegion(outputX, outputY, multiple, multiple);
}
}
}
return output;
}
/**
* get/set -- to help to expose the values
*/
public QRCode getCode() {
return code;
}
public void setCode(QRCode code) {
this.code = code;
}
public int getLeftPadding() {
return leftPadding;
}
public void setLeftPadding(int leftPadding) {
this.leftPadding = leftPadding;
}
public int getTopPadding() {
return topPadding;
}
public void setTopPadding(int topPadding) {
this.topPadding = topPadding;
}
}
| 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/thridparty/EncodingDetect.java | released/MyBox/src/main/java/thridparty/EncodingDetect.java | package thridparty;
/**
* @Author https://www.cnblogs.com/ChurchYim/p/8427373.html
*
* Changed by Mara
* My updates are marked with #####.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
public class EncodingDetect {
public static int MAX_CHECK_BYTES = 20000000; // ##### Added by Mara
public static String detect(String path) {
BytesEncodingDetect s = new BytesEncodingDetect();
String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(new File(path))];
return fileCode;
}
public static String detect(File file) {
BytesEncodingDetect s = new BytesEncodingDetect();
String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(file)];
return fileCode;
}
public static String detect(byte[] contents) {
BytesEncodingDetect s = new BytesEncodingDetect();
String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(contents)];
return fileCode;
}
public static String detect(URL url) {
BytesEncodingDetect s = new BytesEncodingDetect();
String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(url)];
return fileCode;
}
static class BytesEncodingDetect extends Encoding {
int GBFreq[][];
int GBKFreq[][];
int Big5Freq[][];
int Big5PFreq[][];
int EUC_TWFreq[][];
int KRFreq[][];
int JPFreq[][];
public boolean debug;
public BytesEncodingDetect() {
super();
debug = false;
GBFreq = new int[94][94];
GBKFreq = new int[126][191];
Big5Freq = new int[94][158];
Big5PFreq = new int[126][191];
EUC_TWFreq = new int[94][94];
KRFreq = new int[94][94];
JPFreq = new int[94][94];
initialize_frequencies();
}
public int detectEncoding(URL testurl) {
byte[] rawtext = new byte[10000];
int bytesread = 0, byteoffset = 0;
int guess = OTHER;
InputStream is;
try {
is = testurl.openStream();
while ((bytesread = is.read(rawtext, byteoffset, rawtext.length - byteoffset)) > 0) {
byteoffset += bytesread;
}
is.close();
guess = detectEncoding(rawtext);
} catch (Exception e) {
System.err.println("Error loading or using URL " + e.toString());
guess = -1;
}
return guess;
}
public int detectEncoding(File testfile) {
byte[] rawtext = new byte[MAX_CHECK_BYTES]; // ##### Updated by Mara
try ( FileInputStream fileis = new FileInputStream(testfile)) {
fileis.read(rawtext);
} catch (Exception e) {
return OTHER;
}
return detectEncoding(rawtext);
}
public int detectEncoding(byte[] rawtext) {
int[] scores;
int index, maxscore = 0;
int encoding_guess = OTHER;
scores = new int[TOTALTYPES];
// Assign Scores
scores[GB2312] = gb2312_probability(rawtext);
scores[GBK] = gbk_probability(rawtext);
scores[GB18030] = gb18030_probability(rawtext);
scores[HZ] = hz_probability(rawtext);
scores[BIG5] = big5_probability(rawtext);
scores[CNS11643] = euc_tw_probability(rawtext);
scores[ISO2022CN] = iso_2022_cn_probability(rawtext);
scores[UTF8] = utf8_probability(rawtext);
scores[UNICODE] = utf16_probability(rawtext);
scores[EUC_KR] = euc_kr_probability(rawtext);
scores[CP949] = cp949_probability(rawtext);
scores[JOHAB] = 0;
scores[ISO2022KR] = iso_2022_kr_probability(rawtext);
scores[ASCII] = ascii_probability(rawtext);
scores[SJIS] = sjis_probability(rawtext);
scores[EUC_JP] = euc_jp_probability(rawtext);
scores[ISO2022JP] = iso_2022_jp_probability(rawtext);
scores[UNICODET] = 0;
scores[UNICODES] = 0;
scores[ISO2022CN_GB] = 0;
scores[ISO2022CN_CNS] = 0;
scores[OTHER] = 0;
// Tabulate Scores
for (index = 0; index < TOTALTYPES; index++) {
if (debug) {
System.err.println("Encoding " + nicename[index] + " score " + scores[index]);
}
if (scores[index] > maxscore) {
encoding_guess = index;
maxscore = scores[index];
}
}
// Return OTHER if nothing scored above 50
if (maxscore <= 50) {
encoding_guess = OTHER;
}
return encoding_guess;
}
/*
* Function: gb2312_probability Argument: pointer to byte array Returns : number from 0 to 100 representing
* probability text in array uses GB-2312 encoding
*/
int gb2312_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, gbchars = 1;
long gbfreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Stage 1: Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
// System.err.println(rawtext[i]);
if (rawtext[i] >= 0) {
// asciichars++;
} else {
dbchars++;
if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7 && (byte) 0xA1 <= rawtext[i + 1]
&& rawtext[i + 1] <= (byte) 0xFE) {
gbchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0xA1;
column = rawtext[i + 1] + 256 - 0xA1;
if (GBFreq[row][column] != 0) {
gbfreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
// In GB high-freq character range
gbfreq += 200;
}
}
i++;
}
}
rangeval = 50 * ((float) gbchars / (float) dbchars);
freqval = 50 * ((float) gbfreq / (float) totalfreq);
return (int) (rangeval + freqval);
}
/*
* Function: gbk_probability Argument: pointer to byte array Returns : number from 0 to 100 representing
* probability text in array uses GBK encoding
*/
int gbk_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, gbchars = 1;
long gbfreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Stage 1: Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
// System.err.println(rawtext[i]);
if (rawtext[i] >= 0) {
// asciichars++;
} else {
dbchars++;
if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7
&& // Original GB range
(byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) {
gbchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0xA1;
column = rawtext[i + 1] + 256 - 0xA1;
// System.out.println("original row " + row + " column " +
// column);
if (GBFreq[row][column] != 0) {
gbfreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
gbfreq += 200;
}
} else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE
&& // Extended GB range
(((byte) 0x80 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE)
|| ((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E))) {
gbchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0x81;
if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) {
column = rawtext[i + 1] - 0x40;
} else {
column = rawtext[i + 1] + 256 - 0x40;
}
// System.out.println("extended row " + row + " column " +
// column + " rawtext[i] " + rawtext[i]);
if (GBKFreq[row][column] != 0) {
gbfreq += GBKFreq[row][column];
}
}
i++;
}
}
rangeval = 50 * ((float) gbchars / (float) dbchars);
freqval = 50 * ((float) gbfreq / (float) totalfreq);
// For regular GB files, this would give the same score, so I handicap
// it slightly
return (int) (rangeval + freqval) - 1;
}
/*
* Function: gb18030_probability Argument: pointer to byte array Returns : number from 0 to 100 representing
* probability text in array uses GBK encoding
*/
int gb18030_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, gbchars = 1;
long gbfreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Stage 1: Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
// System.err.println(rawtext[i]);
if (rawtext[i] >= 0) {
// asciichars++;
} else {
dbchars++;
if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7
&& // Original GB range
i + 1 < rawtextlen && (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) {
gbchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0xA1;
column = rawtext[i + 1] + 256 - 0xA1;
// System.out.println("original row " + row + " column " +
// column);
if (GBFreq[row][column] != 0) {
gbfreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
gbfreq += 200;
}
} else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE
&& // Extended GB range
i + 1 < rawtextlen && (((byte) 0x80 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE)
|| ((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E))) {
gbchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0x81;
if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) {
column = rawtext[i + 1] - 0x40;
} else {
column = rawtext[i + 1] + 256 - 0x40;
}
// System.out.println("extended row " + row + " column " +
// column + " rawtext[i] " + rawtext[i]);
if (GBKFreq[row][column] != 0) {
gbfreq += GBKFreq[row][column];
}
} else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE
&& // Extended GB range
i + 3 < rawtextlen && (byte) 0x30 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x39
&& (byte) 0x81 <= rawtext[i + 2] && rawtext[i + 2] <= (byte) 0xFE && (byte) 0x30 <= rawtext[i + 3]
&& rawtext[i + 3] <= (byte) 0x39) {
gbchars++;
/*
* totalfreq += 500; row = rawtext[i] + 256 - 0x81; if (0x40 <= rawtext[i+1] && rawtext[i+1] <=
* 0x7E) { column = rawtext[i+1] - 0x40; } else { column = rawtext[i+1] + 256 - 0x40; }
* //System.out.println("extended row " + row + " column " + column + " rawtext[i] " +
* rawtext[i]); if (GBKFreq[row][column] != 0) { gbfreq += GBKFreq[row][column]; }
*/
}
i++;
}
}
rangeval = 50 * ((float) gbchars / (float) dbchars);
freqval = 50 * ((float) gbfreq / (float) totalfreq);
// For regular GB files, this would give the same score, so I handicap
// it slightly
return (int) (rangeval + freqval) - 1;
}
/*
* Function: hz_probability Argument: byte array Returns : number from 0 to 100 representing probability text in
* array uses HZ encoding
*/
int hz_probability(byte[] rawtext) {
int i, rawtextlen;
int hzchars = 0, dbchars = 1;
long hzfreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int hzstart = 0, hzend = 0;
int row, column;
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen; ++i) {
if (rawtext[i] == '~') {
if (rawtext[i + 1] == '{') {
hzstart++;
i += 2;
while (i < rawtextlen - 1) {
if (rawtext[i] == 0x0A || rawtext[i] == 0x0D) {
break;
} else if (rawtext[i] == '~' && rawtext[i + 1] == '}') {
hzend++;
i++;
break;
} else if ((0x21 <= rawtext[i] && rawtext[i] <= 0x77) && (0x21 <= rawtext[i + 1] && rawtext[i + 1] <= 0x77)) {
hzchars += 2;
row = rawtext[i] - 0x21;
column = rawtext[i + 1] - 0x21;
totalfreq += 500;
if (GBFreq[row][column] != 0) {
hzfreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
hzfreq += 200;
}
} else if ((0xA1 <= rawtext[i] && rawtext[i] <= 0xF7) && (0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= 0xF7)) {
hzchars += 2;
row = rawtext[i] + 256 - 0xA1;
column = rawtext[i + 1] + 256 - 0xA1;
totalfreq += 500;
if (GBFreq[row][column] != 0) {
hzfreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
hzfreq += 200;
}
}
dbchars += 2;
i += 2;
}
} else if (rawtext[i + 1] == '}') {
hzend++;
i++;
} else if (rawtext[i + 1] == '~') {
i++;
}
}
}
if (hzstart > 4) {
rangeval = 50;
} else if (hzstart > 1) {
rangeval = 41;
} else if (hzstart > 0) { // Only 39 in case the sequence happened to
// occur
rangeval = 39; // in otherwise non-Hz text
} else {
rangeval = 0;
}
freqval = 50 * ((float) hzfreq / (float) totalfreq);
return (int) (rangeval + freqval);
}
/**
* Function: big5_probability Argument: byte array Returns : number from
* 0 to 100 representing probability text in array uses Big5 encoding
*/
int big5_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, bfchars = 1;
float rangeval = 0, freqval = 0;
long bffreq = 0, totalfreq = 1;
int row, column;
// Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
if (rawtext[i] >= 0) {
// asciichars++;
} else {
dbchars++;
if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF9
&& (((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E)
|| ((byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE))) {
bfchars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0xA1;
if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) {
column = rawtext[i + 1] - 0x40;
} else {
column = rawtext[i + 1] + 256 - 0x61;
}
if (Big5Freq[row][column] != 0) {
bffreq += Big5Freq[row][column];
} else if (3 <= row && row <= 37) {
bffreq += 200;
}
}
i++;
}
}
rangeval = 50 * ((float) bfchars / (float) dbchars);
freqval = 50 * ((float) bffreq / (float) totalfreq);
return (int) (rangeval + freqval);
}
/*
* Function: big5plus_probability Argument: pointer to unsigned char array Returns : number from 0 to 100
* representing probability text in array uses Big5+ encoding
*/
int big5plus_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, bfchars = 1;
long bffreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Stage 1: Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
// System.err.println(rawtext[i]);
if (rawtext[i] >= 128) {
// asciichars++;
} else {
dbchars++;
if (0xA1 <= rawtext[i] && rawtext[i] <= 0xF9
&& // Original Big5 range
((0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) || (0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= 0xFE))) {
bfchars++;
totalfreq += 500;
row = rawtext[i] - 0xA1;
if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) {
column = rawtext[i + 1] - 0x40;
} else {
column = rawtext[i + 1] - 0x61;
}
// System.out.println("original row " + row + " column " +
// column);
if (Big5Freq[row][column] != 0) {
bffreq += Big5Freq[row][column];
} else if (3 <= row && row < 37) {
bffreq += 200;
}
} else if (0x81 <= rawtext[i] && rawtext[i] <= 0xFE
&& // Extended Big5 range
((0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) || (0x80 <= rawtext[i + 1] && rawtext[i + 1] <= 0xFE))) {
bfchars++;
totalfreq += 500;
row = rawtext[i] - 0x81;
if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) {
column = rawtext[i + 1] - 0x40;
} else {
column = rawtext[i + 1] - 0x40;
}
// System.out.println("extended row " + row + " column " +
// column + " rawtext[i] " + rawtext[i]);
if (Big5PFreq[row][column] != 0) {
bffreq += Big5PFreq[row][column];
}
}
i++;
}
}
rangeval = 50 * ((float) bfchars / (float) dbchars);
freqval = 50 * ((float) bffreq / (float) totalfreq);
// For regular Big5 files, this would give the same score, so I handicap
// it slightly
return (int) (rangeval + freqval) - 1;
}
/*
* Function: euc_tw_probability Argument: byte array Returns : number from 0 to 100 representing probability
* text in array uses EUC-TW (CNS 11643) encoding
*/
int euc_tw_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, cnschars = 1;
long cnsfreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Check to see if characters fit into acceptable ranges
// and have expected frequency of use
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
if (rawtext[i] >= 0) { // in ASCII range
// asciichars++;
} else { // high bit set
dbchars++;
if (i + 3 < rawtextlen && (byte) 0x8E == rawtext[i] && (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xB0
&& (byte) 0xA1 <= rawtext[i + 2] && rawtext[i + 2] <= (byte) 0xFE && (byte) 0xA1 <= rawtext[i + 3]
&& rawtext[i + 3] <= (byte) 0xFE) { // Planes 1 - 16
cnschars++;
// System.out.println("plane 2 or above CNS char");
// These are all less frequent chars so just ignore freq
i += 3;
} else if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xFE
&& // Plane 1
(byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) {
cnschars++;
totalfreq += 500;
row = rawtext[i] + 256 - 0xA1;
column = rawtext[i + 1] + 256 - 0xA1;
if (EUC_TWFreq[row][column] != 0) {
cnsfreq += EUC_TWFreq[row][column];
} else if (35 <= row && row <= 92) {
cnsfreq += 150;
}
i++;
}
}
}
rangeval = 50 * ((float) cnschars / (float) dbchars);
freqval = 50 * ((float) cnsfreq / (float) totalfreq);
return (int) (rangeval + freqval);
}
/*
* Function: iso_2022_cn_probability Argument: byte array Returns : number from 0 to 100 representing
* probability text in array uses ISO 2022-CN encoding WORKS FOR BASIC CASES, BUT STILL NEEDS MORE WORK
*/
int iso_2022_cn_probability(byte[] rawtext) {
int i, rawtextlen = 0;
int dbchars = 1, isochars = 1;
long isofreq = 0, totalfreq = 1;
float rangeval = 0, freqval = 0;
int row, column;
// Check to see if characters fit into acceptable ranges
// and have expected frequency of use
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen - 1; ++i) {
if (rawtext[i] == (byte) 0x1B && i + 3 < rawtextlen) { // Escape
// char ESC
if (rawtext[i + 1] == (byte) 0x24 && rawtext[i + 2] == 0x29 && rawtext[i + 3] == (byte) 0x41) { // GB
// Escape
// $
// )
// A
i += 4;
while (rawtext[i] != (byte) 0x1B) {
dbchars++;
if ((0x21 <= rawtext[i] && rawtext[i] <= 0x77) && (0x21 <= rawtext[i + 1] && rawtext[i + 1] <= 0x77)) {
isochars++;
row = rawtext[i] - 0x21;
column = rawtext[i + 1] - 0x21;
totalfreq += 500;
if (GBFreq[row][column] != 0) {
isofreq += GBFreq[row][column];
} else if (15 <= row && row < 55) {
isofreq += 200;
}
i++;
}
i++;
}
} else if (i + 3 < rawtextlen && rawtext[i + 1] == (byte) 0x24 && rawtext[i + 2] == (byte) 0x29
&& rawtext[i + 3] == (byte) 0x47) {
// CNS Escape $ ) G
i += 4;
while (rawtext[i] != (byte) 0x1B) {
dbchars++;
if ((byte) 0x21 <= rawtext[i] && rawtext[i] <= (byte) 0x7E && (byte) 0x21 <= rawtext[i + 1]
&& rawtext[i + 1] <= (byte) 0x7E) {
isochars++;
totalfreq += 500;
row = rawtext[i] - 0x21;
column = rawtext[i + 1] - 0x21;
if (EUC_TWFreq[row][column] != 0) {
isofreq += EUC_TWFreq[row][column];
} else if (35 <= row && row <= 92) {
isofreq += 150;
}
i++;
}
i++;
}
}
if (rawtext[i] == (byte) 0x1B && i + 2 < rawtextlen && rawtext[i + 1] == (byte) 0x28 && rawtext[i + 2] == (byte) 0x42) { // ASCII:
// ESC
// ( B
i += 2;
}
}
}
rangeval = 50 * ((float) isochars / (float) dbchars);
freqval = 50 * ((float) isofreq / (float) totalfreq);
// System.out.println("isochars dbchars isofreq totalfreq " + isochars +
// " " + dbchars + " " + isofreq + " " + totalfreq + "
// " + rangeval + " " + freqval);
return (int) (rangeval + freqval);
// return 0;
}
/*
* Function: utf8_probability Argument: byte array Returns : number from 0 to 100 representing probability text
* in array uses UTF-8 encoding of Unicode
*/
int utf8_probability(byte[] rawtext) {
int score = 0;
int i, rawtextlen = 0;
int goodbytes = 0, asciibytes = 0;
// Maybe also use UTF8 Byte Order Mark: EF BB BF
// Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen; ++i) {
if ((rawtext[i] & (byte) 0x7F) == rawtext[i]) { // One byte
asciibytes++;
// Ignore ASCII, can throw off count
} else if (-64 <= rawtext[i] && rawtext[i] <= -33
&& // Two bytes
i + 1 < rawtextlen && -128 <= rawtext[i + 1] && rawtext[i + 1] <= -65) {
goodbytes += 2;
i++;
} else if (-32 <= rawtext[i] && rawtext[i] <= -17
&& // Three bytes
i + 2 < rawtextlen && -128 <= rawtext[i + 1] && rawtext[i + 1] <= -65 && -128 <= rawtext[i + 2]
&& rawtext[i + 2] <= -65) {
goodbytes += 3;
i += 2;
}
}
if (asciibytes == rawtextlen) {
return 0;
}
score = (int) (100 * ((float) goodbytes / (float) (rawtextlen - asciibytes)));
// System.out.println("rawtextlen " + rawtextlen + " goodbytes " +
// goodbytes + " asciibytes " + asciibytes + " score " +
// score);
// If not above 98, reduce to zero to prevent coincidental matches
// Allows for some (few) bad formed sequences
if (score > 98) {
return score;
} else if (score > 95 && goodbytes > 30) {
return score;
} else {
return 0;
}
}
/*
* Function: utf16_probability Argument: byte array Returns : number from 0 to 100 representing probability text
* in array uses UTF-16 encoding of Unicode, guess based on BOM // NOT VERY GENERAL, NEEDS MUCH MORE WORK
*/
int utf16_probability(byte[] rawtext) {
// int score = 0;
// int i, rawtextlen = 0;
// int goodbytes = 0, asciibytes = 0;
if (rawtext.length > 1 && ((byte) 0xFE == rawtext[0] && (byte) 0xFF == rawtext[1])
|| // Big-endian
((byte) 0xFF == rawtext[0] && (byte) 0xFE == rawtext[1])) { // Little-endian
return 100;
}
return 0;
/*
* // Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i <
* rawtextlen; i++) { if ((rawtext[i] & (byte)0x7F) == rawtext[i]) { // One byte goodbytes += 1;
* asciibytes++; } else if ((rawtext[i] & (byte)0xDF) == rawtext[i]) { // Two bytes if (i+1 < rawtextlen &&
* (rawtext[i+1] & (byte)0xBF) == rawtext[i+1]) { goodbytes += 2; i++; } } else if ((rawtext[i] &
* (byte)0xEF) == rawtext[i]) { // Three bytes if (i+2 < rawtextlen && (rawtext[i+1] & (byte)0xBF) ==
* rawtext[i+1] && (rawtext[i+2] & (byte)0xBF) == rawtext[i+2]) { goodbytes += 3; i+=2; } } }
*
* score = (int)(100 * ((float)goodbytes/(float)rawtext.length)); // An all ASCII file is also a good UTF8
* file, but I'd rather it // get identified as ASCII. Can delete following 3 lines otherwise if (goodbytes
* == asciibytes) { score = 0; } // If not above 90, reduce to zero to prevent coincidental matches if
* (score > 90) { return score; } else { return 0; }
*/
}
/*
* Function: ascii_probability Argument: byte array Returns : number from 0 to 100 representing probability text
* in array uses all ASCII Description: Sees if array has any characters not in ASCII range, if so, score is
* reduced
*/
int ascii_probability(byte[] rawtext) {
int score = 75;
int i, rawtextlen;
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen; ++i) {
if (rawtext[i] < 0) {
score = score - 5;
} else if (rawtext[i] == (byte) 0x1B) { // ESC (used by ISO 2022)
| 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/thridparty/ColorTemperature.java | released/MyBox/src/main/java/thridparty/ColorTemperature.java | package thridparty;
/**
* @Author http://brucelindbloom.com/index.html?Eqn_XYZ_to_T.html
* http://brucelindbloom.com/index.html?Eqn_T_to_xy.html
*
*/
public class ColorTemperature {
public static double[] rt = { /* reciprocal temperature (K) */
-Double.MAX_VALUE, 10.0e-6, 20.0e-6, 30.0e-6, 40.0e-6, 50.0e-6,
60.0e-6, 70.0e-6, 80.0e-6, 90.0e-6, 100.0e-6, 125.0e-6,
150.0e-6, 175.0e-6, 200.0e-6, 225.0e-6, 250.0e-6, 275.0e-6,
300.0e-6, 325.0e-6, 350.0e-6, 375.0e-6, 400.0e-6, 425.0e-6,
450.0e-6, 475.0e-6, 500.0e-6, 525.0e-6, 550.0e-6, 575.0e-6,
600.0e-6
};
public static double[][] uvt = {
{0.18006, 0.26352, -0.24341},
{0.18066, 0.26589, -0.25479},
{0.18133, 0.26846, -0.26876},
{0.18208, 0.27119, -0.28539},
{0.18293, 0.27407, -0.30470},
{0.18388, 0.27709, -0.32675},
{0.18494, 0.28021, -0.35156},
{0.18611, 0.28342, -0.37915},
{0.18740, 0.28668, -0.40955},
{0.18880, 0.28997, -0.44278},
{0.19032, 0.29326, -0.47888},
{0.19462, 0.30141, -0.58204},
{0.19962, 0.30921, -0.70471},
{0.20525, 0.31647, -0.84901},
{0.21142, 0.32312, -1.0182},
{0.21807, 0.32909, -1.2168},
{0.22511, 0.33439, -1.4512},
{0.23247, 0.33904, -1.7298},
{0.24010, 0.34308, -2.0637},
{0.24792, 0.34655, -2.4681}, /* Note: 0.24792 is a corrected value for the error found in W&S as 0.24702 */
{0.25591, 0.34951, -2.9641},
{0.26400, 0.35200, -3.5814},
{0.27218, 0.35407, -4.3633},
{0.28039, 0.35577, -5.3762},
{0.28863, 0.35714, -6.7262},
{0.29685, 0.35823, -8.5955},
{0.30505, 0.35907, -11.324},
{0.31320, 0.35968, -15.628},
{0.32129, 0.36011, -23.325},
{0.32931, 0.36038, -40.770},
{0.33724, 0.36051, -116.45}
};
// xyz are tristimulus values
public static double xyz2ColorTemp(double[] xyz) {
if ((xyz[0] < 1.0e-20) && (xyz[1] < 1.0e-20) && (xyz[2] < 1.0e-20)) {
return (-1);
/* protect against possible divide-by-zero failure */
}
double us = (4.0 * xyz[0]) / (xyz[0] + 15.0 * xyz[1] + 3.0 * xyz[2]);
double vs = (6.0 * xyz[1]) / (xyz[0] + 15.0 * xyz[1] + 3.0 * xyz[2]);
double di = 0.0, dm = 0.0;
int i;
for (i = 0; i < uvt.length; ++i) {
di = (vs - uvt[i][1]) - uvt[i][2] * (us - uvt[i][0]);
if ((i > 0) && (((di < 0.0) && (dm >= 0.0)) || ((di >= 0.0) && (dm < 0.0)))) {
break;
/* found lines bounding (us, vs) : i-1 and i */
}
dm = di;
}
if (i == 31) {
return (-1);
/* bad XYZ input, color temp would be less than minimum of 1666.7 degrees, or too far towards blue */
}
di = di / Math.sqrt(1.0 + uvt[i][2] * uvt[i][2]);
dm = dm / Math.sqrt(1.0 + uvt[i - 1][2] * uvt[i - 1][2]);
double temp = dm / (dm - di);
/* temp = interpolation parameter, 0.0 : i-1, 1.0 : i */
temp = 1.0 / ((rt[i] - rt[i - 1]) * temp + rt[i - 1]);
return temp;
}
public static double[] colorTemp2xy(double temp) {
if (temp < 4000 || temp > 25000) {
return null;
}
double[] xy = new double[2];
if (temp <= 7000) {
xy[0] = -4.6070 * Math.pow(10, 9) / Math.pow(temp, 3)
+ 2.9678 * Math.pow(10, 6) / Math.pow(temp, 2)
+ 0.09911 * Math.pow(10, 3) / temp + 0.244063;
} else {
xy[0] = -2.0064 * Math.pow(10, 9) / Math.pow(temp, 3)
+ 1.9018 * Math.pow(10, 6) / Math.pow(temp, 2)
+ 0.24748 * Math.pow(10, 3) / temp + 0.237040;
}
xy[1] = -3.000 * Math.pow(xy[0], 2) + 2.870 * xy[0] - 0.275;
return xy;
}
}
| 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/thridparty/GifDecoder.java | released/MyBox/src/main/java/thridparty/GifDecoder.java | package thridparty;
import static java.lang.System.arraycopy;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2014 Dhyan Blum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>
* A decoder capable of processing a GIF data stream to render the graphics
* contained in it. This implementation follows the official
* <A HREF="http://www.w3.org/Graphics/GIF/spec-gif89a.txt">GIF
* specification</A>.
* </p>
*
* <p>
* Example usage:
* </p>
*
* <p>
*
* <pre>
* final GifImage gifImage = GifDecoder.read(int[] data);
* final int width = gifImage.getWidth();
* final int height = gifImage.getHeight();
* final int frameCount = gifImage.getFrameCount();
* for (int i = 0; i < frameCount; ++i) {
* final BufferedImage image = gifImage.getFrame(i);
* final int delay = gif.getDelay(i);
* }
* </pre>
*
* </p>
*
* @author Dhyan Blum
* @version 1.09 November 2017
*
*/
public final class GifDecoder {
static final class BitReader {
private int bitPos; // Next bit to read
private int numBits; // Number of bits to read
private int bitMask; // Use to kill unwanted higher bits
private byte[] in; // Data array
// To avoid costly bounds checks, 'in' needs 2 more 0-bytes at the end
private final void init(final byte[] in) {
this.in = in;
bitPos = 0;
}
private final int read() {
// Byte indices: (bitPos / 8), (bitPos / 8) + 1, (bitPos / 8) + 2
int i = bitPos >>> 3; // Byte = bit / 8
// Bits we'll shift to the right, AND 7 is the same as MODULO 8
final int rBits = bitPos & 7;
// Byte 0 to 2, AND to get their unsigned values
final int b0 = in[i++] & 0xFF, b1 = in[i++] & 0xFF, b2 = in[i] & 0xFF;
// Glue the bytes together, don't do more shifting than necessary
final int buf = ((b2 << 8 | b1) << 8 | b0) >>> rBits;
bitPos += numBits;
return buf & bitMask; // Kill the unwanted higher bits
}
private final void setNumBits(final int numBits) {
this.numBits = numBits;
bitMask = (1 << numBits) - 1;
}
}
static final class CodeTable {
private final int[][] tbl; // Maps codes to lists of colors
private int initTableSize; // Number of colors +2 for CLEAR + EOI
private int initCodeSize; // Initial code size
private int initCodeLimit; // First code limit
private int codeSize; // Current code size, maximum is 12 bits
private int nextCode; // Next available code for a new entry
private int nextCodeLimit; // Increase codeSize when nextCode == limit
private BitReader br; // Notify when code sizes increases
public CodeTable() {
tbl = new int[4096][1];
}
private final int add(final int[] indices) {
if (nextCode < 4096) {
if (nextCode == nextCodeLimit && codeSize < 12) {
codeSize++; // Max code size is 12
br.setNumBits(codeSize);
nextCodeLimit = (1 << codeSize) - 1; // 2^codeSize - 1
}
tbl[nextCode++] = indices;
}
return codeSize;
}
private final int clear() {
codeSize = initCodeSize;
br.setNumBits(codeSize);
nextCodeLimit = initCodeLimit;
nextCode = initTableSize; // Don't recreate table, reset pointer
return codeSize;
}
private final void init(final GifFrame fr, final int[] activeColTbl, final BitReader br) {
this.br = br;
final int numColors = activeColTbl.length;
initCodeSize = fr.firstCodeSize;
initCodeLimit = (1 << initCodeSize) - 1; // 2^initCodeSize - 1
initTableSize = fr.endOfInfoCode + 1;
nextCode = initTableSize;
for (int c = numColors - 1; c >= 0; c--) {
tbl[c][0] = activeColTbl[c]; // Translated color
} // A gap may follow with no colors assigned if numCols < CLEAR
tbl[fr.clearCode] = new int[]{fr.clearCode}; // CLEAR
tbl[fr.endOfInfoCode] = new int[]{fr.endOfInfoCode}; // EOI
// Locate transparent color in code table and set to 0
if (fr.transpColFlag && fr.transpColIndex < numColors) {
tbl[fr.transpColIndex][0] = 0;
}
}
}
final class GifFrame {
// Graphic control extension (optional)
// Disposal: 0=NO_ACTION, 1=NO_DISPOSAL, 2=RESTORE_BG, 3=RESTORE_PREV
private int disposalMethod; // 0-3 as above, 4-7 undefined
private boolean transpColFlag; // 1 Bit
private int delay; // Unsigned, LSByte first, n * 1/100 * s
private int transpColIndex; // 1 Byte
// Image descriptor
private int x; // Position on the canvas from the left
private int y; // Position on the canvas from the top
private int w; // May be smaller than the base image
private int h; // May be smaller than the base image
private int wh; // width * height
private boolean hasLocColTbl; // Has local color table? 1 Bit
private boolean interlaceFlag; // Is an interlace image? 1 Bit
@SuppressWarnings("unused")
private boolean sortFlag; // True if local colors are sorted, 1 Bit
private int sizeOfLocColTbl; // Size of the local color table, 3 Bits
private int[] localColTbl; // Local color table (optional)
// Image data
private int firstCodeSize; // LZW minimum code size + 1 for CLEAR & EOI
private int clearCode;
private int endOfInfoCode;
private byte[] data; // Holds LZW encoded data
private BufferedImage img; // Full drawn image, not just the frame area
}
public final class GifImage {
public String header; // Bytes 0-5, GIF87a or GIF89a
private int w; // Unsigned 16 Bit, least significant byte first
private int h; // Unsigned 16 Bit, least significant byte first
private int wh; // Image width * image height
public boolean hasGlobColTbl; // 1 Bit
public int colorResolution; // 3 Bits
public boolean sortFlag; // True if global colors are sorted, 1 Bit
public int sizeOfGlobColTbl; // 2^(val(3 Bits) + 1), see spec
public int bgColIndex; // Background color index, 1 Byte
public int pxAspectRatio; // Pixel aspect ratio, 1 Byte
public int[] globalColTbl; // Global color table
private final List<GifFrame> frames = new ArrayList<>(64);
public String appId = ""; // 8 Bytes at in[i+3], usually "NETSCAPE"
public String appAuthCode = ""; // 3 Bytes at in[i+11], usually "2.0"
public int repetitions = 0; // 0: infinite loop, N: number of loops
private BufferedImage img = null; // Currently drawn frame
private int[] prevPx = null; // Previous frame's pixels
private final BitReader bits = new BitReader();
private final CodeTable codes = new CodeTable();
private Graphics2D g;
private final int[] decode(final GifFrame fr, final int[] activeColTbl) {
codes.init(fr, activeColTbl, bits);
bits.init(fr.data); // Incoming codes
final int clearCode = fr.clearCode, endCode = fr.endOfInfoCode;
final int[] out = new int[wh]; // Target image pixel array
final int[][] tbl = codes.tbl; // Code table
int outPos = 0; // Next pixel position in the output image array
codes.clear(); // Init code table
bits.read(); // Skip leading clear code
int code = bits.read(); // Read first code
int[] pixels = tbl[code]; // Output pixel for first code
arraycopy(pixels, 0, out, outPos, pixels.length);
outPos += pixels.length;
try {
while (true) {
final int prevCode = code;
code = bits.read(); // Get next code in stream
if (code == clearCode) { // After a CLEAR table, there is
codes.clear(); // no previous code, we need to read
code = bits.read(); // a new one
pixels = tbl[code]; // Output pixels
arraycopy(pixels, 0, out, outPos, pixels.length);
outPos += pixels.length;
continue; // Back to the loop with a valid previous code
} else if (code == endCode) {
break;
}
final int[] prevVals = tbl[prevCode];
final int[] prevValsAndK = new int[prevVals.length + 1];
arraycopy(prevVals, 0, prevValsAndK, 0, prevVals.length);
if (code < codes.nextCode) { // Code table contains code
pixels = tbl[code]; // Output pixels
arraycopy(pixels, 0, out, outPos, pixels.length);
outPos += pixels.length;
prevValsAndK[prevVals.length] = tbl[code][0]; // K
} else {
prevValsAndK[prevVals.length] = prevVals[0]; // K
arraycopy(prevValsAndK, 0, out, outPos, prevValsAndK.length);
outPos += prevValsAndK.length;
}
codes.add(prevValsAndK); // Previous indices + K
}
} catch (final ArrayIndexOutOfBoundsException e) {
}
return out;
}
private final int[] deinterlace(final int[] src, final GifFrame fr) {
final int w = fr.w, h = fr.h, wh = fr.wh;
final int[] dest = new int[src.length];
// Interlaced images are organized in 4 sets of pixel lines
final int set2Y = (h + 7) >>> 3; // Line no. = ceil(h/8.0)
final int set3Y = set2Y + ((h + 3) >>> 3); // ceil(h-4/8.0)
final int set4Y = set3Y + ((h + 1) >>> 2); // ceil(h-2/4.0)
// Sets' start indices in source array
final int set2 = w * set2Y, set3 = w * set3Y, set4 = w * set4Y;
// Line skips in destination array
final int w2 = w << 1, w4 = w2 << 1, w8 = w4 << 1;
// Group 1 contains every 8th line starting from 0
int from = 0, to = 0;
for (; from < set2; from += w, to += w8) {
arraycopy(src, from, dest, to, w);
} // Group 2 contains every 8th line starting from 4
for (to = w4; from < set3; from += w, to += w8) {
arraycopy(src, from, dest, to, w);
} // Group 3 contains every 4th line starting from 2
for (to = w2; from < set4; from += w, to += w4) {
arraycopy(src, from, dest, to, w);
} // Group 4 contains every 2nd line starting from 1 (biggest group)
for (to = w; from < wh; from += w, to += w2) {
arraycopy(src, from, dest, to, w);
}
return dest; // All pixel lines have now been rearranged
}
private final void drawFrame(final GifFrame fr) {
// Determine the color table that will be active for this frame
final int[] activeColTbl = fr.hasLocColTbl ? fr.localColTbl : globalColTbl;
// Get pixels from data stream
int[] pixels = decode(fr, activeColTbl);
if (fr.interlaceFlag) {
pixels = deinterlace(pixels, fr); // Rearrange pixel lines
}
// Create image of type 2=ARGB for frame area
final BufferedImage frame = new BufferedImage(fr.w, fr.h, 2);
arraycopy(pixels, 0, ((DataBufferInt) frame.getRaster().getDataBuffer()).getData(), 0, fr.wh);
// Draw frame area on top of working image
g.drawImage(frame, fr.x, fr.y, null);
// Visualize frame boundaries during testing
// if (DEBUG_MODE) {
// if (prev != null) {
// g.setColor(Color.RED); // Previous frame color
// g.drawRect(prev.x, prev.y, prev.w - 1, prev.h - 1);
// }
// g.setColor(Color.GREEN); // New frame color
// g.drawRect(fr.x, fr.y, fr.w - 1, fr.h - 1);
// }
// Keep one copy as "previous frame" in case we need to restore it
prevPx = new int[wh];
arraycopy(((DataBufferInt) img.getRaster().getDataBuffer()).getData(), 0, prevPx, 0, wh);
// Create another copy for the end user to not expose internal state
fr.img = new BufferedImage(w, h, 2); // 2 = ARGB
arraycopy(prevPx, 0, ((DataBufferInt) fr.img.getRaster().getDataBuffer()).getData(), 0, wh);
// Handle disposal of current frame
if (fr.disposalMethod == 2) {
// Restore to background color (clear frame area only)
g.clearRect(fr.x, fr.y, fr.w, fr.h);
} else if (fr.disposalMethod == 3 && prevPx != null) {
// Restore previous frame
arraycopy(prevPx, 0, ((DataBufferInt) img.getRaster().getDataBuffer()).getData(), 0, wh);
}
}
/**
* Returns the background color of the first frame in this GIF image. If
* the frame has a local color table, the returned color will be from
* that table. If not, the color will be from the global color table.
* Returns 0 if there is neither a local nor a global color table.
*
* @param index Index of the current frame, 0 to N-1
* @return 32 bit ARGB color in the form 0xAARRGGBB
*/
public final int getBackgroundColor() {
final GifFrame frame = frames.get(0);
if (frame.hasLocColTbl) {
return frame.localColTbl[bgColIndex];
} else if (hasGlobColTbl) {
return globalColTbl[bgColIndex];
}
return 0;
}
/**
* If not 0, the delay specifies how many hundredths (1/100) of a second
* to wait before displaying the frame <i>after</i> the current frame.
*
* @param index Index of the current frame, 0 to N-1
* @return Delay as number of hundredths (1/100) of a second
*/
public final int getDelay(final int index) {
return frames.get(index).delay;
}
/**
* @param index Index of the frame to return as image, starting from 0.
* For incremental calls such as [0, 1, 2, ...] the method's run time is
* O(1) as only one frame is drawn per call. For random access calls
* such as [7, 12, ...] the run time is O(N+1) with N being the number
* of previous frames that need to be drawn before N+1 can be drawn on
* top. Once a frame has been drawn it is being cached and the run time
* is more or less O(0) to retrieve it from the list.
* @return A BufferedImage for the specified frame.
*/
public final BufferedImage getFrame(final int index) {
if (img == null) { // Init
img = new BufferedImage(w, h, 2); // 2 = ARGB
g = img.createGraphics();
g.setBackground(new Color(0, true)); // Transparent color
}
GifFrame fr = frames.get(index);
if (fr.img == null) {
// Draw all frames until and including the requested frame
for (int i = 0; i <= index; ++i) {
fr = frames.get(i);
if (fr.img == null) {
drawFrame(fr);
}
}
}
return fr.img;
}
/**
* @return The number of frames contained in this GIF image
*/
public final int getFrameCount() {
return frames.size();
}
/**
* @return The height of the GIF image
*/
public final int getHeight() {
return h;
}
/**
* @return The width of the GIF image
*/
public final int getWidth() {
return w;
}
}
static final boolean DEBUG_MODE = false;
/**
* @param in Raw image data as a byte[] array
* @return A GifImage object exposing the properties of the GIF image.
* @throws IOException If the image violates the GIF specification or is
* truncated.
*/
public static final GifImage read(final byte[] in) throws IOException {
final GifDecoder decoder = new GifDecoder();
final GifImage img = decoder.new GifImage();
GifFrame frame = null; // Currently open frame
int pos = readHeader(in, img); // Read header, get next byte position
pos = readLogicalScreenDescriptor(img, in, pos);
if (img.hasGlobColTbl) {
img.globalColTbl = new int[img.sizeOfGlobColTbl];
pos = readColTbl(in, img.globalColTbl, pos);
}
while (pos < in.length) {
final int block = in[pos] & 0xFF;
switch (block) {
case 0x21: // Extension introducer
if (pos + 1 >= in.length) {
throw new IOException("Unexpected end of file.");
}
switch (in[pos + 1] & 0xFF) {
case 0xFE: // Comment extension
pos = readTextExtension(in, pos);
break;
case 0xFF: // Application extension
pos = readAppExt(img, in, pos);
break;
case 0x01: // Plain text extension
frame = null; // End of current frame
pos = readTextExtension(in, pos);
break;
case 0xF9: // Graphic control extension
if (frame == null) {
frame = decoder.new GifFrame();
img.frames.add(frame);
}
pos = readGraphicControlExt(frame, in, pos);
break;
default:
throw new IOException("Unknown extension at " + pos);
}
break;
case 0x2C: // Image descriptor
if (frame == null) {
frame = decoder.new GifFrame();
img.frames.add(frame);
}
pos = readImgDescr(frame, in, pos);
if (frame.hasLocColTbl) {
frame.localColTbl = new int[frame.sizeOfLocColTbl];
pos = readColTbl(in, frame.localColTbl, pos);
}
pos = readImgData(frame, in, pos);
frame = null; // End of current frame
break;
case 0x3B: // GIF Trailer
return img; // Found trailer, finished reading.
default:
// Unknown block. The image is corrupted. Strategies: a) Skip
// and wait for a valid block. Experience: It'll get worse. b)
// Throw exception. c) Return gracefully if we are almost done
// processing. The frames we have so far should be error-free.
final double progress = 1.0 * pos / in.length;
if (progress < 0.9) {
throw new IOException("Unknown block at: " + pos);
}
pos = in.length; // Exit loop
}
}
return img;
}
/**
* @param is Image data as input stream. This method will read from the
* input stream's current position. It will not reset the position before
* reading and won't reset or close the stream afterwards. Call these
* methods before and after calling this method as needed.
* @return A GifImage object exposing the properties of the GIF image.
* @throws IOException If an I/O error occurs, the image violates the GIF
* specification or the GIF is truncated.
*/
public static final GifImage read(final InputStream is) throws IOException {
final byte[] data = new byte[is.available()];
is.read(data, 0, data.length);
return read(data);
}
/**
* @param ext Empty application extension object
* @param in Raw data
* @param i Index of the first byte of the application extension
* @return Index of the first byte after this extension
*/
static final int readAppExt(final GifImage img, final byte[] in, int i) {
img.appId = new String(in, i + 3, 8); // should be "NETSCAPE"
img.appAuthCode = new String(in, i + 11, 3); // should be "2.0"
i += 14; // Go to sub-block size, it's value should be 3
final int subBlockSize = in[i] & 0xFF;
// The only app extension widely used is NETSCAPE, it's got 3 data bytes
if (subBlockSize == 3) {
// in[i+1] should have value 01, in[i+5] should be block terminator
img.repetitions = in[i + 2] & 0xFF | in[i + 3] & 0xFF << 8; // Short
return i + 5;
} // Skip unknown application extensions
while ((in[i] & 0xFF) != 0) { // While sub-block size != 0
i += (in[i] & 0xFF) + 1; // Skip to next sub-block
}
return i + 1;
}
/**
* @param in Raw data
* @param colors Pre-initialized target array to store ARGB colors
* @param i Index of the color table's first byte
* @return Index of the first byte after the color table
*/
static final int readColTbl(final byte[] in, final int[] colors, int i) {
final int numColors = colors.length;
for (int c = 0; c < numColors; c++) {
final int a = 0xFF; // Alpha 255 (opaque)
final int r = in[i++] & 0xFF; // 1st byte is red
final int g = in[i++] & 0xFF; // 2nd byte is green
final int b = in[i++] & 0xFF; // 3rd byte is blue
colors[c] = ((a << 8 | r) << 8 | g) << 8 | b;
}
return i;
}
/**
* @param ext Graphic control extension object
* @param in Raw data
* @param i Index of the extension introducer
* @return Index of the first byte after this block
*/
static final int readGraphicControlExt(final GifFrame fr, final byte[] in, final int i) {
fr.disposalMethod = (in[i + 3] & 0b00011100) >>> 2; // Bits 4-2
fr.transpColFlag = (in[i + 3] & 1) == 1; // Bit 0
fr.delay = in[i + 4] & 0xFF | (in[i + 5] & 0xFF) << 8; // 16 bit LSB
fr.transpColIndex = in[i + 6] & 0xFF; // Byte 6
return i + 8; // Skipped byte 7 (blockTerminator), as it's always 0x00
}
/**
* @param in Raw data
* @param img The GifImage object that is currently read
* @return Index of the first byte after this block
* @throws IOException If the GIF header/trailer is missing, incomplete or
* unknown
*/
static final int readHeader(final byte[] in, final GifImage img) throws IOException {
if (in.length < 6) { // Check first 6 bytes
throw new IOException("Image is truncated.");
}
img.header = new String(in, 0, 6);
if (!img.header.equals("GIF87a") && !img.header.equals("GIF89a")) {
throw new IOException("Invalid GIF header.");
}
return 6;
}
/**
* @param fr The GIF frame to whom this image descriptor belongs
* @param in Raw data
* @param i Index of the first byte of this block, i.e. the minCodeSize
* @return
*/
static final int readImgData(final GifFrame fr, final byte[] in, int i) {
final int fileSize = in.length;
final int minCodeSize = in[i++] & 0xFF; // Read code size, go to block
final int clearCode = 1 << minCodeSize; // CLEAR = 2^minCodeSize
fr.firstCodeSize = minCodeSize + 1; // Add 1 bit for CLEAR and EOI
fr.clearCode = clearCode;
fr.endOfInfoCode = clearCode + 1;
final int imgDataSize = readImgDataSize(in, i);
final byte[] imgData = new byte[imgDataSize + 2];
int imgDataPos = 0;
int subBlockSize = in[i] & 0xFF;
while (subBlockSize > 0) { // While block has data
try { // Next line may throw exception if sub-block size is fake
final int nextSubBlockSizePos = i + subBlockSize + 1;
final int nextSubBlockSize = in[nextSubBlockSizePos] & 0xFF;
arraycopy(in, i + 1, imgData, imgDataPos, subBlockSize);
imgDataPos += subBlockSize; // Move output data position
i = nextSubBlockSizePos; // Move to next sub-block size
subBlockSize = nextSubBlockSize;
} catch (final Exception e) {
// Sub-block exceeds file end, only use remaining bytes
subBlockSize = fileSize - i - 1; // Remaining bytes
arraycopy(in, i + 1, imgData, imgDataPos, subBlockSize);
imgDataPos += subBlockSize; // Move output data position
i += subBlockSize + 1; // Move to next sub-block size
break;
}
}
fr.data = imgData; // Holds LZW encoded data
i++; // Skip last sub-block size, should be 0
return i;
}
static final int readImgDataSize(final byte[] in, int i) {
final int fileSize = in.length;
int imgDataPos = 0;
int subBlockSize = in[i] & 0xFF;
while (subBlockSize > 0) { // While block has data
try { // Next line may throw exception if sub-block size is fake
final int nextSubBlockSizePos = i + subBlockSize + 1;
final int nextSubBlockSize = in[nextSubBlockSizePos] & 0xFF;
imgDataPos += subBlockSize; // Move output data position
i = nextSubBlockSizePos; // Move to next sub-block size
subBlockSize = nextSubBlockSize;
} catch (final Exception e) {
// Sub-block exceeds file end, only use remaining bytes
subBlockSize = fileSize - i - 1; // Remaining bytes
imgDataPos += subBlockSize; // Move output data position
break;
}
}
return imgDataPos;
}
/**
* @param fr The GIF frame to whom this image descriptor belongs
* @param in Raw data
* @param i Index of the image separator, i.e. the first block byte
* @return Index of the first byte after this block
*/
static final int readImgDescr(final GifFrame fr, final byte[] in, int i) {
fr.x = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 1-2: left
fr.y = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 3-4: top
fr.w = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 5-6: width
fr.h = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 7-8: height
fr.wh = fr.w * fr.h;
final byte b = in[++i]; // Byte 9 is a packed byte
fr.hasLocColTbl = (b & 0b10000000) >>> 7 == 1; // Bit 7
fr.interlaceFlag = (b & 0b01000000) >>> 6 == 1; // Bit 6
fr.sortFlag = (b & 0b00100000) >>> 5 == 1; // Bit 5
final int colTblSizePower = (b & 7) + 1; // Bits 2-0
fr.sizeOfLocColTbl = 1 << colTblSizePower; // 2^(N+1), As per the spec
return ++i;
}
/**
* @param img
* @param i Start index of this block.
* @return Index of the first byte after this block.
*/
static final int readLogicalScreenDescriptor(final GifImage img, final byte[] in, final int i) {
img.w = in[i] & 0xFF | (in[i + 1] & 0xFF) << 8; // 16 bit, LSB 1st
img.h = in[i + 2] & 0xFF | (in[i + 3] & 0xFF) << 8; // 16 bit
img.wh = img.w * img.h;
final byte b = in[i + 4]; // Byte 4 is a packed byte
img.hasGlobColTbl = (b & 0b10000000) >>> 7 == 1; // Bit 7
final int colResPower = ((b & 0b01110000) >>> 4) + 1; // Bits 6-4
img.colorResolution = 1 << colResPower; // 2^(N+1), As per the spec
img.sortFlag = (b & 0b00001000) >>> 3 == 1; // Bit 3
final int globColTblSizePower = (b & 7) + 1; // Bits 0-2
img.sizeOfGlobColTbl = 1 << globColTblSizePower; // 2^(N+1), see spec
img.bgColIndex = in[i + 5] & 0xFF; // 1 Byte
img.pxAspectRatio = in[i + 6] & 0xFF; // 1 Byte
return i + 7;
}
/**
* @param in Raw data
* @param pos Index of the extension introducer
* @return Index of the first byte after this block
*/
static final int readTextExtension(final byte[] in, final int pos) {
int i = pos + 2; // Skip extension introducer and label
int subBlockSize = in[i++] & 0xFF;
while (subBlockSize != 0 && i < in.length) {
i += subBlockSize;
subBlockSize = in[i++] & 0xFF;
}
return i;
}
}
| 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/thridparty/miguelemosreverte/Quantize.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/Quantize.java | package thridparty.miguelemosreverte;
/*
* @(#)Quantize.java 0.90 9/19/00 Adam Doppelt
*/
/**
* An efficient color quantization algorithm, adapted from the C++
* implementation quantize.c in <a
* href="http://www.imagemagick.org/">ImageMagick</a>. The pixels for
* an image are placed into an oct tree. The oct tree is reduced in
* size, and the pixels from the original image are reassigned to the
* nodes in the reduced tree.<p>
*
* Here is the copyright notice from ImageMagick:
*
* <pre>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% E. I. du Pont de Nemours and Company be liable for any claim, damages or %
% other liability, whether in an action of contract, tort or otherwise, %
% arising from, out of or in connection with ImageMagick or the use or other %
% dealings in ImageMagick. %
% %
% Except as contained in this notice, the name of the E. I. du Pont de %
% Nemours and Company shall not be used in advertising or otherwise to %
% promote the sale, use or other dealings in ImageMagick without prior %
% written authorization from the E. I. du Pont de Nemours and Company. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
</pre>
*
*
* @version 0.90 19 Sep 2000
* @author <a href="http://www.gurge.com/amd/">Adam Doppelt</a>
*/
public class Quantize {
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
% Q Q U U A A NN N T I ZZ E %
% Q Q U U AAAAA N N N T I ZZZ EEEEE %
% Q QQ U U A A N NN T I ZZ E %
% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
% %
% %
% Reduce the Number of Unique Colors in an Image %
% %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1998 E. I. du Pont de Nemours and Company %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% E. I. du Pont de Nemours and Company be liable for any claim, damages or %
% other liability, whether in an action of contract, tort or otherwise, %
% arising from, out of or in connection with ImageMagick or the use or other %
% dealings in ImageMagick. %
% %
% Except as contained in this notice, the name of the E. I. du Pont de %
% Nemours and Company shall not be used in advertising or otherwise to %
% promote the sale, use or other dealings in ImageMagick without prior %
% written authorization from the E. I. du Pont de Nemours and Company. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Realism in computer graphics typically requires using 24 bits/pixel to
% generate an image. Yet many graphic display devices do not contain
% the amount of memory necessary to match the spatial and color
% resolution of the human eye. The QUANTIZE program takes a 24 bit
% image and reduces the number of colors so it can be displayed on
% raster device with less bits per pixel. In most instances, the
% quantized image closely resembles the original reference image.
%
% A reduction of colors in an image is also desirable for image
% transmission and real-time animation.
%
% Function Quantize takes a standard RGB or monochrome images and quantizes
% them down to some fixed number of colors.
%
% For purposes of color allocation, an image is a set of n pixels, where
% each pixel is a point in RGB space. RGB space is a 3-dimensional
% vector space, and each pixel, pi, is defined by an ordered triple of
% red, green, and blue coordinates, (ri, gi, bi).
%
% Each primary color component (red, green, or blue) represents an
% intensity which varies linearly from 0 to a maximum value, cmax, which
% corresponds to full saturation of that color. Color allocation is
% defined over a domain consisting of the cube in RGB space with
% opposite vertices at (0,0,0) and (cmax,cmax,cmax). QUANTIZE requires
% cmax = 255.
%
% The algorithm maps this domain onto a tree in which each node
% represents a cube within that domain. In the following discussion
% these cubes are defined by the coordinate of two opposite vertices:
% The vertex nearest the origin in RGB space and the vertex farthest
% from the origin.
%
% The tree's root node represents the the entire domain, (0,0,0) through
% (cmax,cmax,cmax). Each lower level in the tree is generated by
% subdividing one node's cube into eight smaller cubes of equal size.
% This corresponds to bisecting the parent cube with planes passing
% through the midpoints of each edge.
%
% The basic algorithm operates in three phases: Classification,
% Reduction, and Assignment. Classification builds a color
% description tree for the image. Reduction collapses the tree until
% the number it represents, at most, the number of colors desired in the
% output image. Assignment defines the output image's color map and
% sets each pixel's color by reclassification in the reduced tree.
% Our goal is to minimize the numerical discrepancies between the original
% colors and quantized colors (quantization error).
%
% Classification begins by initializing a color description tree of
% sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color
% description tree in the classification phase for realistic values of
% cmax. If colors components in the input image are quantized to k-bit
% precision, so that cmax= 2k-1, the tree would need k levels below the
% root node to allow representing each possible input color in a leaf.
% This becomes prohibitive because the tree's total number of nodes is
% 1 + sum(i=1,k,8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, classification scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing the pixel's color. It updates the following data for each
% such node:
%
% n1: Number of pixels whose color is contained in the RGB cube
% which this node represents;
%
% n2: Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb: Sums of the red, green, and blue component values for
% all pixels not classified at a lower depth. The combination of
% these sums and n2 will ultimately characterize the mean color of a
% set of pixels represented by this node.
%
% E: The distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the quantization
% error for a node.
%
% Reduction repeatedly prunes the tree until the number of nodes with
% n2 > 0 is less than or equal to the maximum number of colors allowed
% in the output image. On any given iteration over the tree, it selects
% those nodes whose E count is minimal for pruning and merges their
% color statistics upward. It uses a pruning threshold, Ep, to govern
% node selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors
% within the cubic volume which the node represents. This includes n1 -
% n2 pixels whose colors should be defined by nodes at a lower level in
% the tree.
%
% Assignment generates the output image from the pruned tree. The
% output image consists of two parts: (1) A color map, which is an
% array of color descriptions (RGB triples) for each color present in
% the output image; (2) A pixel array, which represents each pixel as
% an index into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the
% mean color of all pixels that classify no lower than this node. Each
% of these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% With the permission of USC Information Sciences Institute, 4676 Admiralty
% Way, Marina del Rey, California 90292, this code was adapted from module
% ALCOLS written by Paul Raveling.
%
% The names of ISI and USC are not used in advertising or publicity
% pertaining to distribution of the software without prior specific
% written permission from ISI.
%
*/
final static boolean QUICK = true;
final static int MAX_RGB = 255;
final static int MAX_NODES = 266817;
final static int MAX_TREE_DEPTH = 8;
// these are precomputed in advance
static int SQUARES[];
static int SHIFT[];
static {
SQUARES = new int[MAX_RGB + MAX_RGB + 1];
for (int i= -MAX_RGB; i <= MAX_RGB; i++) {
SQUARES[i + MAX_RGB] = i * i;
}
SHIFT = new int[MAX_TREE_DEPTH + 1];
for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) {
SHIFT[i] = 1 << (15 - i);
}
}
/**
* Reduce the image to the given number of colors. The pixels are
* reduced in place.
* @return The new color palette.
*/
public static int[] quantizeImage(int pixels[][], int max_colors) {
Cube cube = new Cube(pixels, max_colors);
cube.classification();
cube.reduction();
cube.assignment();
return cube.colormap;
}
static class Cube {
int pixels[][];
int max_colors;
int colormap[];
Node root;
int depth;
// counter for the number of colors in the cube. this gets
// recalculated often.
int colors;
// counter for the number of nodes in the tree
int nodes;
Cube(int pixels[][], int max_colors) {
this.pixels = pixels;
this.max_colors = max_colors;
int i = max_colors;
// tree_depth = log max_colors
// 4
for (depth = 1; i != 0; depth++) {
i /= 4;
}
if (depth > 1) {
--depth;
}
if (depth > MAX_TREE_DEPTH) {
depth = MAX_TREE_DEPTH;
} else if (depth < 2) {
depth = 2;
}
root = new Node(this);
}
/*
* Procedure Classification begins by initializing a color
* description tree of sufficient depth to represent each
* possible input color in a leaf. However, it is impractical
* to generate a fully-formed color description tree in the
* classification phase for realistic values of cmax. If
* colors components in the input image are quantized to k-bit
* precision, so that cmax= 2k-1, the tree would need k levels
* below the root node to allow representing each possible
* input color in a leaf. This becomes prohibitive because the
* tree's total number of nodes is 1 + sum(i=1,k,8k).
*
* A complete tree would require 19,173,961 nodes for k = 8,
* cmax = 255. Therefore, to avoid building a fully populated
* tree, QUANTIZE: (1) Initializes data structures for nodes
* only as they are needed; (2) Chooses a maximum depth for
* the tree as a function of the desired number of colors in
* the output image (currently log2(colormap size)).
*
* For each pixel in the input image, classification scans
* downward from the root of the color description tree. At
* each level of the tree it identifies the single node which
* represents a cube in RGB space containing It updates the
* following data for each such node:
*
* number_pixels : Number of pixels whose color is contained
* in the RGB cube which this node represents;
*
* unique : Number of pixels whose color is not represented
* in a node at lower depth in the tree; initially, n2 = 0
* for all nodes except leaves of the tree.
*
* total_red/green/blue : Sums of the red, green, and blue
* component values for all pixels not classified at a lower
* depth. The combination of these sums and n2 will
* ultimately characterize the mean color of a set of pixels
* represented by this node.
*/
void classification() {
int pixels[][] = this.pixels;
int width = pixels.length;
int height = pixels[0].length;
// convert to indexed color
for (int x = width; x-- > 0; ) {
for (int y = height; y-- > 0; ) {
int pixel = pixels[x][y];
int red = (pixel >> 16) & 0xFF;
int green = (pixel >> 8) & 0xFF;
int blue = (pixel >> 0) & 0xFF;
// a hard limit on the number of nodes in the tree
if (nodes > MAX_NODES) {
//System.out.println("pruning");
root.pruneLevel();
--depth;
}
// walk the tree to depth, increasing the
// number_pixels count for each node
Node node = root;
for (int level = 1; level <= depth; ++level) {
int id = (((red > node.mid_red ? 1 : 0) << 0) |
((green > node.mid_green ? 1 : 0) << 1) |
((blue > node.mid_blue ? 1 : 0) << 2));
if (node.child[id] == null) {
new Node(node, id, level);
}
node = node.child[id];
node.number_pixels += SHIFT[level];
}
++node.unique;
node.total_red += red;
node.total_green += green;
node.total_blue += blue;
}
}
}
/*
* reduction repeatedly prunes the tree until the number of
* nodes with unique > 0 is less than or equal to the maximum
* number of colors allowed in the output image.
*
* When a node to be pruned has offspring, the pruning
* procedure invokes itself recursively in order to prune the
* tree from the leaves upward. The statistics of the node
* being pruned are always added to the corresponding data in
* that node's parent. This retains the pruned node's color
* characteristics for later averaging.
*/
void reduction() {
int threshold = 1;
while (colors > max_colors) {
colors = 0;
threshold = root.reduce(threshold, Integer.MAX_VALUE);
}
}
/**
* The result of a closest color search.
*/
static class Search {
int distance;
int color_number;
}
/*
* Procedure assignment generates the output image from the
* pruned tree. The output image consists of two parts: (1) A
* color map, which is an array of color descriptions (RGB
* triples) for each color present in the output image; (2) A
* pixel array, which represents each pixel as an index into
* the color map array.
*
* First, the assignment phase makes one pass over the pruned
* color description tree to establish the image's color map.
* For each node with n2 > 0, it divides Sr, Sg, and Sb by n2.
* This produces the mean color of all pixels that classify no
* lower than this node. Each of these colors becomes an entry
* in the color map.
*
* Finally, the assignment phase reclassifies each pixel in
* the pruned tree to identify the deepest node containing the
* pixel's color. The pixel's value in the pixel array becomes
* the index of this node's mean color in the color map.
*/
void assignment() {
colormap = new int[colors];
colors = 0;
root.colormap();
int pixels[][] = this.pixels;
int width = pixels.length;
int height = pixels[0].length;
Search search = new Search();
// convert to indexed color
for (int x = width; x-- > 0; ) {
for (int y = height; y-- > 0; ) {
int pixel = pixels[x][y];
int red = (pixel >> 16) & 0xFF;
int green = (pixel >> 8) & 0xFF;
int blue = (pixel >> 0) & 0xFF;
// walk the tree to find the cube containing that color
Node node = root;
for ( ; ; ) {
int id = (((red > node.mid_red ? 1 : 0) << 0) |
((green > node.mid_green ? 1 : 0) << 1) |
((blue > node.mid_blue ? 1 : 0) << 2) );
if (node.child[id] == null) {
break;
}
node = node.child[id];
}
if (QUICK) {
// if QUICK is set, just use that
// node. Strictly speaking, this isn't
// necessarily best match.
pixels[x][y] = node.color_number;
} else {
// Find the closest color.
search.distance = Integer.MAX_VALUE;
node.parent.closestColor(red, green, blue, search);
pixels[x][y] = search.color_number;
}
}
}
}
/**
* A single Node in the tree.
*/
static class Node {
Cube cube;
// parent node
Node parent;
// child nodes
Node child[];
int nchild;
// our index within our parent
int id;
// our level within the tree
int level;
// our color midpoint
int mid_red;
int mid_green;
int mid_blue;
// the pixel count for this node and all children
int number_pixels;
// the pixel count for this node
int unique;
// the sum of all pixels contained in this node
int total_red;
int total_green;
int total_blue;
// used to build the colormap
int color_number;
Node(Cube cube) {
this.cube = cube;
this.parent = this;
this.child = new Node[8];
this.id = 0;
this.level = 0;
this.number_pixels = Integer.MAX_VALUE;
this.mid_red = (MAX_RGB + 1) >> 1;
this.mid_green = (MAX_RGB + 1) >> 1;
this.mid_blue = (MAX_RGB + 1) >> 1;
}
Node(Node parent, int id, int level) {
this.cube = parent.cube;
this.parent = parent;
this.child = new Node[8];
this.id = id;
this.level = level;
// add to the cube
++cube.nodes;
if (level == cube.depth) {
++cube.colors;
}
// add to the parent
++parent.nchild;
parent.child[id] = this;
// figure out our midpoint
int bi = (1 << (MAX_TREE_DEPTH - level)) >> 1;
mid_red = parent.mid_red + ((id & 1) > 0 ? bi : -bi);
mid_green = parent.mid_green + ((id & 2) > 0 ? bi : -bi);
mid_blue = parent.mid_blue + ((id & 4) > 0 ? bi : -bi);
}
/**
* Remove this child node, and make sure our parent
* absorbs our pixel statistics.
*/
void pruneChild() {
--parent.nchild;
parent.unique += unique;
parent.total_red += total_red;
parent.total_green += total_green;
parent.total_blue += total_blue;
parent.child[id] = null;
--cube.nodes;
cube = null;
parent = null;
}
/**
* Prune the lowest layer of the tree.
*/
void pruneLevel() {
if (nchild != 0) {
for (int id = 0; id < 8; id++) {
if (child[id] != null) {
child[id].pruneLevel();
}
}
}
if (level == cube.depth) {
pruneChild();
}
}
/**
* Remove any nodes that have fewer than threshold
* pixels. Also, as long as we're walking the tree:
*
* - figure out the color with the fewest pixels
* - recalculate the total number of colors in the tree
*/
int reduce(int threshold, int next_threshold) {
if (nchild != 0) {
for (int id = 0; id < 8; id++) {
if (child[id] != null) {
next_threshold = child[id].reduce(threshold, next_threshold);
}
}
}
if (number_pixels <= threshold) {
pruneChild();
} else {
if (unique != 0) {
cube.colors++;
}
if (number_pixels < next_threshold) {
next_threshold = number_pixels;
}
}
return next_threshold;
}
/*
* colormap traverses the color cube tree and notes each
* colormap entry. A colormap entry is any node in the
* color cube tree where the number of unique colors is
* not zero.
*/
void colormap() {
if (nchild != 0) {
for (int id = 0; id < 8; id++) {
if (child[id] != null) {
child[id].colormap();
}
}
}
if (unique != 0) {
int r = ((total_red + (unique >> 1)) / unique);
int g = ((total_green + (unique >> 1)) / unique);
int b = ((total_blue + (unique >> 1)) / unique);
cube.colormap[cube.colors] = ((( 0xFF) << 24) |
((r & 0xFF) << 16) |
((g & 0xFF) << 8) |
((b & 0xFF) << 0));
color_number = cube.colors++;
}
}
/* ClosestColor traverses the color cube tree at a
* particular node and determines which colormap entry
* best represents the input color.
*/
void closestColor(int red, int green, int blue, Search search) {
if (nchild != 0) {
for (int id = 0; id < 8; id++) {
if (child[id] != null) {
child[id].closestColor(red, green, blue, search);
}
}
}
if (unique != 0) {
int color = cube.colormap[color_number];
int distance = distance(color, red, green, blue);
if (distance < search.distance) {
search.distance = distance;
search.color_number = color_number;
}
}
}
/**
* Figure out the distance between this node and som color.
*/
final static int distance(int color, int r, int g, int b) {
return (SQUARES[((color >> 16) & 0xFF) - r + MAX_RGB] +
SQUARES[((color >> 8) & 0xFF) - g + MAX_RGB] +
SQUARES[((color >> 0) & 0xFF) - b + MAX_RGB]);
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (parent == this) {
buf.append("root");
} else {
buf.append("node");
}
buf.append(' ');
buf.append(level);
buf.append(" [");
buf.append(mid_red);
buf.append(',');
buf.append(mid_green);
buf.append(',');
buf.append(mid_blue);
buf.append(']');
return new String(buf);
}
}
}
}
| 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/thridparty/miguelemosreverte/PDFUtils.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/PDFUtils.java | package thridparty.miguelemosreverte;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import de.erichseifert.vectorgraphics2d.Document;
import de.erichseifert.vectorgraphics2d.VectorGraphics2D;
import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence;
import de.erichseifert.vectorgraphics2d.pdf.PDFProcessor;
import de.erichseifert.vectorgraphics2d.util.PageSize;
import thridparty.miguelemosreverte.ImageTracer.IndexedImage;
public class PDFUtils {
public static String getPDFString(IndexedImage ii, HashMap<String, Float> options) {
// Document setup
int w = (int) (ii.width * options.get("scale")), h = (int) (ii.height * options.get("scale"));
VectorGraphics2D vg2d = new VectorGraphics2D();
// creating Z-index
TreeMap<Double, Integer[]> zindex = new TreeMap<Double, Integer[]>();
double label;
// Layer loop
for (int k = 0; k < ii.layers.size(); k++) {
// Path loop
for (int pcnt = 0; pcnt < ii.layers.get(k).size(); pcnt++) {
// Label (Z-index key) is the startpoint of the path, linearized
label = (ii.layers.get(k).get(pcnt).get(0)[2] * w) + ii.layers.get(k).get(pcnt).get(0)[1];
// Creating new list if required
if (!zindex.containsKey(label)) {
zindex.put(label, new Integer[2]);
}
// Adding layer and path number to list
zindex.get(label)[0] = new Integer(k);
zindex.get(label)[1] = new Integer(pcnt);
}// End of path loop
}// End of layer loop
// Drawing
// Z-index loop
String thisdesc = "";
for (Map.Entry<Double, Integer[]> entry : zindex.entrySet()) {
byte[] c = ii.palette[entry.getValue()[0]];
if (options.get("desc") != 0) {
thisdesc = "desc=\"l " + entry.getValue()[0] + " p " + entry.getValue()[1] + "\" ";
} else {
thisdesc = "";
}
drawPdfPath(vg2d,
thisdesc,
ii.layers.get(entry.getValue()[0]).get(entry.getValue()[1]),
new Color(c[0] + 128, c[1] + 128, c[2] + 128),
options);
}
// Write result
PDFProcessor pdfProcessor = new PDFProcessor(false);
CommandSequence commands = vg2d.getCommands();
Document doc = pdfProcessor.getDocument(commands, new PageSize(0.0, 0.0, w, h));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
doc.writeTo(bos);
} catch (IOException e) {
e.printStackTrace();
}
return bos.toString();
}
public static void drawPdfPath(VectorGraphics2D graphics, String desc, ArrayList<Double[]> segments, Color color, HashMap<String, Float> options) {
float scale = options.get("scale"), lcpr = options.get("lcpr"), qcpr = options.get("qcpr"), roundcoords = (float) Math.floor(options.get("roundcoords"));
graphics.setColor(color);
final Path2D path = new Path2D.Double();
path.moveTo(segments.get(0)[1] * scale, segments.get(0)[2] * scale);
if (roundcoords == -1) {
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if (segments.get(pcnt)[0] == 1.0) {
path.lineTo(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale);
} else {
path.quadTo(
segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale,
segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale
);
}
}
} else {
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if (segments.get(pcnt)[0] == 1.0) {
path.lineTo(
roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords),
roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords)
);
} else {
path.quadTo(
roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords),
roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords),
roundtodec((float) (segments.get(pcnt)[5] * scale), roundcoords),
roundtodec((float) (segments.get(pcnt)[6] * scale), roundcoords));
}
}
}
graphics.fill(path);
graphics.draw(path);
// Rendering control points
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if ((lcpr > 0) && (segments.get(pcnt)[0] == 1.0)) {
graphics.setColor(Color.BLACK);
graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, lcpr, lcpr));
}
if ((qcpr > 0) && (segments.get(pcnt)[0] == 2.0)) {
graphics.setColor(Color.CYAN);
graphics.setStroke(new BasicStroke((float) (qcpr * 0.2), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0F, (float[]) null, 0.0F));
graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, qcpr, qcpr));
graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale, qcpr, qcpr));
graphics.draw(new Line2D.Double(segments.get(pcnt)[1] * scale, segments.get(pcnt)[2] * scale, segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale));
graphics.draw(new Line2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale));
}// End of quadratic control points
}
}
public static float roundtodec(float val, float places) {
return (float) (Math.round(val * Math.pow(10, places)) / Math.pow(10, places));
}
}
| 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/thridparty/miguelemosreverte/VectorizingUtils.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/VectorizingUtils.java | package thridparty.miguelemosreverte;
import java.util.ArrayList;
import java.util.HashMap;
import thridparty.miguelemosreverte.ImageTracer.ImageData;
import thridparty.miguelemosreverte.ImageTracer.IndexedImage;
public class VectorizingUtils {
////////////////////////////////////////////////////////////
//
// Vectorizing functions
//
////////////////////////////////////////////////////////////
// 1. Color quantization repeated "cycles" times, based on K-means clustering
// https://en.wikipedia.org/wiki/Color_quantization https://en.wikipedia.org/wiki/K-means_clustering
public static IndexedImage colorquantization(ImageData imgd, byte[][] palette, HashMap<String, Float> options) {
// Selective Gaussian blur preprocessing
if (options.get("blurradius") > 0) {
imgd = SelectiveBlur.blur(imgd, options.get("blurradius"), options.get("blurdelta"));
}
int cycles = (int) Math.floor(options.get("colorquantcycles"));
// Creating indexed color array arr which has a boundary filled with -1 in every direction
int[][] arr = new int[imgd.height + 2][imgd.width + 2];
for (int j = 0; j < (imgd.height + 2); j++) {
arr[j][0] = -1;
arr[j][imgd.width + 1] = -1;
}
for (int i = 0; i < (imgd.width + 2); i++) {
arr[0][i] = -1;
arr[imgd.height + 1][i] = -1;
}
int idx = 0, cd, cdl, ci, c1, c2, c3, c4;
byte[][] original_palette_backup = palette;
long[][] paletteacc = new long[palette.length][5];
// Repeat clustering step "cycles" times
for (int cnt = 0; cnt < cycles; cnt++) {
// Average colors from the second iteration
if (cnt > 0) {
// averaging paletteacc for palette
//float ratio;
for (int k = 0; k < palette.length; k++) {
// averaging
if (paletteacc[k][3] > 0) {
palette[k][0] = (byte) (-128 + (paletteacc[k][0] / paletteacc[k][4]));
palette[k][1] = (byte) (-128 + (paletteacc[k][1] / paletteacc[k][4]));
palette[k][2] = (byte) (-128 + (paletteacc[k][2] / paletteacc[k][4]));
palette[k][3] = (byte) (-128 + (paletteacc[k][3] / paletteacc[k][4]));
}
//ratio = (float)( (double)(paletteacc[k][4]) / (double)(imgd.width*imgd.height) );
/*// Randomizing a color, if there are too few pixels and there will be a new cycle
if( (ratio<minratio) && (cnt<(cycles-1)) ){
palette[k][0] = (byte) (-128+Math.floor(Math.random()*255));
palette[k][1] = (byte) (-128+Math.floor(Math.random()*255));
palette[k][2] = (byte) (-128+Math.floor(Math.random()*255));
palette[k][3] = (byte) (-128+Math.floor(Math.random()*255));
}*/
}// End of palette loop
}// End of Average colors from the second iteration
// Reseting palette accumulator for averaging
for (int i = 0; i < palette.length; i++) {
paletteacc[i][0] = 0;
paletteacc[i][1] = 0;
paletteacc[i][2] = 0;
paletteacc[i][3] = 0;
paletteacc[i][4] = 0;
}
// loop through all pixels
for (int j = 0; j < imgd.height; j++) {
for (int i = 0; i < imgd.width; i++) {
idx = ((j * imgd.width) + i) * 4;
// find closest color from original_palette_backup by measuring (rectilinear)
// color distance between this pixel and all palette colors
cdl = 256 + 256 + 256 + 256;
ci = 0;
for (int k = 0; k < original_palette_backup.length; k++) {
// In my experience, https://en.wikipedia.org/wiki/Rectilinear_distance works better than https://en.wikipedia.org/wiki/Euclidean_distance
c1 = Math.abs(original_palette_backup[k][0] - imgd.data[idx]);
c2 = Math.abs(original_palette_backup[k][1] - imgd.data[idx + 1]);
c3 = Math.abs(original_palette_backup[k][2] - imgd.data[idx + 2]);
c4 = Math.abs(original_palette_backup[k][3] - imgd.data[idx + 3]);
cd = c1 + c2 + c3 + (c4 * 4); // weighted alpha seems to help images with transparency
// Remember this color if this is the closest yet
if (cd < cdl) {
cdl = cd;
ci = k;
}
}// End of palette loop
// add to palettacc
paletteacc[ci][0] += 128 + imgd.data[idx];
paletteacc[ci][1] += 128 + imgd.data[idx + 1];
paletteacc[ci][2] += 128 + imgd.data[idx + 2];
paletteacc[ci][3] += 128 + imgd.data[idx + 3];
paletteacc[ci][4]++;
arr[j + 1][i + 1] = ci;
}// End of i loop
}// End of j loop
}// End of Repeat clustering step "cycles" times
return new IndexedImage(arr, original_palette_backup);
}// End of colorquantization
// 2. Layer separation and edge detection
// Edge node types ( ▓:light or 1; ░:dark or 0 )
// 12 ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓
// 48 ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
public static int[][][] layering(IndexedImage ii) {
// Creating layers for each indexed color in arr
int val = 0, aw = ii.array[0].length, ah = ii.array.length, n1, n2, n3, n4, n5, n6, n7, n8;
int[][][] layers = new int[ii.palette.length][ah][aw];
// Looping through all pixels and calculating edge node type
for (int j = 1; j < (ah - 1); j++) {
for (int i = 1; i < (aw - 1); i++) {
// This pixel's indexed color
val = ii.array[j][i];
// Are neighbor pixel colors the same?
n1 = ii.array[j - 1][i - 1] == val ? 1 : 0;
n2 = ii.array[j - 1][i] == val ? 1 : 0;
n3 = ii.array[j - 1][i + 1] == val ? 1 : 0;
n4 = ii.array[j][i - 1] == val ? 1 : 0;
n5 = ii.array[j][i + 1] == val ? 1 : 0;
n6 = ii.array[j + 1][i - 1] == val ? 1 : 0;
n7 = ii.array[j + 1][i] == val ? 1 : 0;
n8 = ii.array[j + 1][i + 1] == val ? 1 : 0;
// this pixel"s type and looking back on previous pixels
layers[val][j + 1][i + 1] = 1 + (n5 * 2) + (n8 * 4) + (n7 * 8);
if (n4 == 0) {
layers[val][j + 1][i] = 0 + 2 + (n7 * 4) + (n6 * 8);
}
if (n2 == 0) {
layers[val][j][i + 1] = 0 + (n3 * 2) + (n5 * 4) + 8;
}
if (n1 == 0) {
layers[val][j][i] = 0 + (n2 * 2) + 4 + (n4 * 8);
}
}// End of i loop
}// End of j loop
return layers;
}// End of layering()
// Lookup tables for pathscan
static byte[] pathscan_dir_lookup = {0, 0, 3, 0, 1, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0};
static boolean[] pathscan_holepath_lookup = {false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false};
// pathscan_combined_lookup[ arr[py][px] ][ dir ] = [nextarrpypx, nextdir, deltapx, deltapy];
static byte[][][] pathscan_combined_lookup = {
{{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},// arr[py][px]==0 is invalid
{{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}},
{{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}},
{{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}},
{{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}},
{{13, 3, 0, 1}, {13, 2, -1, 0}, {7, 1, 0, -1}, {7, 0, 1, 0}},
{{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}},
{{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},
{{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},
{{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}},
{{11, 1, 0, -1}, {14, 0, 1, 0}, {14, 3, 0, 1}, {11, 2, -1, 0}},
{{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}},
{{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}},
{{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}},
{{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}},
{{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}// arr[py][px]==15 is invalid
};
// 3. Walking through an edge node array, discarding edge node types 0 and 15 and creating paths from the rest.
// Walk directions (dir): 0 > ; 1 ^ ; 2 < ; 3 v
// Edge node types ( ▓:light or 1; ░:dark or 0 )
// ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓
// ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
public static ArrayList<ArrayList<Integer[]>> pathscan(int[][] arr, float pathomit) {
ArrayList<ArrayList<Integer[]>> paths = new ArrayList<ArrayList<Integer[]>>();
ArrayList<Integer[]> thispath;
int px = 0, py = 0, w = arr[0].length, h = arr.length, dir = 0;
boolean pathfinished = true, holepath = false;
byte[] lookuprow;
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
if ((arr[j][i] != 0) && (arr[j][i] != 15)) {
// Init
px = i;
py = j;
paths.add(new ArrayList<Integer[]>());
thispath = paths.get(paths.size() - 1);
pathfinished = false;
// fill paths will be drawn, but hole paths are also required to remove unnecessary edge nodes
dir = pathscan_dir_lookup[arr[py][px]];
holepath = pathscan_holepath_lookup[arr[py][px]];
// Path points loop
while (!pathfinished) {
// New path point
thispath.add(new Integer[3]);
thispath.get(thispath.size() - 1)[0] = px - 1;
thispath.get(thispath.size() - 1)[1] = py - 1;
thispath.get(thispath.size() - 1)[2] = arr[py][px];
// Next: look up the replacement, direction and coordinate changes = clear this cell, turn if required, walk forward
lookuprow = pathscan_combined_lookup[arr[py][px]][dir];
arr[py][px] = lookuprow[0];
dir = lookuprow[1];
px += lookuprow[2];
py += lookuprow[3];
// Close path
if (((px - 1) == thispath.get(0)[0]) && ((py - 1) == thispath.get(0)[1])) {
pathfinished = true;
// Discarding 'hole' type paths and paths shorter than pathomit
if ((holepath) || (thispath.size() < pathomit)) {
paths.remove(thispath);
}
}
}// End of Path points loop
}// End of Follow path
}// End of i loop
}// End of j loop
return paths;
}// End of pathscan()
// 3. Batch pathscan
public static ArrayList<ArrayList<ArrayList<Integer[]>>> batchpathscan(int[][][] layers, float pathomit) {
ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths = new ArrayList<ArrayList<ArrayList<Integer[]>>>();
for (int[][] layer : layers) {
bpaths.add(pathscan(layer, pathomit));
}
return bpaths;
}
// 4. interpolating between path points for nodes with 8 directions ( East, SouthEast, S, SW, W, NW, N, NE )
public static ArrayList<ArrayList<Double[]>> internodes(ArrayList<ArrayList<Integer[]>> paths) {
ArrayList<ArrayList<Double[]>> ins = new ArrayList<ArrayList<Double[]>>();
ArrayList<Double[]> thisinp;
Double[] thispoint, nextpoint = new Double[2];
Integer[] pp1, pp2, pp3;
int palen = 0, nextidx = 0, nextidx2 = 0;
// paths loop
for (int pacnt = 0; pacnt < paths.size(); pacnt++) {
ins.add(new ArrayList<Double[]>());
thisinp = ins.get(ins.size() - 1);
palen = paths.get(pacnt).size();
// pathpoints loop
for (int pcnt = 0; pcnt < palen; pcnt++) {
// interpolate between two path points
nextidx = (pcnt + 1) % palen;
nextidx2 = (pcnt + 2) % palen;
thisinp.add(new Double[3]);
thispoint = thisinp.get(thisinp.size() - 1);
pp1 = paths.get(pacnt).get(pcnt);
pp2 = paths.get(pacnt).get(nextidx);
pp3 = paths.get(pacnt).get(nextidx2);
thispoint[0] = (pp1[0] + pp2[0]) / 2.0;
thispoint[1] = (pp1[1] + pp2[1]) / 2.0;
nextpoint[0] = (pp2[0] + pp3[0]) / 2.0;
nextpoint[1] = (pp2[1] + pp3[1]) / 2.0;
// line segment direction to the next point
if (thispoint[0] < nextpoint[0]) {
if (thispoint[1] < nextpoint[1]) {
thispoint[2] = 1.0;
}// SouthEast
else if (thispoint[1] > nextpoint[1]) {
thispoint[2] = 7.0;
}// NE
else {
thispoint[2] = 0.0;
} // E
} else if (thispoint[0] > nextpoint[0]) {
if (thispoint[1] < nextpoint[1]) {
thispoint[2] = 3.0;
}// SW
else if (thispoint[1] > nextpoint[1]) {
thispoint[2] = 5.0;
}// NW
else {
thispoint[2] = 4.0;
}// W
} else {
if (thispoint[1] < nextpoint[1]) {
thispoint[2] = 2.0;
}// S
else if (thispoint[1] > nextpoint[1]) {
thispoint[2] = 6.0;
}// N
else {
thispoint[2] = 8.0;
}// center, this should not happen
}
}// End of pathpoints loop
}// End of paths loop
return ins;
}// End of internodes()
// 4. Batch interpollation
public static ArrayList<ArrayList<ArrayList<Double[]>>> batchinternodes(ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths) {
ArrayList<ArrayList<ArrayList<Double[]>>> binternodes = new ArrayList<ArrayList<ArrayList<Double[]>>>();
for (int k = 0; k < bpaths.size(); k++) {
binternodes.add(internodes(bpaths.get(k)));
}
return binternodes;
}
// 5. tracepath() : recursively trying to fit straight and quadratic spline segments on the 8 direction internode path
// 5.1. Find sequences of points with only 2 segment types
// 5.2. Fit a straight line on the sequence
// 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error
// 5.4. Fit a quadratic spline through errorpoint (project this to get controlpoint), then measure errors on every point in the sequence
// 5.5. If the spline fails (an error>qtreshold), find the point with the biggest error, set splitpoint = (fitting point + errorpoint)/2
// 5.6. Split sequence and recursively apply 5.2. - 5.7. to startpoint-splitpoint and splitpoint-endpoint sequences
// 5.7. TODO? If splitpoint-endpoint is a spline, try to add new points from the next sequence
// This returns an SVG Path segment as a double[7] where
// segment[0] ==1.0 linear ==2.0 quadratic interpolation
// segment[1] , segment[2] : x1 , y1
// segment[3] , segment[4] : x2 , y2 ; middle point of Q curve, endpoint of L line
// segment[5] , segment[6] : x3 , y3 for Q curve, should be 0.0 , 0.0 for L line
//
// path type is discarded, no check for path.size < 3 , which should not happen
public static ArrayList<Double[]> tracepath(ArrayList<Double[]> path, float ltreshold, float qtreshold) {
int pcnt = 0, seqend = 0;
double segtype1, segtype2;
ArrayList<Double[]> smp = new ArrayList<Double[]>();
//Double [] thissegment;
int pathlength = path.size();
while (pcnt < pathlength) {
// 5.1. Find sequences of points with only 2 segment types
segtype1 = path.get(pcnt)[2];
segtype2 = -1;
seqend = pcnt + 1;
while (((path.get(seqend)[2] == segtype1) || (path.get(seqend)[2] == segtype2) || (segtype2 == -1))
&& (seqend < (pathlength - 1))) {
if ((path.get(seqend)[2] != segtype1) && (segtype2 == -1)) {
segtype2 = path.get(seqend)[2];
}
seqend++;
}
if (seqend == (pathlength - 1)) {
seqend = 0;
}
// 5.2. - 5.6. Split sequence and recursively apply 5.2. - 5.6. to startpoint-splitpoint and splitpoint-endpoint sequences
smp.addAll(fitseq(path, ltreshold, qtreshold, pcnt, seqend));
// 5.7. TODO? If splitpoint-endpoint is a spline, try to add new points from the next sequence
// forward pcnt;
if (seqend > 0) {
pcnt = seqend;
} else {
pcnt = pathlength;
}
}// End of pcnt loop
return smp;
}// End of tracepath()
// 5.2. - 5.6. recursively fitting a straight or quadratic line segment on this sequence of path nodes,
// called from tracepath()
public static ArrayList<Double[]> fitseq(ArrayList<Double[]> path, float ltreshold, float qtreshold, int seqstart, int seqend) {
ArrayList<Double[]> segment = new ArrayList<Double[]>();
Double[] thissegment;
int pathlength = path.size();
// return if invalid seqend
if ((seqend > pathlength) || (seqend < 0)) {
return segment;
}
int errorpoint = seqstart;
boolean curvepass = true;
double px, py, dist2, errorval = 0;
double tl = (seqend - seqstart);
if (tl < 0) {
tl += pathlength;
}
double vx = (path.get(seqend)[0] - path.get(seqstart)[0]) / tl,
vy = (path.get(seqend)[1] - path.get(seqstart)[1]) / tl;
// 5.2. Fit a straight line on the sequence
int pcnt = (seqstart + 1) % pathlength;
double pl;
while (pcnt != seqend) {
pl = pcnt - seqstart;
if (pl < 0) {
pl += pathlength;
}
px = path.get(seqstart)[0] + (vx * pl);
py = path.get(seqstart)[1] + (vy * pl);
dist2 = ((path.get(pcnt)[0] - px) * (path.get(pcnt)[0] - px)) + ((path.get(pcnt)[1] - py) * (path.get(pcnt)[1] - py));
if (dist2 > ltreshold) {
curvepass = false;
}
if (dist2 > errorval) {
errorpoint = pcnt;
errorval = dist2;
}
pcnt = (pcnt + 1) % pathlength;
}
// return straight line if fits
if (curvepass) {
segment.add(new Double[7]);
thissegment = segment.get(segment.size() - 1);
thissegment[0] = 1.0;
thissegment[1] = path.get(seqstart)[0];
thissegment[2] = path.get(seqstart)[1];
thissegment[3] = path.get(seqend)[0];
thissegment[4] = path.get(seqend)[1];
thissegment[5] = 0.0;
thissegment[6] = 0.0;
return segment;
}
// 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error
int fitpoint = errorpoint;
curvepass = true;
errorval = 0;
// 5.4. Fit a quadratic spline through this point, measure errors on every point in the sequence
// helpers and projecting to get control point
double t = (fitpoint - seqstart) / tl, t1 = (1.0 - t) * (1.0 - t), t2 = 2.0 * (1.0 - t) * t, t3 = t * t;
double cpx = (((t1 * path.get(seqstart)[0]) + (t3 * path.get(seqend)[0])) - path.get(fitpoint)[0]) / -t2,
cpy = (((t1 * path.get(seqstart)[1]) + (t3 * path.get(seqend)[1])) - path.get(fitpoint)[1]) / -t2;
// Check every point
pcnt = seqstart + 1;
while (pcnt != seqend) {
t = (pcnt - seqstart) / tl;
t1 = (1.0 - t) * (1.0 - t);
t2 = 2.0 * (1.0 - t) * t;
t3 = t * t;
px = (t1 * path.get(seqstart)[0]) + (t2 * cpx) + (t3 * path.get(seqend)[0]);
py = (t1 * path.get(seqstart)[1]) + (t2 * cpy) + (t3 * path.get(seqend)[1]);
dist2 = ((path.get(pcnt)[0] - px) * (path.get(pcnt)[0] - px)) + ((path.get(pcnt)[1] - py) * (path.get(pcnt)[1] - py));
if (dist2 > qtreshold) {
curvepass = false;
}
if (dist2 > errorval) {
errorpoint = pcnt;
errorval = dist2;
}
pcnt = (pcnt + 1) % pathlength;
}
// return spline if fits
if (curvepass) {
segment.add(new Double[7]);
thissegment = segment.get(segment.size() - 1);
thissegment[0] = 2.0;
thissegment[1] = path.get(seqstart)[0];
thissegment[2] = path.get(seqstart)[1];
thissegment[3] = cpx;
thissegment[4] = cpy;
thissegment[5] = path.get(seqend)[0];
thissegment[6] = path.get(seqend)[1];
return segment;
}
// 5.5. If the spline fails (an error>qtreshold), find the point with the biggest error,
// set splitpoint = (fitting point + errorpoint)/2
int splitpoint = (fitpoint + errorpoint) / 2;
// 5.6. Split sequence and recursively apply 5.2. - 5.6. to startpoint-splitpoint and splitpoint-endpoint sequences
segment = fitseq(path, ltreshold, qtreshold, seqstart, splitpoint);
segment.addAll(fitseq(path, ltreshold, qtreshold, splitpoint, seqend));
return segment;
}// End of fitseq()
// 5. Batch tracing paths
public static ArrayList<ArrayList<Double[]>> batchtracepaths(ArrayList<ArrayList<Double[]>> internodepaths, float ltres, float qtres) {
ArrayList<ArrayList<Double[]>> btracedpaths = new ArrayList<ArrayList<Double[]>>();
for (int k = 0; k < internodepaths.size(); k++) {
btracedpaths.add(tracepath(internodepaths.get(k), ltres, qtres));
}
return btracedpaths;
}
// 5. Batch tracing layers
public static ArrayList<ArrayList<ArrayList<Double[]>>> batchtracelayers(ArrayList<ArrayList<ArrayList<Double[]>>> binternodes, float ltres, float qtres) {
ArrayList<ArrayList<ArrayList<Double[]>>> btbis = new ArrayList<ArrayList<ArrayList<Double[]>>>();
for (int k = 0; k < binternodes.size(); k++) {
btbis.add(batchtracepaths(binternodes.get(k), ltres, qtres));
}
return btbis;
}
}
| 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/thridparty/miguelemosreverte/ImageTracer.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/ImageTracer.java | // https://github.com/miguelemosreverte/imagetracerjava
package thridparty.miguelemosreverte;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.imageio.ImageIO;
public class ImageTracer {
public static String versionnumber = "1.1.3";
private static int[] rawdata;
public ImageTracer() {
}
public static void main(String[] args) {
try {
if (args.length < 1) {
System.out.println("ERROR: there's no input filename. Basic usage: \r\n\r\njava -jar ImageTracer.jar <filename>"
+ "\r\n\r\nor\r\n\r\njava -jar ImageTracer.jar help");
//System.out.println("Starting anyway with default value for testing purposes.");
//saveString("output.svg",imageToSVG("input.jpg",new HashMap<String,Float>()));
} else if (arraycontains(args, "help") > -1) {
System.out.println("Example usage:\r\n\r\njava -jar ImageTracer.jar <filename> outfilename test.svg "
+ "ltres 1 qtres 1 pathomit 1 numberofcolors 128 colorquantcycles 15 "
+ "scale 1 roundcoords 1 lcpr 0 qcpr 0 desc 1 viewbox 0 blurradius 0 blurdelta 20 \r\n"
+ "\r\nOnly <filename> is mandatory, if some of the other optional parameters are missing, they will be set to these defaults. "
+ "\r\nWarning: if outfilename is not specified, then <filename>.svg will be overwritten."
+ "\r\nSee https://github.com/jankovicsandras/imagetracerjava for details. \r\nThis is version " + versionnumber);
} else {
// Parameter parsing
String outfilename = args[0];
HashMap<String, Float> options = new HashMap<String, Float>();
String[] parameternames = {"ltres", "qtres", "pathomit", "numberofcolors", "colorquantcycles", "format", "scale", "roundcoords", "lcpr", "qcpr", "desc", "viewbox", "outfilename", "blurammount"};
int j = -1;
float f = -1;
for (String parametername : parameternames) {
j = arraycontains(args, parametername);
if (j > -1) {
if (parametername == "outfilename") {
if (j < (args.length - 1)) {
outfilename = args[j + 1];
}
} else {
f = parsenext(args, j);
if (f > -1) {
options.put(parametername, new Float(f));
}
}
}
}// End of parameternames loop
options = checkoptions(options);
// Loading image, tracing, rendering, saving output file
if (options.get("format") == 0) {
saveString(outfilename + ".svg", imageToSVG(args[0], options));
} else if (options.get("format") == 1) {
saveString(outfilename + ".pdf", imageToPDF(args[0], options));
} else {
System.out.println("ERROR: Incorrect output format. Options: 0 - SVG, 1 - PDF");
}
}// End of parameter parsing and processing
} catch (Exception e) {
e.printStackTrace();
}
}// End of main()
public static int arraycontains(String[] arr, String str) {
for (int j = 0; j < arr.length; j++) {
if (arr[j].toLowerCase().equals(str)) {
return j;
}
}
return -1;
}
public static float parsenext(String[] arr, int i) {
if (i < (arr.length - 1)) {
try {
return Float.parseFloat(arr[i + 1]);
} catch (Exception e) {
}
}
return -1;
}
// Container for the color-indexed image before and tracedata after vectorizing
public static class IndexedImage {
public int width, height;
public int[][] array; // array[x][y] of palette colors
public byte[][] palette;// array[palettelength][4] RGBA color palette
public ArrayList<ArrayList<ArrayList<Double[]>>> layers;// tracedata
public IndexedImage(int[][] marray, byte[][] mpalette) {
array = marray;
palette = mpalette;
width = marray[0].length - 2;
height = marray.length - 2;// Color quantization adds +2 to the original width and height
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/ImageData
public static class ImageData {
public int width, height;
public byte[] data; // raw byte data: R G B A R G B A ...
public ImageData(int mwidth, int mheight, byte[] mdata) {
width = mwidth;
height = mheight;
data = mdata;
}
}
// Saving a String as a file
public static void saveString(String filename, String str) throws Exception {
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str);
bw.close();
}
// Loading a file to ImageData, ARGB byte order
public static ImageData loadImageData(String filename, HashMap<String, Float> options)
throws Exception {
BufferedImage image = ImageIO.read(new File(filename));
return loadImageData(image);
}
public static ImageData loadImageData(BufferedImage image) throws Exception {
int width = image.getWidth();
int height = image.getHeight();
rawdata = image.getRGB(0, 0, width, height, null, 0, width);
byte[] data = new byte[rawdata.length * 4];
for (int i = 0; i < rawdata.length; i++) {
data[(i * 4) + 3] = bytetrans((byte) (rawdata[i] >>> 24));
data[i * 4] = bytetrans((byte) (rawdata[i] >>> 16));
data[(i * 4) + 1] = bytetrans((byte) (rawdata[i] >>> 8));
data[(i * 4) + 2] = bytetrans((byte) (rawdata[i]));
}
return new ImageData(width, height, data);
}
// The bitshift method in loadImageData creates signed bytes where -1 -> 255 unsigned ; -128 -> 128 unsigned ;
// 127 -> 127 unsigned ; 0 -> 0 unsigned ; These will be converted to -128 (representing 0 unsigned) ...
// 127 (representing 255 unsigned) and tosvgcolorstr will add +128 to create RGB values 0..255
public static byte bytetrans(byte b) {
if (b < 0) {
return (byte) (b + 128);
} else {
return (byte) (b - 128);
}
}
public static byte[][] getPalette(BufferedImage image, HashMap<String, Float> options) {
int numberofcolors = options.get("numberofcolors").intValue();
int[][] pixels = new int[image.getWidth()][image.getHeight()];
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
pixels[i][j] = image.getRGB(i, j);
}
}
int[] palette = Quantize.quantizeImage(pixels, numberofcolors);
byte[][] bytepalette = new byte[numberofcolors][4];
for (int i = 0; i < palette.length; i++) {
Color c = new Color(palette[i]);
bytepalette[i][0] = (byte) c.getRed();
bytepalette[i][1] = (byte) c.getGreen();
bytepalette[i][2] = (byte) c.getBlue();
bytepalette[i][3] = 0;
}
return bytepalette;
}
////////////////////////////////////////////////////////////
//
// User friendly functions
//
////////////////////////////////////////////////////////////
// Loading an image from a file, tracing when loaded, then returning the SVG String
public static String imageToSVG(String filename, HashMap<String, Float> options)
throws Exception {
System.out.println(options.toString());
ImageData imgd = loadImageData(filename, options);
return imagedataToSVG(imgd, options, getPalette(ImageIO.read(new File(filename)), options));
}// End of imageToSVG()
// Tracing ImageData, then returning the SVG String
public static String imagedataToSVG(ImageData imgd, HashMap<String, Float> options, byte[][] palette) {
IndexedImage ii = imagedataToTracedata(imgd, options, palette);
return SVGUtils.getsvgstring(ii, options);
}// End of imagedataToSVG()
// Loading an image from a file, tracing when loaded, then returning PDF String
public static String imageToPDF(String filename, HashMap<String, Float> options)
throws Exception {
ImageData imgd = loadImageData(filename, options);
IndexedImage ii = imagedataToTracedata(imgd, options, getPalette(ImageIO.read(new File(filename)), options));
return PDFUtils.getPDFString(ii, options);
}// End of imagedataToSVG()
// Loading an image from a file, tracing when loaded, then returning IndexedImage with tracedata in layers
public IndexedImage imageToTracedata(String filename, HashMap<String, Float> options, byte[][] palette)
throws Exception {
ImageData imgd = loadImageData(filename, options);
return imagedataToTracedata(imgd, options, palette);
}// End of imageToTracedata()
public IndexedImage imageToTracedata(BufferedImage image, HashMap<String, Float> options, byte[][] palette)
throws Exception {
ImageData imgd = loadImageData(image);
return imagedataToTracedata(imgd, options, palette);
}// End of imageToTracedata()
// Tracing ImageData, then returning IndexedImage with tracedata in layers
public static IndexedImage imagedataToTracedata(ImageData imgd, HashMap<String, Float> options, byte[][] palette) {
// 1. Color quantization
IndexedImage ii = VectorizingUtils.colorquantization(imgd, palette, options);
// 2. Layer separation and edge detection
int[][][] rawlayers = VectorizingUtils.layering(ii);
// 3. Batch pathscan
ArrayList<ArrayList<ArrayList<Integer[]>>> bps = VectorizingUtils.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit"))));
// 4. Batch interpollation
ArrayList<ArrayList<ArrayList<Double[]>>> bis = VectorizingUtils.batchinternodes(bps);
// 5. Batch tracing
ii.layers = VectorizingUtils.batchtracelayers(bis, options.get("ltres"), options.get("qtres"));
return ii;
}// End of imagedataToTracedata()
// creating options object, setting defaults for missing values
public static HashMap<String, Float> checkoptions(HashMap<String, Float> options) {
if (options == null) {
options = new HashMap<String, Float>();
}
// Tracing
if (!options.containsKey("ltres")) {
options.put("ltres", 10f);
}
if (!options.containsKey("qtres")) {
options.put("qtres", 10f);
}
if (!options.containsKey("pathomit")) {
options.put("pathomit", 1f);
}
// Color quantization
if (!options.containsKey("numberofcolors")) {
options.put("numberofcolors", 128f);
}
if (!options.containsKey("colorquantcycles")) {
options.put("colorquantcycles", 15f);
}
// Output rendering
if (!options.containsKey("format")) {
options.put("format", 0f);
}
if (!options.containsKey("scale")) {
options.put("scale", 1f);
}
if (!options.containsKey("roundcoords")) {
options.put("roundcoords", 1f);
}
if (!options.containsKey("lcpr")) {
options.put("lcpr", 0f);
}
if (!options.containsKey("qcpr")) {
options.put("qcpr", 0f);
}
if (!options.containsKey("desc")) {
options.put("desc", 1f);
}
if (!options.containsKey("viewbox")) {
options.put("viewbox", 0f);
}
// Blur
if (!options.containsKey("blurradius")) {
options.put("blurradius", 5f);
}
if (!options.containsKey("blurdelta")) {
options.put("blurdelta", 50f);
}
return options;
}// End of checkoptions()
}// End of ImageTracer class
| 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/thridparty/miguelemosreverte/SelectiveBlur.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/SelectiveBlur.java | package thridparty.miguelemosreverte;
import thridparty.miguelemosreverte.ImageTracer.ImageData;
public class SelectiveBlur {
// Gaussian kernels for blur
static double[][] gks = {{0.27901, 0.44198, 0.27901}, {0.135336, 0.228569, 0.272192, 0.228569, 0.135336}, {0.086776, 0.136394, 0.178908, 0.195843, 0.178908, 0.136394, 0.086776},
{0.063327, 0.093095, 0.122589, 0.144599, 0.152781, 0.144599, 0.122589, 0.093095, 0.063327}, {0.049692, 0.069304, 0.089767, 0.107988, 0.120651, 0.125194, 0.120651, 0.107988, 0.089767, 0.069304, 0.049692}};
// Selective Gaussian blur for preprocessing
static ImageData blur(ImageData imgd, float rad, float del) {
int i, j, k, d, idx;
double racc, gacc, bacc, aacc, wacc;
ImageData imgd2 = new ImageData(imgd.width, imgd.height, new byte[imgd.width * imgd.height * 4]);
// radius and delta limits, this kernel
int radius = (int) Math.floor(rad);
if (radius < 1) {
return imgd;
}
if (radius > 5) {
radius = 5;
}
int delta = (int) Math.abs(del);
if (delta > 1024) {
delta = 1024;
}
double[] thisgk = gks[radius - 1];
// loop through all pixels, horizontal blur
for (j = 0; j < imgd.height; j++) {
for (i = 0; i < imgd.width; i++) {
racc = 0;
gacc = 0;
bacc = 0;
aacc = 0;
wacc = 0;
// gauss kernel loop
for (k = -radius; k < (radius + 1); k++) {
// add weighted color values
if (((i + k) > 0) && ((i + k) < imgd.width)) {
idx = ((j * imgd.width) + i + k) * 4;
racc += imgd.data[idx] * thisgk[k + radius];
gacc += imgd.data[idx + 1] * thisgk[k + radius];
bacc += imgd.data[idx + 2] * thisgk[k + radius];
aacc += imgd.data[idx + 3] * thisgk[k + radius];
wacc += thisgk[k + radius];
}
}
// The new pixel
idx = ((j * imgd.width) + i) * 4;
imgd2.data[idx] = (byte) Math.floor(racc / wacc);
imgd2.data[idx + 1] = (byte) Math.floor(gacc / wacc);
imgd2.data[idx + 2] = (byte) Math.floor(bacc / wacc);
imgd2.data[idx + 3] = (byte) Math.floor(aacc / wacc);
}// End of width loop
}// End of horizontal blur
// copying the half blurred imgd2
byte[] himgd = imgd2.data.clone();
// loop through all pixels, vertical blur
for (j = 0; j < imgd.height; j++) {
for (i = 0; i < imgd.width; i++) {
racc = 0;
gacc = 0;
bacc = 0;
aacc = 0;
wacc = 0;
// gauss kernel loop
for (k = -radius; k < (radius + 1); k++) {
// add weighted color values
if (((j + k) > 0) && ((j + k) < imgd.height)) {
idx = (((j + k) * imgd.width) + i) * 4;
racc += himgd[idx] * thisgk[k + radius];
gacc += himgd[idx + 1] * thisgk[k + radius];
bacc += himgd[idx + 2] * thisgk[k + radius];
aacc += himgd[idx + 3] * thisgk[k + radius];
wacc += thisgk[k + radius];
}
}
// The new pixel
idx = ((j * imgd.width) + i) * 4;
imgd2.data[idx] = (byte) Math.floor(racc / wacc);
imgd2.data[idx + 1] = (byte) Math.floor(gacc / wacc);
imgd2.data[idx + 2] = (byte) Math.floor(bacc / wacc);
imgd2.data[idx + 3] = (byte) Math.floor(aacc / wacc);
}// End of width loop
}// End of vertical blur
// Selective blur: loop through all pixels
for (j = 0; j < imgd.height; j++) {
for (i = 0; i < imgd.width; i++) {
idx = ((j * imgd.width) + i) * 4;
// d is the difference between the blurred and the original pixel
d = Math.abs(imgd2.data[idx] - imgd.data[idx]) + Math.abs(imgd2.data[idx + 1] - imgd.data[idx + 1])
+ Math.abs(imgd2.data[idx + 2] - imgd.data[idx + 2]) + Math.abs(imgd2.data[idx + 3] - imgd.data[idx + 3]);
// selective blur: if d>delta, put the original pixel back
if (d > delta) {
imgd2.data[idx] = imgd.data[idx];
imgd2.data[idx + 1] = imgd.data[idx + 1];
imgd2.data[idx + 2] = imgd.data[idx + 2];
imgd2.data[idx + 3] = imgd.data[idx + 3];
}
}
}// End of Selective blur
return imgd2;
}// End of blur()
}
| 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/thridparty/miguelemosreverte/SVGUtils.java | released/MyBox/src/main/java/thridparty/miguelemosreverte/SVGUtils.java | package thridparty.miguelemosreverte;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import thridparty.miguelemosreverte.ImageTracer.IndexedImage;
public class SVGUtils {
////////////////////////////////////////////////////////////
//
// SVG Drawing functions
//
////////////////////////////////////////////////////////////
public static float roundtodec(float val, float places) {
return (float) (Math.round(val * Math.pow(10, places)) / Math.pow(10, places));
}
// Getting SVG path element string from a traced path
public static void svgpathstring(StringBuilder sb, String desc, ArrayList<Double[]> segments, String colorstr, HashMap<String, Float> options) {
float scale = options.get("scale"), lcpr = options.get("lcpr"), qcpr = options.get("qcpr"), roundcoords = (float) Math.floor(options.get("roundcoords"));
// Path
sb.append("<path ").append(desc).append(colorstr).append("d=\"").append("M ").append(segments.get(0)[1] * scale).append(" ").append(segments.get(0)[2] * scale).append(" ");
if (roundcoords == -1) {
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if (segments.get(pcnt)[0] == 1.0) {
sb.append("L ").append(segments.get(pcnt)[3] * scale).append(" ").append(segments.get(pcnt)[4] * scale).append(" ");
} else {
sb.append("Q ").append(segments.get(pcnt)[3] * scale).append(" ").append(segments.get(pcnt)[4] * scale).append(" ").append(segments.get(pcnt)[5] * scale).append(" ").append(segments.get(pcnt)[6] * scale).append(" ");
}
}
} else {
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if (segments.get(pcnt)[0] == 1.0) {
sb.append("L ").append(roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords)).append(" ")
.append(roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords)).append(" ");
} else {
sb.append("Q ").append(roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords)).append(" ")
.append(roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords)).append(" ")
.append(roundtodec((float) (segments.get(pcnt)[5] * scale), roundcoords)).append(" ")
.append(roundtodec((float) (segments.get(pcnt)[6] * scale), roundcoords)).append(" ");
}
}
}// End of roundcoords check
sb.append("Z\" />");
// Rendering control points
for (int pcnt = 0; pcnt < segments.size(); pcnt++) {
if ((lcpr > 0) && (segments.get(pcnt)[0] == 1.0)) {
sb.append("<circle cx=\"").append(segments.get(pcnt)[3] * scale).append("\" cy=\"").append(segments.get(pcnt)[4] * scale).append("\" r=\"").append(lcpr).append("\" fill=\"white\" stroke-width=\"").append(lcpr * 0.2).append("\" stroke=\"black\" />");
}
if ((qcpr > 0) && (segments.get(pcnt)[0] == 2.0)) {
sb.append("<circle cx=\"").append(segments.get(pcnt)[3] * scale).append("\" cy=\"").append(segments.get(pcnt)[4] * scale).append("\" r=\"").append(qcpr).append("\" fill=\"cyan\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"black\" />");
sb.append("<circle cx=\"").append(segments.get(pcnt)[5] * scale).append("\" cy=\"").append(segments.get(pcnt)[6] * scale).append("\" r=\"").append(qcpr).append("\" fill=\"white\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"black\" />");
sb.append("<line x1=\"").append(segments.get(pcnt)[1] * scale).append("\" y1=\"").append(segments.get(pcnt)[2] * scale).append("\" x2=\"").append(segments.get(pcnt)[3] * scale).append("\" y2=\"").append(segments.get(pcnt)[4] * scale).append("\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"cyan\" />");
sb.append("<line x1=\"").append(segments.get(pcnt)[3] * scale).append("\" y1=\"").append(segments.get(pcnt)[4] * scale).append("\" x2=\"").append(segments.get(pcnt)[5] * scale).append("\" y2=\"").append(segments.get(pcnt)[6] * scale).append("\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"cyan\" />");
}// End of quadratic control points
}
}// End of svgpathstring()
// Converting tracedata to an SVG string, paths are drawn according to a Z-index
// the optional lcpr and qcpr are linear and quadratic control point radiuses
public static String getsvgstring(IndexedImage ii, HashMap<String, Float> options) {
// SVG start
int w = (int) (ii.width * options.get("scale")), h = (int) (ii.height * options.get("scale"));
String viewboxorviewport = options.get("viewbox") != 0 ? "viewBox=\"0 0 " + w + " " + h + "\" " : "width=\"" + w + "\" height=\"" + h + "\" ";
StringBuilder svgstr = new StringBuilder("<svg " + viewboxorviewport + "version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" ");
if (options.get("desc") != 0) {
svgstr.append("desc=\"Created with ImageTracer.java version " + ImageTracer.versionnumber + "\" ");
}
svgstr.append(">");
// creating Z-index
TreeMap<Double, Integer[]> zindex = new TreeMap<Double, Integer[]>();
double label;
// Layer loop
for (int k = 0; k < ii.layers.size(); k++) {
// Path loop
for (int pcnt = 0; pcnt < ii.layers.get(k).size(); pcnt++) {
// Label (Z-index key) is the startpoint of the path, linearized
label = (ii.layers.get(k).get(pcnt).get(0)[2] * w) + ii.layers.get(k).get(pcnt).get(0)[1];
// Creating new list if required
if (!zindex.containsKey(label)) {
zindex.put(label, new Integer[2]);
}
// Adding layer and path number to list
zindex.get(label)[0] = new Integer(k);
zindex.get(label)[1] = new Integer(pcnt);
}// End of path loop
}// End of layer loop
// Sorting Z-index is not required, TreeMap is sorted automatically
// Drawing
// Z-index loop
String thisdesc = "";
for (Entry<Double, Integer[]> entry : zindex.entrySet()) {
if (options.get("desc") != 0) {
thisdesc = "desc=\"l " + entry.getValue()[0] + " p " + entry.getValue()[1] + "\" ";
} else {
thisdesc = "";
}
svgpathstring(svgstr,
thisdesc,
ii.layers.get(entry.getValue()[0]).get(entry.getValue()[1]),
tosvgcolorstr(ii.palette[entry.getValue()[0]]),
options);
}
// SVG End
svgstr.append("</svg>");
return svgstr.toString();
}// End of getsvgstring()
static String tosvgcolorstr(byte[] c) {
return "fill=\"rgb(" + (c[0] + 128) + "," + (c[1] + 128) + "," + (c[2] + 128) + ")\" stroke=\"rgb(" + (c[0] + 128) + "," + (c[1] + 128) + "," + (c[2] + 128) + ")\" stroke-width=\"1\" opacity=\"" + ((c[3] + 128) / 255.0) + "\" ";
}
}
| 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/thridparty/image4j/LittleEndianRandomAccessFile.java | released/MyBox/src/main/java/thridparty/image4j/LittleEndianRandomAccessFile.java | /*
* LittleEndianRandomAccessFile.java
*
* Created on 07 November 2006, 03:04
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Provides endian conversions for input and output with a <tt>RandomAccessFile</tt>.
*
* This class is currently not in use and has not been tested.
*
* @author Ian McDonagh
*/
public class LittleEndianRandomAccessFile extends RandomAccessFile {
public LittleEndianRandomAccessFile(java.io.File file, String mode) throws FileNotFoundException {
super(file, mode);
}
public LittleEndianRandomAccessFile(String name, String mode) throws FileNotFoundException {
super(name, mode);
}
public short readShortLE() throws IOException {
short ret = super.readShort();
ret = EndianUtils.swapShort(ret);
return ret;
}
public int readIntLE() throws IOException {
int ret = super.readInt();
ret = EndianUtils.swapInteger(ret);
return ret;
}
public float readFloatLE() throws IOException {
float ret = super.readFloat();
ret = EndianUtils.swapFloat(ret);
return ret;
}
public long readLongLE() throws IOException {
long ret = super.readLong();
ret = EndianUtils.swapLong(ret);
return ret;
}
public double readDoubleLE() throws IOException {
double ret = super.readDouble();
ret = EndianUtils.swapDouble(ret);
return ret;
}
public void writeShortLE(short value) throws IOException {
value = EndianUtils.swapShort(value);
super.writeShort(value);
}
public void writeIntLE(int value) throws IOException {
value = EndianUtils.swapInteger(value);
super.writeInt(value);
}
public void writeFloatLE(float value) throws IOException {
value = EndianUtils.swapFloat(value);
super.writeFloat(value);
}
public void writeLongLE(long value) throws IOException {
value = EndianUtils.swapLong(value);
super.writeLong(value);
}
public void writeDoubleLE(double value) throws IOException {
value = EndianUtils.swapDouble(value);
super.writeDouble(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/thridparty/image4j/ICOEncoder.java | released/MyBox/src/main/java/thridparty/image4j/ICOEncoder.java | /*
* ICOEncoder.java
*
* Created on 12 May 2006, 04:08
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.*;
import java.util.List;
import javax.imageio.ImageWriter;
import thridparty.image4j.BMPEncoder;
import thridparty.image4j.InfoHeader;
/**
* Encodes images in ICO format.
* @author Ian McDonagh
*/
public class ICOEncoder {
/** Creates a new instance of ICOEncoder */
private ICOEncoder() {
}
/**
* Encodes and writes a single image to file without colour depth conversion.
* @param image the source image to encode
* @param file the output file to which the encoded image will be written
* @throws java.io.IOException if an exception occurs
*/
public static void write(BufferedImage image, java.io.File file) throws IOException {
write(image, -1, file);
}
/**
* Encodes and writes a single image without colour depth conversion.
* @param image the source image to encode
* @param os the output to which the encoded image will be written
* @throws java.io.IOException if an exception occurs
*/
public static void write(BufferedImage image, java.io.OutputStream os) throws IOException {
write(image, -1, os);
}
/**
* Encodes and writes multiple images without colour depth conversion.
* @param images the list of source images to be encoded
* @param os the output to which the encoded image will be written
* @throws java.io.IOException if an error occurs
*/
public static void write(List<BufferedImage> images, java.io.OutputStream os) throws IOException {
write(images, null, null, os);
}
/**
* Encodes and writes multiple images to file without colour depth conversion.
* @param images the list of source images to encode
* @param file the file to which the encoded images will be written
* @throws java.io.IOException if an exception occurs
*/
public static void write(List<BufferedImage> images, java.io.File file) throws IOException {
write(images, null, file);
}
/**
* Encodes and writes multiple images to file with the colour depth conversion using the specified values.
* @param images the list of source images to encode
* @param bpp array containing desired colour depths for colour depth conversion
* @param file the output file to which the encoded images will be written
* @throws java.io.IOException if an error occurs
*/
public static void write(List<BufferedImage> images, int[] bpp, java.io.File file) throws IOException {
write(images, bpp, new java.io.FileOutputStream(file));
}
/**
* Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on.
* @param images List of images to encode, which will be output in the order supplied in the list.
* @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image.
* @param compress Array containing the compression flag for the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no compression will be peformed. A value of <tt>true</tt> specifies that compression should be performed, while a value of <tt>false</tt> specifies that no compression should be performed.
* @param file the file to which the encoded images will be written.
* @throws java.io.IOException if an error occurred.
* @since 0.6
*/
public static void write(List<BufferedImage> images, int[] bpp, boolean[] compress, java.io.File file) throws IOException {
write(images, bpp, compress, new java.io.FileOutputStream(file));
}
/**
* Encodes and writes a single image to file with colour depth conversion using the specified value.
* @param image the source image to encode
* @param bpp the colour depth (bits per pixel) for the colour depth conversion, or <tt>-1</tt> if no colour depth conversion should be performed
* @param file the output file to which the encoded image will be written
* @throws java.io.IOException if an error occurs
*/
public static void write(BufferedImage image, int bpp, java.io.File file) throws IOException {
java.io.FileOutputStream fout = new java.io.FileOutputStream(file);
try {
BufferedOutputStream out = new BufferedOutputStream(fout);
write(image, bpp, out);
out.flush();
} finally {
try {
fout.close();
} catch (IOException ex) { }
}
}
/**
* Encodes and outputs a single image in ICO format.
* Convenience method, which calls {@link #write(java.util.List,int[],java.io.OutputStream) write(java.util.List,int[],java.io.OutputStream)}.
* @param image The image to encode.
* @param bpp Colour depth (in bits per pixel) for the colour depth conversion, or <tt>-1</tt> if no colour depth conversion should be performed.
* @param os The output to which the encoded image will be written.
* @throws java.io.IOException if an error occurs when trying to write the output.
*/
public static void write(BufferedImage image, int bpp, java.io.OutputStream os) throws IOException {
List<BufferedImage> list = new java.util.ArrayList<BufferedImage>(1);
list.add(image);
write(list, new int[] { bpp }, new boolean[] { false }, os);
}
/**
* Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on.
* @param images List of images to encode, which will be output in the order supplied in the list.
* @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image.
* @param os The output to which the encoded images will be written.
* @throws java.io.IOException if an error occurred.
*/
public static void write(List<BufferedImage> images, int[] bpp, java.io.OutputStream os) throws IOException {
write(images, bpp, null, os);
}
/**
* Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on.
* @param images List of images to encode, which will be output in the order supplied in the list.
* @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image.
* @param compress Array containing the compression flag for the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no compression will be peformed. A value of <tt>true</tt> specifies that compression should be performed, while a value of <tt>false</tt> specifies that no compression should be performed.
* @param os The output to which the encoded images will be written.
* @throws java.io.IOException if an error occurred.
* @since 0.6
*/
public static void write(List<BufferedImage> images, int[] bpp, boolean[] compress, java.io.OutputStream os) throws IOException {
LittleEndianOutputStream out = new LittleEndianOutputStream(os);
int count = images.size();
//file header 6
writeFileHeader(count, ICOConstants.TYPE_ICON, out);
//file offset where images start
int fileOffset = 6 + count * 16;
List<InfoHeader> infoHeaders = new java.util.ArrayList<InfoHeader>(count);
List<BufferedImage> converted = new java.util.ArrayList<BufferedImage>(count);
List<byte[]> compressedImages = null;
if (compress != null) {
compressedImages = new java.util.ArrayList<byte[]>(count);
}
javax.imageio.ImageWriter pngWriter = null;
//icon entries 16 * count
for (int i = 0; i < count; i++) {
BufferedImage img = images.get(i);
int b = bpp == null ? -1 : bpp[i];
//convert image
BufferedImage imgc = b == -1 ? img : convert(img, b);
converted.add(imgc);
//create info header
InfoHeader ih = BMPEncoder.createInfoHeader(imgc);
//create icon entry
IconEntry e = createIconEntry(ih);
if (compress != null) {
if (compress[i]) {
if (pngWriter == null) {
pngWriter = getPNGImageWriter();
}
byte[] compressedImage = encodePNG(pngWriter, imgc);
compressedImages.add(compressedImage);
e.iSizeInBytes = compressedImage.length;
} else {
compressedImages.add(null);
}
}
ih.iHeight *= 2;
e.iFileOffset = fileOffset;
fileOffset += e.iSizeInBytes;
e.write(out);
infoHeaders.add(ih);
}
//images
for (int i = 0; i < count; i++) {
BufferedImage img = images.get(i);
BufferedImage imgc = converted.get(i);
if (compress == null || !compress[i]) {
//info header
InfoHeader ih = infoHeaders.get(i);
ih.write(out);
//color map
if (ih.sBitCount <= 8) {
IndexColorModel icm = (IndexColorModel) imgc.getColorModel();
BMPEncoder.writeColorMap(icm, out);
}
//xor bitmap
writeXorBitmap(imgc, ih, out);
//and bitmap
writeAndBitmap(img, out);
}
else {
byte[] compressedImage = compressedImages.get(i);
out.write(compressedImage);
}
//javax.imageio.ImageIO.write(imgc, "png", new java.io.File("test_"+i+".png"));
}
}
/**
* Writes the ICO file header for an ICO containing the given number of images.
* @param count the number of images in the ICO
* @param type one of {@link net.sf.image4j.codec.ico.ICOConstants#TYPE_ICON TYPE_ICON} or
* {@link net.sf.image4j.codec.ico.ICOConstants#TYPE_CURSOR TYPE_CURSOR}
* @param out the output to which the file header will be written
* @throws java.io.IOException if an error occurs
*/
public static void writeFileHeader(int count, int type, LittleEndianOutputStream out) throws IOException {
//reserved 2
out.writeShortLE((short) 0);
//type 2
out.writeShortLE((short) type);
//count 2
out.writeShortLE((short) count);
}
/**
* Constructs an <tt>IconEntry</tt> from the given <tt>InfoHeader</tt>
* structure.
* @param ih the <tt>InfoHeader</tt> structure from which to construct the <tt>IconEntry</tt> structure.
* @return the <tt>IconEntry</tt> structure constructed from the <tt>IconEntry</tt> structure.
*/
public static IconEntry createIconEntry(InfoHeader ih) {
IconEntry ret = new IconEntry();
//width 1
ret.bWidth = ih.iWidth == 256 ? 0 : ih.iWidth;
//height 1
ret.bHeight = ih.iHeight == 256 ? 0 : ih.iHeight;
//color count 1
ret.bColorCount = ih.iNumColors >= 256 ? 0 : ih.iNumColors;
//reserved 1
ret.bReserved = 0;
//planes 2 = 1
ret.sPlanes = 1;
//bit count 2
ret.sBitCount = ih.sBitCount;
//sizeInBytes 4 - size of infoHeader + xor bitmap + and bitbmap
int cmapSize = BMPEncoder.getColorMapSize(ih.sBitCount);
int xorSize = BMPEncoder.getBitmapSize(ih.iWidth, ih.iHeight, ih.sBitCount);
int andSize = BMPEncoder.getBitmapSize(ih.iWidth, ih.iHeight, 1);
int size = ih.iSize + cmapSize + xorSize + andSize;
ret.iSizeInBytes = size;
//fileOffset 4
ret.iFileOffset = 0;
return ret;
}
/**
* Encodes the <em>AND</em> bitmap for the given image according the its alpha channel (transparency) and writes it to the given output.
* @param img the image to encode as the <em>AND</em> bitmap.
* @param out the output to which the <em>AND</em> bitmap will be written
* @throws java.io.IOException if an error occurs.
*/
public static void writeAndBitmap(BufferedImage img, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
WritableRaster alpha = img.getAlphaRaster();
//indexed transparency (eg. GIF files)
if (img.getColorModel() instanceof IndexColorModel && img.getColorModel().hasAlpha()) {
int w = img.getWidth();
int h = img.getHeight();
int bytesPerLine = BMPEncoder.getBytesPerLine1(w);
byte[] line = new byte[bytesPerLine];
IndexColorModel icm = (IndexColorModel) img.getColorModel();
Raster raster = img.getRaster();
for (int y = h - 1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
int bi = x / 8;
int i = x % 8;
//int a = alpha.getSample(x, y, 0);
int p = raster.getSample(x, y, 0);
int a = icm.getAlpha(p);
//invert bit since and mask is applied to xor mask
int b = ~a & 1;
line[bi] = setBit(line[bi], i, b);
}
out.write(line);
}
}
//no transparency
else if (alpha == null) {
int h = img.getHeight();
int w = img.getWidth();
//calculate number of bytes per line, including 32-bit padding
int bytesPerLine = BMPEncoder.getBytesPerLine1(w);
byte[] line = new byte[bytesPerLine];
for (int i = 0; i < bytesPerLine; i++) {
line[i] = (byte) 0;
}
for (int y = h - 1; y >= 0; y--) {
out.write(line);
}
}
//transparency (ARGB, etc. eg. PNG)
else {
//BMPEncoder.write1(alpha, cmap, out);
int w = img.getWidth();
int h = img.getHeight();
int bytesPerLine = BMPEncoder.getBytesPerLine1(w);
byte[] line = new byte[bytesPerLine];
for (int y = h - 1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
int bi = x / 8;
int i = x % 8;
int a = alpha.getSample(x, y, 0);
//invert bit since and mask is applied to xor mask
int b = ~a & 1;
line[bi] = setBit(line[bi], i, b);
}
out.write(line);
}
}
}
private static byte setBit(byte bits, int index, int bit) {
int mask = 1 << (7 - index);
bits &= ~mask;
bits |= bit << (7 - index);
return bits;
}
private static void writeXorBitmap(BufferedImage img, InfoHeader ih, LittleEndianOutputStream out) throws IOException {
Raster raster = img.getRaster();
switch (ih.sBitCount) {
case 1:
BMPEncoder.write1(raster, out);
break;
case 4:
BMPEncoder.write4(raster, out);
break;
case 8:
BMPEncoder.write8(raster, out);
break;
case 24:
BMPEncoder.write24(raster, out);
break;
case 32:
Raster alpha = img.getAlphaRaster();
BMPEncoder.write32(raster, alpha, out);
break;
}
}
/**
* Utility method, which converts the given image to the specified colour depth.
* @param img the image to convert.
* @param bpp the target colour depth (bits per pixel) for the conversion.
* @return the given image converted to the specified colour depth.
*/
public static BufferedImage convert(BufferedImage img, int bpp) {
BufferedImage ret = null;
switch (bpp) {
case 1:
ret = ConvertUtil.convert1(img);
break;
case 4:
ret = ConvertUtil.convert4(img);
break;
case 8:
ret = ConvertUtil.convert8(img);
break;
case 24:
int b = img.getColorModel().getPixelSize();
if (b == 24 || b == 32) {
ret = img;
} else {
ret = ConvertUtil.convert24(img);
}
break;
case 32:
int b2 = img.getColorModel().getPixelSize();
if (b2 == 24 || b2 == 32) {
ret = img;
} else {
ret = ConvertUtil.convert32(img);
}
break;
}
return ret;
}
/**
* @since 0.6
*/
private static javax.imageio.ImageWriter getPNGImageWriter() {
javax.imageio.ImageWriter ret = null;
java.util.Iterator<javax.imageio.ImageWriter> itr = javax.imageio.ImageIO.getImageWritersByFormatName("png");
if (itr.hasNext()) {
ret = itr.next();
}
return ret;
}
/**
* @since 0.6
*/
private static byte[] encodePNG(ImageWriter pngWriter, BufferedImage img) throws IOException {
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
javax.imageio.stream.ImageOutputStream output = javax.imageio.ImageIO.createImageOutputStream(bout);
pngWriter.setOutput(output);
pngWriter.write(img);
bout.flush();
byte[] ret = bout.toByteArray();
return ret;
}
}
| 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/thridparty/image4j/CountingInput.java | released/MyBox/src/main/java/thridparty/image4j/CountingInput.java | package thridparty.image4j;
public interface CountingInput {
int getCount();
}
| 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/thridparty/image4j/BMPEncoder.java | released/MyBox/src/main/java/thridparty/image4j/BMPEncoder.java | /*
* BMPEncoder.java
*
* Created on 11 May 2006, 04:19
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.io.*;
/**
* Encodes images in BMP format.
* @author Ian McDonagh
*/
public class BMPEncoder {
/** Creates a new instance of BMPEncoder */
private BMPEncoder() {
}
/**
* Encodes and writes BMP data the output file
* @param img the image to encode
* @param file the file to which encoded data will be written
* @throws java.io.IOException if an error occurs
*/
public static void write(BufferedImage img, java.io.File file) throws IOException {
java.io.FileOutputStream fout = new java.io.FileOutputStream(file);
try {
BufferedOutputStream out = new BufferedOutputStream(fout);
write(img, out);
out.flush();
} finally {
try {
fout.close();
} catch (IOException ex) { }
}
}
/**
* Encodes and writes BMP data to the output
* @param img the image to encode
* @param os the output to which encoded data will be written
* @throws java.io.IOException if an error occurs
*/
public static void write(BufferedImage img, java.io.OutputStream os) throws IOException {
// create info header
InfoHeader ih = createInfoHeader(img);
// Create colour map if the image uses an indexed colour model.
// Images with colour depth of 8 bits or less use an indexed colour model.
int mapSize = 0;
IndexColorModel icm = null;
if (ih.sBitCount <= 8) {
icm = (IndexColorModel) img.getColorModel();
mapSize = icm.getMapSize();
}
// Calculate header size
int headerSize = 14 //file header
+ ih.iSize //info header
;
// Calculate map size
int mapBytes = 4 * mapSize;
// Calculate data offset
int dataOffset = headerSize + mapBytes;
// Calculate bytes per line
int bytesPerLine = 0;
switch (ih.sBitCount) {
case 1:
bytesPerLine = getBytesPerLine1(ih.iWidth);
break;
case 4:
bytesPerLine = getBytesPerLine4(ih.iWidth);
break;
case 8:
bytesPerLine = getBytesPerLine8(ih.iWidth);
break;
case 24:
bytesPerLine = getBytesPerLine24(ih.iWidth);
break;
case 32:
bytesPerLine = ih.iWidth * 4;
break;
}
// calculate file size
int fileSize = dataOffset + bytesPerLine * ih.iHeight;
// output little endian byte order
LittleEndianOutputStream out = new LittleEndianOutputStream(os);
//write file header
writeFileHeader(fileSize, dataOffset, out);
//write info header
ih.write(out);
//write color map (bit count <= 8)
if (ih.sBitCount <= 8) {
writeColorMap(icm, out);
}
//write raster data
switch (ih.sBitCount) {
case 1:
write1(img.getRaster(), out);
break;
case 4:
write4(img.getRaster(), out);
break;
case 8:
write8(img.getRaster(), out);
break;
case 24:
write24(img.getRaster(), out);
break;
case 32:
write32(img.getRaster(), img.getAlphaRaster(), out);
break;
}
}
/**
* Creates an <tt>InfoHeader</tt> from the source image.
* @param img the source image
* @return the resultant <tt>InfoHeader</tt> structure
*/
public static InfoHeader createInfoHeader(BufferedImage img) {
InfoHeader ret = new InfoHeader();
ret.iColorsImportant = 0;
ret.iColorsUsed = 0;
ret.iCompression = 0;
ret.iHeight = img.getHeight();
ret.iWidth = img.getWidth();
ret.sBitCount = (short) img.getColorModel().getPixelSize();
ret.iNumColors = 1 << (ret.sBitCount == 32 ? 24 : ret.sBitCount);
ret.iImageSize = 0;
return ret;
}
/**
* Writes the file header.
* @param fileSize the calculated file size for the BMP data being written
* @param dataOffset the calculated offset within the BMP data where the actual bitmap begins
* @param out the output to which the file header will be written
* @throws java.io.IOException if an error occurs
*/
public static void writeFileHeader(int fileSize, int dataOffset,
thridparty.image4j.LittleEndianOutputStream out) throws IOException {
//signature
byte[] signature = BMPConstants.FILE_HEADER.getBytes("UTF-8");
out.write(signature);
//file size
out.writeIntLE(fileSize);
//reserved
out.writeIntLE(0);
//data offset
out.writeIntLE(dataOffset);
}
/**
* Writes the colour map resulting from the source <tt>IndexColorModel</tt>.
* @param icm the source <tt>IndexColorModel</tt>
* @param out the output to which the colour map will be written
* @throws java.io.IOException if an error occurs
*/
public static void writeColorMap(IndexColorModel icm, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
int mapSize = icm.getMapSize();
for (int i = 0; i < mapSize; i++) {
int rgb = icm.getRGB(i);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb) &0xFF;
out.writeByte(b);
out.writeByte(g);
out.writeByte(r);
out.writeByte(0);
}
}
/**
* Calculates the number of bytes per line required for the given width in pixels,
* for a 1-bit bitmap. Lines are always padded to the next 4-byte boundary.
* @param width the width in pixels
* @return the number of bytes per line
*/
public static int getBytesPerLine1(int width) {
int ret = (int) width / 8;
if (ret * 8 < width) {
ret++;
}
if (ret % 4 != 0) {
ret = (ret / 4 + 1) * 4;
}
return ret;
}
/**
* Calculates the number of bytes per line required for the given with in pixels,
* for a 4-bit bitmap. Lines are always padded to the next 4-byte boundary.
* @param width the width in pixels
* @return the number of bytes per line
*/
public static int getBytesPerLine4(int width) {
int ret = (int) width / 2;
if (ret % 4 != 0) {
ret = (ret / 4 + 1) * 4;
}
return ret;
}
/**
* Calculates the number of bytes per line required for the given with in pixels,
* for a 8-bit bitmap. Lines are always padded to the next 4-byte boundary.
* @param width the width in pixels
* @return the number of bytes per line
*/
public static int getBytesPerLine8(int width) {
int ret = width;
if (ret % 4 != 0) {
ret = (ret / 4 + 1) * 4;
}
return ret;
}
/**
* Calculates the number of bytes per line required for the given with in pixels,
* for a 24-bit bitmap. Lines are always padded to the next 4-byte boundary.
* @param width the width in pixels
* @return the number of bytes per line
*/
public static int getBytesPerLine24(int width) {
int ret = width * 3;
if (ret % 4 != 0) {
ret = (ret / 4 + 1) * 4;
}
return ret;
}
/**
* Calculates the size in bytes of a bitmap with the specified size and colour depth.
* @param w the width in pixels
* @param h the height in pixels
* @param bpp the colour depth (bits per pixel)
* @return the size of the bitmap in bytes
*/
public static int getBitmapSize(int w, int h, int bpp) {
int bytesPerLine = 0;
switch (bpp) {
case 1:
bytesPerLine = getBytesPerLine1(w);
break;
case 4:
bytesPerLine = getBytesPerLine4(w);
break;
case 8:
bytesPerLine = getBytesPerLine8(w);
break;
case 24:
bytesPerLine = getBytesPerLine24(w);
break;
case 32:
bytesPerLine = w * 4;
break;
}
int ret = bytesPerLine * h;
return ret;
}
/**
* Encodes and writes raster data as a 1-bit bitmap.
* @param raster the source raster data
* @param out the output to which the bitmap will be written
* @throws java.io.IOException if an error occurs
*/
public static void write1(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
int bytesPerLine = getBytesPerLine1(raster.getWidth());
byte[] line = new byte[bytesPerLine];
for (int y = raster.getHeight() - 1; y >= 0; y--) {
for (int i = 0; i < bytesPerLine; i++) {
line[i] = 0;
}
for (int x = 0; x < raster.getWidth(); x++) {
int bi = x / 8;
int i = x % 8;
int index = raster.getSample(x, y, 0);
line[bi] = setBit(line[bi], i, index);
}
out.write(line);
}
}
/**
* Encodes and writes raster data as a 4-bit bitmap.
* @param raster the source raster data
* @param out the output to which the bitmap will be written
* @throws java.io.IOException if an error occurs
*/
public static void write4(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
// The approach taken here is to use a buffer to hold encoded raster data
// one line at a time.
// Perhaps we could just write directly to output instead
// and avoid using a buffer altogether. Hypothetically speaking,
// a very wide image would require a large line buffer here, but then again,
// large 4 bit bitmaps are pretty uncommon, so using the line buffer approach
// should be okay.
int width = raster.getWidth();
int height = raster.getHeight();
// calculate bytes per line
int bytesPerLine = getBytesPerLine4(width);
// line buffer
byte[] line = new byte[bytesPerLine];
// encode and write lines
for (int y = height - 1; y >= 0; y--) {
// clear line buffer
for (int i = 0; i < bytesPerLine; i++) {
line[i] = 0;
}
// encode raster data for line
for (int x = 0; x < width; x++) {
// calculate buffer index
int bi = x / 2;
// calculate nibble index (high order or low order)
int i = x % 2;
// get color index
int index = raster.getSample(x, y, 0);
// set color index in buffer
line[bi] = setNibble(line[bi], i, index);
}
// write line data (padding bytes included)
out.write(line);
}
}
/**
* Encodes and writes raster data as an 8-bit bitmap.
* @param raster the source raster data
* @param out the output to which the bitmap will be written
* @throws java.io.IOException if an error occurs
*/
public static void write8(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
int width = raster.getWidth();
int height = raster.getHeight();
// calculate bytes per line
int bytesPerLine = getBytesPerLine8(width);
// write lines
for (int y = height - 1; y >= 0; y--) {
// write raster data for each line
for (int x = 0; x < width; x++) {
// get color index for pixel
int index = raster.getSample(x, y, 0);
// write color index
out.writeByte(index);
}
// write padding bytes at end of line
for (int i = width; i < bytesPerLine; i++) {
out.writeByte(0);
}
}
}
/**
* Encodes and writes raster data as a 24-bit bitmap.
* @param raster the source raster data
* @param out the output to which the bitmap will be written
* @throws java.io.IOException if an error occurs
*/
public static void write24(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
int width = raster.getWidth();
int height = raster.getHeight();
// calculate bytes per line
int bytesPerLine = getBytesPerLine24(width);
// write lines
for (int y = height - 1; y >= 0; y--) {
// write pixel data for each line
for (int x = 0; x < width; x++) {
// get RGB values for pixel
int r = raster.getSample(x, y, 0);
int g = raster.getSample(x, y, 1);
int b = raster.getSample(x, y, 2);
// write RGB values
out.writeByte(b);
out.writeByte(g);
out.writeByte(r);
}
// write padding bytes at end of line
for (int i = width * 3; i < bytesPerLine; i++) {
out.writeByte(0);
}
}
}
/**
* Encodes and writes raster data, together with alpha (transparency) data, as a 32-bit bitmap.
* @param raster the source raster data
* @param alpha the source alpha data
* @param out the output to which the bitmap will be written
* @throws java.io.IOException if an error occurs
*/
public static void write32(Raster raster, Raster alpha, thridparty.image4j.LittleEndianOutputStream out) throws IOException {
int width = raster.getWidth();
int height = raster.getHeight();
// write lines
for (int y = height - 1; y >= 0; y--) {
// write pixel data for each line
for (int x = 0; x < width; x++) {
// get RGBA values
int r = raster.getSample(x, y, 0);
int g = raster.getSample(x, y, 1);
int b = raster.getSample(x, y, 2);
int a = alpha.getSample(x, y, 0);
// write RGBA values
out.writeByte(b);
out.writeByte(g);
out.writeByte(r);
out.writeByte(a);
}
}
}
/**
* Sets a particular bit in a byte.
* @param bits the source byte
* @param index the index of the bit to set
* @param bit the value for the bit, which should be either <tt>0</tt> or <tt>1</tt>.
* @param the resultant byte
*/
private static byte setBit(byte bits, int index, int bit) {
if (bit == 0) {
bits &= ~(1 << (7 - index));
} else {
bits |= 1 << (7 - index);
}
return bits;
}
/**
* Sets a particular nibble (4 bits) in a byte.
* @param nibbles the source byte
* @param index the index of the nibble to set
* @param the value for the nibble, which should be in the range <tt>0x0..0xF</tt>.
*/
private static byte setNibble(byte nibbles, int index, int nibble) {
nibbles |= (nibble << ((1 - index) * 4));
return nibbles;
}
/**
* Calculates the size in bytes for a colour map with the specified bit count.
* @param sBitCount the bit count, which represents the colour depth
* @return the size of the colour map, in bytes if <tt>sBitCount</tt> is less than or equal to 8,
* otherwise <tt>0</tt> as colour maps are only used for bitmaps with a colour depth of 8 bits or less.
*/
public static int getColorMapSize(short sBitCount) {
int ret = 0;
if (sBitCount <= 8) {
ret = (1 << sBitCount) * 4;
}
return ret;
}
}
| 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/thridparty/image4j/IconEntry.java | released/MyBox/src/main/java/thridparty/image4j/IconEntry.java | package thridparty.image4j;
import java.io.IOException;
/**
* Represents an <tt>IconEntry</tt> structure, which contains information about an ICO image.
* @author Ian McDonagh
*/
public class IconEntry {
/**
* The width of the icon image in pixels.
* <tt>0</tt> specifies a width of 256 pixels.
*/
public int bWidth;
/**
* The height of the icon image in pixels.
* <tt>0</tt> specifies a height of 256 pixels.
*/
public int bHeight;
/**
* The number of colours, calculated from {@link #sBitCount sBitCount}.
* <tt>0</tt> specifies a colour count of >= 256.
*/
public int bColorCount;
/**
* Unused. Should always be <tt>0</tt>.
*/
public byte bReserved;
/**
* Number of planes, which should always be <tt>1</tt>.
*/
public short sPlanes;
/**
* Colour depth in bits per pixel.
*/
public short sBitCount;
/**
* Size of ICO data, which should be the size of (InfoHeader + AND bitmap + XOR bitmap).
*/
public int iSizeInBytes;
/**
* Position in file where the InfoHeader starts.
*/
public int iFileOffset;
/**
* Creates an <tt>IconEntry</tt> structure from the source input
* @param in the source input
* @throws java.io.IOException if an error occurs
*/
public IconEntry(LittleEndianInputStream in) throws IOException {
//Width 1 byte Cursor Width (16, 32, 64, 0 = 256)
bWidth = in.readUnsignedByte();
//Height 1 byte Cursor Height (16, 32, 64, 0 = 256 , most commonly = Width)
bHeight = in.readUnsignedByte();
//ColorCount 1 byte Number of Colors (2,16, 0=256)
bColorCount = in.readUnsignedByte();
//Reserved 1 byte =0
bReserved = in.readByte();
//Planes 2 byte =1
sPlanes = in.readShortLE();
//BitCount 2 byte bits per pixel (1, 4, 8)
sBitCount = in.readShortLE();
//SizeInBytes 4 byte Size of (InfoHeader + ANDbitmap + XORbitmap)
iSizeInBytes = in.readIntLE();
//FileOffset 4 byte FilePos, where InfoHeader starts
iFileOffset = in.readIntLE();
}
/**
* Creates and <tt>IconEntry</tt> structure with default values.
*/
public IconEntry() {
bWidth = 0;
bHeight = 0;
bColorCount = 0;
sPlanes = 1;
bReserved = 0;
sBitCount = 0;
iSizeInBytes = 0;
iFileOffset = 0;
}
/**
* A string representation of this <tt>IconEntry</tt> structure.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("width=");
sb.append(bWidth);
sb.append(",height=");
sb.append(bHeight);
sb.append(",bitCount=");
sb.append(sBitCount);
sb.append(",colorCount="+bColorCount);
return sb.toString();
}
/**
* Writes the <tt>IconEntry</tt> structure to output
* @param out the output
* @throws java.io.IOException if an error occurs
*/
public void write(thridparty.image4j.LittleEndianOutputStream out) throws IOException {
//Width 1 byte Cursor Width (16, 32 or 64)
out.writeByte(bWidth);
//Height 1 byte Cursor Height (16, 32 or 64 , most commonly = Width)
out.writeByte(bHeight);
//ColorCount 1 byte Number of Colors (2,16, 0=256)
out.writeByte(bColorCount);
//Reserved 1 byte =0
out.writeByte(bReserved);
//Planes 2 byte =1
out.writeShortLE(sPlanes);
//BitCount 2 byte bits per pixel (1, 4, 8)
out.writeShortLE(sBitCount);
//SizeInBytes 4 byte Size of (InfoHeader + ANDbitmap + XORbitmap)
out.writeIntLE(iSizeInBytes);
//FileOffset 4 byte FilePos, where InfoHeader starts
out.writeIntLE(iFileOffset);
}
}
| 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/thridparty/image4j/CountingDataInputStream.java | released/MyBox/src/main/java/thridparty/image4j/CountingDataInputStream.java | package thridparty.image4j;
import java.io.*;
public class CountingDataInputStream extends DataInputStream implements CountingDataInput {
public CountingDataInputStream(InputStream in) {
super(new CountingInputStream(in));
}
@Override
public int getCount() {
return ((CountingInputStream) in).getCount();
}
public int skip(int count, boolean strict) throws IOException {
return IOUtils.skip(this, count, strict);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" +in + ") ["+getCount()+"]";
}
}
| 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/thridparty/image4j/BMPImage.java | released/MyBox/src/main/java/thridparty/image4j/BMPImage.java | /*
* BMPImage.java
*
* Created on February 19, 2007, 8:08 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
/**
* Contains a decoded BMP image, as well as information about the source encoded image.
* @since 0.7
* @author Ian McDonagh
*/
public class BMPImage {
protected InfoHeader infoHeader;
protected java.awt.image.BufferedImage image;
/**
* Creates a new instance of BMPImage
* @param image the decoded image
* @param infoHeader the InfoHeader structure providing information about the source encoded image
*/
public BMPImage(java.awt.image.BufferedImage image, InfoHeader infoHeader) {
this.image = image;
this.infoHeader = infoHeader;
}
/**
* The InfoHeader structure representing the encoded BMP image.
*/
public InfoHeader getInfoHeader() {
return infoHeader;
}
/**
* Sets the InfoHeader structure used for encoding the BMP image.
*/
public void setInfoHeader(InfoHeader infoHeader) {
this.infoHeader = infoHeader;
}
/**
* The decoded BMP image.
*/
public java.awt.image.BufferedImage getImage() {
return image;
}
/**
* Sets the image to be encoded.
*/
public void setImage(java.awt.image.BufferedImage image) {
this.image = image;
}
/**
* The width of the BMP image in pixels.
* @return the width of the BMP image, or <tt>-1</tt> if unknown
* @since 0.7alpha2
*/
public int getWidth() {
return infoHeader == null ? -1 : infoHeader.iWidth;
}
/**
* The height of the BMP image in pixels.
* @return the height of the BMP image, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getHeight() {
return infoHeader == null ? -1 : infoHeader.iHeight;
}
/**
* The colour depth of the BMP image (bits per pixel).
* @return the colour depth, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getColourDepth() {
return infoHeader == null ? -1 : infoHeader.sBitCount;
}
/**
* The number of possible colours for the BMP image.
* @return the number of colours, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getColourCount() {
int bpp = infoHeader.sBitCount == 32 ? 24 : infoHeader.sBitCount;
return bpp == -1 ? -1 : (int) (1 << bpp);
}
/**
* Specifies whether this BMP image is indexed, that is, the encoded bitmap uses a colour table.
* If <tt>getColourDepth()</tt> returns <tt>-1</tt>, the return value has no meaning.
* @return <tt>true</tt> if indexed, <tt>false</tt> if not.
* @since 0.7alpha2
*/
public boolean isIndexed() {
return infoHeader == null ? false : infoHeader.sBitCount <= 8;
}
}
| 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/thridparty/image4j/IOUtils.java | released/MyBox/src/main/java/thridparty/image4j/IOUtils.java | package thridparty.image4j;
import java.io.*;
public class IOUtils {
public static int skip(InputStream in, int count, boolean strict) throws IOException {
int skipped = 0;
while (skipped < count) {
int b = in.read();
if (b == -1) {
break;
}
skipped++;
}
if (skipped < count && strict) {
throw new EOFException("Failed to skip " + count
+ " bytes in input");
}
return skipped;
}
}
| 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/thridparty/image4j/InfoHeader.java | released/MyBox/src/main/java/thridparty/image4j/InfoHeader.java | /*
* InfoHeader.java
*
* Created on 10 May 2006, 08:10
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.io.IOException;
/**
* Represents a bitmap <tt>InfoHeader</tt> structure, which provides header information.
* @author Ian McDonagh
*/
public class InfoHeader {
/**
* The size of this <tt>InfoHeader</tt> structure in bytes.
*/
public int iSize;
/**
* The width in pixels of the bitmap represented by this <tt>InfoHeader</tt>.
*/
public int iWidth;
/**
* The height in pixels of the bitmap represented by this <tt>InfoHeader</tt>.
*/
public int iHeight;
/**
* The number of planes, which should always be <tt>1</tt>.
*/
public short sPlanes;
/**
* The bit count, which represents the colour depth (bits per pixel).
* This should be either <tt>1</tt>, <tt>4</tt>, <tt>8</tt>, <tt>24</tt> or <tt>32</tt>.
*/
public short sBitCount;
/**
* The compression type, which should be one of the following:
* <ul>
* <li>{@link BMPConstants#BI_RGB BI_RGB} - no compression</li>
* <li>{@link BMPConstants#BI_RLE8 BI_RLE8} - 8-bit RLE compression</li>
* <li>{@link BMPConstants#BI_RLE4 BI_RLE4} - 4-bit RLE compression</li>
* </ul>
*/
public int iCompression;
/**
* The compressed size of the image in bytes, or <tt>0</tt> if <tt>iCompression</tt> is <tt>0</tt>.
*/
public int iImageSize;
/**
* Horizontal resolution in pixels/m.
*/
public int iXpixelsPerM;
/**
* Vertical resolution in pixels/m.
*/
public int iYpixelsPerM;
/**
* Number of colours actually used in the bitmap.
*/
public int iColorsUsed;
/**
* Number of important colours (<tt>0</tt> = all).
*/
public int iColorsImportant;
/**
* Calculated number of colours, based on the colour depth specified by {@link #sBitCount sBitCount}.
*/
public int iNumColors;
/**
* Creates an <tt>InfoHeader</tt> structure from the source input.
* @param in the source input
* @throws java.io.IOException if an error occurs
*/
public InfoHeader(thridparty.image4j.LittleEndianInputStream in) throws IOException {
//Size of InfoHeader structure = 40
iSize = in.readIntLE();
init(in, iSize);
}
/**
* @since 0.6
*/
public InfoHeader(thridparty.image4j.LittleEndianInputStream in, int infoSize) throws IOException {
init(in, infoSize);
}
/**
* @since 0.6
*/
protected void init(thridparty.image4j.LittleEndianInputStream in, int infoSize) throws IOException {
this.iSize = infoSize;
//Width
iWidth = in.readIntLE();
//Height
iHeight = in.readIntLE();
//Planes (=1)
sPlanes = in.readShortLE();
//Bit count
sBitCount = in.readShortLE();
//calculate NumColors
iNumColors = (int) Math.pow(2, sBitCount);
//Compression
iCompression = in.readIntLE();
//Image size - compressed size of image or 0 if Compression = 0
iImageSize = in.readIntLE();
//horizontal resolution pixels/meter
iXpixelsPerM = in.readIntLE();
//vertical resolution pixels/meter
iYpixelsPerM = in.readIntLE();
//Colors used - number of colors actually used
iColorsUsed = in.readIntLE();
//Colors important - number of important colors 0 = all
iColorsImportant = in.readIntLE();
}
/**
* Creates an <tt>InfoHeader</tt> with default values.
*/
public InfoHeader() {
//Size of InfoHeader structure = 40
iSize = 40;
//Width
iWidth = 0;
//Height
iHeight = 0;
//Planes (=1)
sPlanes = 1;
//Bit count
sBitCount = 0;
//caculate NumColors
iNumColors = 0;
//Compression
iCompression = BMPConstants.BI_RGB;
//Image size - compressed size of image or 0 if Compression = 0
iImageSize = 0;
//horizontal resolution pixels/meter
iXpixelsPerM = 0;
//vertical resolution pixels/meter
iYpixelsPerM = 0;
//Colors used - number of colors actually used
iColorsUsed = 0;
//Colors important - number of important colors 0 = all
iColorsImportant = 0;
}
/**
* Creates a copy of the source <tt>InfoHeader</tt>.
* @param source the source to copy
*/
public InfoHeader(InfoHeader source) {
iColorsImportant = source.iColorsImportant;
iColorsUsed = source.iColorsUsed;
iCompression = source.iCompression;
iHeight = source.iHeight;
iWidth = source.iWidth;
iImageSize = source.iImageSize;
iNumColors = source.iNumColors;
iSize = source.iSize;
iXpixelsPerM = source.iXpixelsPerM;
iYpixelsPerM = source.iYpixelsPerM;
sBitCount = source.sBitCount;
sPlanes = source.sPlanes;
}
/**
* Writes the <tt>InfoHeader</tt> structure to output
* @param out the output to which the structure will be written
* @throws java.io.IOException if an error occurs
*/
public void write(thridparty.image4j.LittleEndianOutputStream out) throws IOException {
//Size of InfoHeader structure = 40
out.writeIntLE(iSize);
//Width
out.writeIntLE(iWidth);
//Height
out.writeIntLE(iHeight);
//Planes (=1)
out.writeShortLE(sPlanes);
//Bit count
out.writeShortLE(sBitCount);
//caculate NumColors
//iNumColors = (int) Math.pow(2, sBitCount);
//Compression
out.writeIntLE(iCompression);
//Image size - compressed size of image or 0 if Compression = 0
out.writeIntLE(iImageSize);
//horizontal resolution pixels/meter
out.writeIntLE(iXpixelsPerM);
//vertical resolution pixels/meter
out.writeIntLE(iYpixelsPerM);
//Colors used - number of colors actually used
out.writeIntLE(iColorsUsed);
//Colors important - number of important colors 0 = all
out.writeIntLE(iColorsImportant);
}
}
| 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/thridparty/image4j/ICODecoder.java | released/MyBox/src/main/java/thridparty/image4j/ICODecoder.java | /*
* ICODecoder.java
*
* Created on May 9, 2006, 9:31 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import mara.mybox.dev.MyBoxLog;
/**
* Decodes images in ICO format.
*
* @author Ian McDonagh
*/
// ##### Updated by mara. To avoid crash when the file is invalid
public class ICODecoder {
private static final int PNG_MAGIC = 0x89504E47;
private static final int PNG_MAGIC_LE = 0x474E5089;
private static final int PNG_MAGIC2 = 0x0D0A1A0A;
private static final int PNG_MAGIC2_LE = 0x0A1A0A0D;
// private List<BufferedImage> img;
private ICODecoder() {
}
/**
* Reads and decodes the given ICO file. Convenience method equivalent to
* null null null null null {@link #read(java.io.InputStream) read(new
* java.io.FileInputStream(file))}.
*
* @param file the source file to read
* @return the list of images decoded from the ICO data
*
*/
public static List<BufferedImage> read(File file) {
try {
List<ICOImage> icoList = readExt(file);
if (icoList == null) {
return null;
}
List<BufferedImage> bgList = new ArrayList<>(icoList.size());
for (int i = 0; i < icoList.size(); i++) {
ICOImage icoImage = icoList.get(i);
BufferedImage image = icoImage.getImage();
bgList.add(image);
}
return bgList;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
/**
* Reads and decodes the given ICO file, together with all metadata.
* Convenience method equivalent to {@link #readExt(java.io.InputStream)
* readExt(new java.io.FileInputStream(file))}.
*
* @param file the source file to read
* @return the list of images decoded from the ICO data
* @since 0.7
*/
public static List<ICOImage> readExt(File file) {
if (file == null || !file.exists()) {
return null;
}
try (FileInputStream fin = new FileInputStream(file)) {
return readExt(new BufferedInputStream(fin));
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static List<ICOImage> readExt(java.io.InputStream is) {
if (is == null) {
return null;
}
try (LittleEndianInputStream in
= new LittleEndianInputStream(new CountingInputStream(is))) {
// Count 2 byte Number of Icons in this file
// Reserved 2 byte =0
short sReserved = in.readShortLE();
// Type 2 byte =1
short sType = in.readShortLE();
// Count 2 byte Number of Icons in this file
short sCount = in.readShortLE();
// Entries Count * 16 list of icons
IconEntry[] entries = new IconEntry[sCount];
for (short s = 0; s < sCount; s++) {
entries[s] = new IconEntry(in);
}
// Seems like we don't need this, but you never know!
// entries = sortByFileOffset(entries);
// images list of bitmap structures in BMP/PNG format
List<ICOImage> ret = new ArrayList<>(sCount);
for (int i = 0; i < sCount; i++) {
// Make sure we're at the right file offset!
int fileOffset = in.getCount();
if (fileOffset != entries[i].iFileOffset) {
MyBoxLog.error("Cannot read image #" + i
+ " starting at unexpected file offset.");
return null;
}
int info = in.readIntLE();
// MyBoxLog.console("Image #" + i + " @ " + in.getCount()
// + " info = " + EndianUtils.toInfoString(info));
if (info == 40) {
// read XOR bitmap
// BMPDecoder bmp = new BMPDecoder(is);
InfoHeader infoHeader = BMPDecoder.readInfoHeader(in, info);
InfoHeader andHeader = new InfoHeader(infoHeader);
andHeader.iHeight = (int) (infoHeader.iHeight / 2);
InfoHeader xorHeader = new InfoHeader(infoHeader);
xorHeader.iHeight = andHeader.iHeight;
andHeader.sBitCount = 1;
andHeader.iNumColors = 2;
// for now, just read all the raster data (xor + and)
// and store as separate images
BufferedImage xor = BMPDecoder.read(xorHeader, in);
// If we want to be sure we've decoded the XOR mask
// correctly,
// we can write it out as a PNG to a temp file here.
// try {
// File temp = File.createTempFile("image4j", ".png");
// ImageIO.write(xor, "png", temp);
// log.info("Wrote xor mask for image #" + i + " to "
// + temp.getAbsolutePath());
// } catch (Throwable ex) {
// }
// Or just add it to the output list:
// img.add(xor);
BufferedImage img = new BufferedImage(xorHeader.iWidth,
xorHeader.iHeight, BufferedImage.TYPE_INT_ARGB);
ColorEntry[] andColorTable = new ColorEntry[]{
new ColorEntry(255, 255, 255, 255),
new ColorEntry(0, 0, 0, 0)};
if (infoHeader.sBitCount == 32) {
// transparency from alpha
// ignore bytes after XOR bitmap
int size = entries[i].iSizeInBytes;
int infoHeaderSize = infoHeader.iSize;
// data size = w * h * 4
int dataSize = xorHeader.iWidth * xorHeader.iHeight * 4;
int skip = size - infoHeaderSize - dataSize;
int skip2 = entries[i].iFileOffset + size
- in.getCount();
// ignore AND bitmap since alpha channel stores
// transparency
if (in.skip(skip, false) < skip && i < sCount - 1) {
throw new EOFException("Unexpected end of input");
}
// If we skipped less bytes than expected, the AND mask
// is probably badly formatted.
// If we're at the last/only entry in the file, silently
// ignore and continue processing...
// //read AND bitmap
// BufferedImage and = BMPDecoder.read(andHeader, in,
// andColorTable);
// this.img.add(and);
WritableRaster srgb = xor.getRaster();
WritableRaster salpha = xor.getAlphaRaster();
WritableRaster rgb = img.getRaster();
WritableRaster alpha = img.getAlphaRaster();
for (int y = xorHeader.iHeight - 1; y >= 0; y--) {
for (int x = 0; x < xorHeader.iWidth; x++) {
int r = srgb.getSample(x, y, 0);
int g = srgb.getSample(x, y, 1);
int b = srgb.getSample(x, y, 2);
int a = salpha.getSample(x, y, 0);
rgb.setSample(x, y, 0, r);
rgb.setSample(x, y, 1, g);
rgb.setSample(x, y, 2, b);
alpha.setSample(x, y, 0, a);
}
}
} else {
BufferedImage and = BMPDecoder.read(andHeader, in,
andColorTable);
// img.add(and);
// copy rgb
WritableRaster srgb = xor.getRaster();
WritableRaster rgb = img.getRaster();
// copy alpha
WritableRaster alpha = img.getAlphaRaster();
WritableRaster salpha = and.getRaster();
for (int y = 0; y < xorHeader.iHeight; y++) {
for (int x = 0; x < xorHeader.iWidth; x++) {
int r, g, b;
int c = xor.getRGB(x, y);
r = (c >> 16) & 0xFF;
g = (c >> 8) & 0xFF;
b = (c) & 0xFF;
// red
rgb.setSample(x, y, 0, r);
// green
rgb.setSample(x, y, 1, g);
// blue
rgb.setSample(x, y, 2, b);
// System.out.println(x+","+y+"="+Integer.toHexString(c));
// img.setRGB(x, y, c);
// alpha
int a = and.getRGB(x, y);
alpha.setSample(x, y, 0, a);
}
}
}
// create ICOImage
IconEntry iconEntry = entries[i];
ICOImage icoImage = new ICOImage(img, infoHeader, iconEntry);
icoImage.setPngCompressed(false);
icoImage.setIconIndex(i);
ret.add(icoImage);
} // check for PNG magic header and that image height and width =
// 0 = 256 -> Vista format
else if (info == PNG_MAGIC_LE) {
int info2 = in.readIntLE();
if (info2 != PNG_MAGIC2_LE) {
MyBoxLog.error("Unrecognized icon format for image #" + i);
return null;
}
IconEntry e = entries[i];
int size = e.iSizeInBytes - 8;
byte[] pngData = new byte[size];
/* int count = */
in.readFully(pngData);
// if (count != pngData.length) {
// throw new
// IOException("Unable to read image #"+i+" - incomplete PNG compressed data");
// }
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.DataOutputStream dout = new java.io.DataOutputStream(
bout);
dout.writeInt(PNG_MAGIC);
dout.writeInt(PNG_MAGIC2);
dout.write(pngData);
byte[] pngData2 = bout.toByteArray();
java.io.ByteArrayInputStream bin = new java.io.ByteArrayInputStream(
pngData2);
javax.imageio.stream.ImageInputStream input = javax.imageio.ImageIO
.createImageInputStream(bin);
javax.imageio.ImageReader reader = getPNGImageReader();
reader.setInput(input);
java.awt.image.BufferedImage img = reader.read(0);
// create ICOImage
IconEntry iconEntry = entries[i];
ICOImage icoImage = new ICOImage(img, null, iconEntry);
icoImage.setPngCompressed(true);
icoImage.setIconIndex(i);
ret.add(icoImage);
} else {
MyBoxLog.error("Unrecognized icon format for image #" + i);
return null;
}
/*
* InfoHeader andInfoHeader = new InfoHeader();
* andInfoHeader.iColorsImportant = 0; andInfoHeader.iColorsUsed
* = 0; andInfoHeader.iCompression = BMPConstants.BI_RGB;
* andInfoHeader.iHeight = xorInfoHeader.iHeight / 2;
* andInfoHeader.iWidth = xorInfoHeader.
*/
}
// long t2 = System.currentTimeMillis();
// System.out.println("Loaded ICO file in "+(t2 - t)+"ms");
return ret;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
private static IconEntry[] sortByFileOffset(IconEntry[] entries) {
List<IconEntry> list = Arrays.asList(entries);
Collections.sort(list, new Comparator<IconEntry>() {
@Override
public int compare(IconEntry o1, IconEntry o2) {
return o1.iFileOffset - o2.iFileOffset;
}
});
return list.toArray(new IconEntry[list.size()]);
}
/**
* Reads and decodes ICO data from the given source, together with all
* metadata. The returned list of images is in the order in which they
* appear in the source ICO data.
*
* @param is the source <tt>InputStream</tt> to read
* @return the list of images decoded from the ICO data
* @throws java.io.IOException if an error occurs
* @since 0.7
*/
private static javax.imageio.ImageReader getPNGImageReader() {
javax.imageio.ImageReader ret = null;
java.util.Iterator<javax.imageio.ImageReader> itr = javax.imageio.ImageIO
.getImageReadersByFormatName("png");
if (itr.hasNext()) {
ret = itr.next();
}
return ret;
}
}
| 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/thridparty/image4j/ICOImage.java | released/MyBox/src/main/java/thridparty/image4j/ICOImage.java | /*
* ICOImage.java
*
* Created on February 19, 2007, 8:11 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import thridparty.image4j.InfoHeader;
/**
* Contains a decoded ICO image, as well as information about the source encoded ICO image.
* @since 0.7
* @author Ian McDonagh
*/
public class ICOImage extends thridparty.image4j.BMPImage {
protected IconEntry iconEntry;
protected boolean pngCompressed = false;
protected int iconIndex = -1;
/**
* Creates a new instance of ICOImage
* @param image the BufferedImage decoded from the source ICO image
* @param infoHeader the BMP InfoHeader structure for the BMP encoded ICO image
* @param iconEntry the IconEntry structure describing the ICO image
*/
public ICOImage(java.awt.image.BufferedImage image, thridparty.image4j.InfoHeader infoHeader,
IconEntry iconEntry) {
super(image, infoHeader);
this.iconEntry = iconEntry;
}
/**
* The IconEntry associated with this <tt>ICOImage</tt>, which provides information
* about the image format and encoding.
* @return the IconEntry structure
*/
public IconEntry getIconEntry() {
return iconEntry;
}
/**
* Sets the IconEntry associated with this <tt>ICOImage</tt>.
* @param iconEntry the new IconEntry structure to set
*/
public void setIconEntry(IconEntry iconEntry) {
this.iconEntry = iconEntry;
}
/**
* Specifies whether the encoded image is PNG compressed.
* @return <tt>true</tt> if the encoded image is PNG compressed, <tt>false</tt> if it is plain BMP encoded
*/
public boolean isPngCompressed() {
return pngCompressed;
}
/**
* Sets whether the encoded image is PNG compressed.
* @param pngCompressed <tt>true</tt> if the encoded image is PNG compressed, <tt>false</tt> if it is plain BMP encoded
*/
public void setPngCompressed(boolean pngCompressed) {
this.pngCompressed = pngCompressed;
}
/**
* The InfoHeader structure representing the encoded ICO image.
* @return the InfoHeader structure, or <tt>null</tt> if there is no InfoHeader structure, which is possible for PNG compressed icons.
*/
public InfoHeader getInfoHeader() {
return super.getInfoHeader();
}
/**
* The zero-based index for this <tt>ICOImage</tt> in the source ICO file or resource.
* @return the index in the source, or <tt>-1</tt> if it is unknown.
*/
public int getIconIndex() {
return iconIndex;
}
/**
* Sets the icon index, which is zero-based.
* @param iconIndex the zero-based icon index, or <tt>-1</tt> if unknown.
*/
public void setIconIndex(int iconIndex) {
this.iconIndex = iconIndex;
}
/**
* The width of the ICO image in pixels.
* @return the width of the ICO image, or <tt>-1</tt> if unknown
* @since 0.7alpha2
*/
public int getWidth() {
return iconEntry == null ? -1 : (iconEntry.bWidth == 0 ? 256 : iconEntry.bWidth);
}
/**
* The height of the ICO image in pixels.
* @return the height of the ICO image, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getHeight() {
return iconEntry == null ? -1 : (iconEntry.bHeight == 0 ? 256 : iconEntry.bHeight);
}
/**
* The colour depth of the ICO image (bits per pixel).
* @return the colour depth, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getColourDepth() {
return iconEntry == null ? -1 : iconEntry.sBitCount;
}
/**
* The number of possible colours for the ICO image.
* @return the number of colours, or <tt>-1</tt> if unknown.
* @since 0.7alpha2
*/
public int getColourCount() {
int bpp = iconEntry.sBitCount == 32 ? 24 : iconEntry.sBitCount;
return bpp == -1 ? -1 : (int) (1 << bpp);
}
/**
* Specifies whether this ICO image is indexed, that is, the encoded bitmap uses a colour table.
* If <tt>getColourDepth()</tt> returns <tt>-1</tt>, the return value has no meaning.
* @return <tt>true</tt> if indexed, <tt>false</tt> if not.
* @since 0.7alpha2
*/
public boolean isIndexed() {
return iconEntry == null ? false : iconEntry.sBitCount <= 8;
}
}
| 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/thridparty/image4j/ColorEntry.java | released/MyBox/src/main/java/thridparty/image4j/ColorEntry.java | /*
* ColorEntry.java
*
* Created on 10 May 2006, 08:29
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.io.IOException;
/**
* Represents an RGB colour entry used in the palette of an indexed image (colour depth <= 8).
* @author Ian McDonagh
*/
public class ColorEntry {
/**
* The red component, which should be in the range <tt>0..255</tt>.
*/
public int bRed;
/**
* The green component, which should be in the range <tt>0..255</tt>.
*/
public int bGreen;
/**
* The blue component, which should be in the range <tt>0..255</tt>.
*/
public int bBlue;
/**
* Unused.
*/
public int bReserved;
/**
* Reads and creates a colour entry from the source input.
* @param in the source input
* @throws java.io.IOException if an error occurs
*/
public ColorEntry(thridparty.image4j.LittleEndianInputStream in) throws IOException {
bBlue = in.readUnsignedByte();
bGreen = in.readUnsignedByte();
bRed = in.readUnsignedByte();
bReserved = in.readUnsignedByte();
}
/**
* Creates a colour entry with colour components initialized to <tt>0</tt>.
*/
public ColorEntry() {
bBlue = 0;
bGreen = 0;
bRed = 0;
bReserved = 0;
}
/**
* Creates a colour entry with the specified colour components.
* @param r red component
* @param g green component
* @param b blue component
* @param a unused
*/
public ColorEntry(int r, int g, int b, int a) {
bBlue = b;
bGreen = g;
bRed = r;
bReserved = 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/thridparty/image4j/LittleEndianOutputStream.java | released/MyBox/src/main/java/thridparty/image4j/LittleEndianOutputStream.java | /*
* LittleEndianOutputStream.java
*
* Created on 07 November 2006, 08:26
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Writes little-endian data to a target <tt>OutputStream</tt> by reversing byte ordering.
* @author Ian McDonagh
*/
public class LittleEndianOutputStream extends DataOutputStream {
/**
* Creates a new instance of <tt>LittleEndianOutputStream</tt>, which will write to the specified target.
* @param out the target <tt>OutputStream</tt>
*/
public LittleEndianOutputStream(java.io.OutputStream out) {
super(out);
}
/**
* Writes a little-endian <tt>short</tt> value
* @param value the source value to convert
* @throws java.io.IOException if an error occurs
*/
public void writeShortLE(short value) throws IOException {
value = EndianUtils.swapShort(value);
super.writeShort(value);
}
/**
* Writes a little-endian <tt>int</tt> value
* @param value the source value to convert
* @throws java.io.IOException if an error occurs
*/
public void writeIntLE(int value) throws IOException {
value = EndianUtils.swapInteger(value);
super.writeInt(value);
}
/**
* Writes a little-endian <tt>float</tt> value
* @param value the source value to convert
* @throws java.io.IOException if an error occurs
*/
public void writeFloatLE(float value) throws IOException {
value = EndianUtils.swapFloat(value);
super.writeFloat(value);
}
/**
* Writes a little-endian <tt>long</tt> value
* @param value the source value to convert
* @throws java.io.IOException if an error occurs
*/
public void writeLongLE(long value) throws IOException {
value = EndianUtils.swapLong(value);
super.writeLong(value);
}
/**
* Writes a little-endian <tt>double</tt> value
* @param value the source value to convert
* @throws java.io.IOException if an error occurs
*/
public void writeDoubleLE(double value) throws IOException {
value = EndianUtils.swapDouble(value);
super.writeDouble(value);
}
/**
* @since 0.6
*/
public void writeUnsignedInt(long value) throws IOException {
int i1 = (int)(value >> 24);
int i2 = (int)((value >> 16) & 0xFF);
int i3 = (int)((value >> 8) & 0xFF);
int i4 = (int)(value & 0xFF);
write(i1);
write(i2);
write(i3);
write(i4);
}
/**
* @since 0.6
*/
public void writeUnsignedIntLE(long value) throws IOException {
int i1 = (int)(value >> 24);
int i2 = (int)((value >> 16) & 0xFF);
int i3 = (int)((value >> 8) & 0xFF);
int i4 = (int)(value & 0xFF);
write(i4);
write(i3);
write(i2);
write(i1);
}
}
| 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/thridparty/image4j/ImageUtil.java | released/MyBox/src/main/java/thridparty/image4j/ImageUtil.java | /*
* ImageUtil.java
*
* Created on 15 May 2006, 01:12
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package thridparty.image4j;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
/**
* Provides utility methods for handling images (<tt>java.awt.BufferedImage</tt>)
* @author Ian McDonagh
*/
public class ImageUtil {
/**
* Creates a scaled copy of the source image.
* @param src source image to be scaled
* @param width the width for the new scaled image in pixels
* @param height the height for the new scaled image in pixels
* @return a copy of the source image scaled to <tt>width</tt> x <tt>height</tt> pixels.
*/
public static BufferedImage scaleImage(BufferedImage src, int width, int height) {
Image scaled = src.getScaledInstance(width, height, 0);
BufferedImage ret = null;
/*
ColorModel cm = src.getColorModel();
if (cm instanceof IndexColorModel) {
ret = new BufferedImage(
width, height, src.getType(), (IndexColorModel) cm
);
}
else {
ret = new BufferedImage(
src.getWidth(), src.getHeight(), src.getType()
);
}
Graphics2D g = ret.createGraphics();
//clear alpha channel
Composite comp = g.getComposite();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
Rectangle2D.Double d = new Rectangle2D.Double(0,0,ret.getWidth(),ret.getHeight());
g.fill(d);
g.setComposite(comp);
*/
ret = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = ret.createGraphics();
//copy image
g.drawImage(scaled, 0, 0, null);
return ret;
}
}
| 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/thridparty/image4j/CountingInputStream.java | released/MyBox/src/main/java/thridparty/image4j/CountingInputStream.java | package thridparty.image4j;
import java.io.*;
public class CountingInputStream extends FilterInputStream {
private int count;
public CountingInputStream(InputStream src) {
super(src);
}
public int getCount() {
return count;
}
@Override
public int read() throws IOException {
int b = super.read();
if (b != -1) {
count++;
}
return b;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r > 0) {
count += r;
}
return r;
}
}
| 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/thridparty/image4j/CountingDataInput.java | released/MyBox/src/main/java/thridparty/image4j/CountingDataInput.java | package thridparty.image4j;
import java.io.DataInput;
public interface CountingDataInput extends DataInput, CountingInput {
}
| 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/thridparty/image4j/EndianUtils.java | released/MyBox/src/main/java/thridparty/image4j/EndianUtils.java | package thridparty.image4j;
/**
* Provides utility methods for endian conversions [big-endian to little-endian;
* little-endian to big-endian].
*
* @author Ian McDonagh
*/
public class EndianUtils {
/**
* Reverses the byte order of the source <tt>short</tt> value
*
* @param value
* the source value
* @return the converted value
*/
public static short swapShort(short value) {
return (short) (((value & 0xFF00) >> 8) | ((value & 0x00FF) << 8));
}
/**
* Reverses the byte order of the source <tt>int</tt> value
*
* @param value
* the source value
* @return the converted value
*/
public static int swapInteger(int value) {
return ((value & 0xFF000000) >> 24) | ((value & 0x00FF0000) >> 8)
| ((value & 0x0000FF00) << 8) | ((value & 0x000000FF) << 24);
}
/**
* Reverses the byte order of the source <tt>long</tt> value
*
* @param value
* the source value
* @return the converted value
*/
public static long swapLong(long value) {
return ((value & 0xFF00000000000000L) >> 56)
| ((value & 0x00FF000000000000L) >> 40)
| ((value & 0x0000FF0000000000L) >> 24)
| ((value & 0x000000FF00000000L) >> 8)
| ((value & 0x00000000FF000000L) << 8)
| ((value & 0x0000000000FF0000L) << 24)
| ((value & 0x000000000000FF00L) << 40)
| ((value & 0x00000000000000FFL) << 56);
}
/**
* Reverses the byte order of the source <tt>float</tt> value
*
* @param value
* the source value
* @return the converted value
*/
public static float swapFloat(float value) {
int i = Float.floatToIntBits(value);
i = swapInteger(i);
return Float.intBitsToFloat(i);
}
/**
* Reverses the byte order of the source <tt>double</tt> value
*
* @param value
* the source value
* @return the converted value
*/
public static double swapDouble(double value) {
long l = Double.doubleToLongBits(value);
l = swapLong(l);
return Double.longBitsToDouble(l);
}
public static String toHexString(int i, boolean littleEndian, int bytes) {
if (littleEndian) {
i = swapInteger(i);
}
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(i));
if (sb.length() % 2 != 0) {
sb.insert(0, '0');
}
while (sb.length() < bytes * 2) {
sb.insert(0, "00");
}
return sb.toString();
}
public static StringBuilder toCharString(StringBuilder sb, int i, int bytes, char def) {
int shift = 24;
for (int j = 0; j < bytes; j++) {
int b = (i >> shift) & 0xFF;
char c = b < 32 ? def : (char) b;
sb.append(c);
shift -= 8;
}
return sb;
}
public static String toInfoString(int info) {
StringBuilder sb = new StringBuilder();
sb.append("Decimal: ").append(info);
sb.append(", Hex BE: ").append(toHexString(info, false, 4));
sb.append(", Hex LE: ").append(toHexString(info, true, 4));
sb.append(", String BE: [");
sb = toCharString(sb, info, 4, '.');
sb.append(']');
sb.append(", String LE: [");
sb = toCharString(sb, swapInteger(info), 4, '.');
sb.append(']');
return sb.toString();
}
} | java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.