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/image/file/ImageBmpFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageBmpFile.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.bmp.BMPImageReader;
import com.github.jaiimageio.impl.plugins.bmp.BMPImageReaderSpi;
import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriter;
import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriterSpi;
import com.github.jaiimageio.impl.plugins.bmp.BMPMetadata;
import com.github.jaiimageio.plugins.bmp.BMPImageWriteParam;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.tools.ImageConvertTools;
import static mara.mybox.image.tools.ImageConvertTools.dpi2dpm;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2018-6-19
* @Description
* @License Apache License Version 2.0
*/
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/bmp_metadata.html
public class ImageBmpFile {
public static String[] getBmpCompressionTypes() {
return new BMPImageWriteParam(null).getCompressionTypes();
}
public static ImageWriter getWriter() {
// BMP's meta data can not be modified and read correctly if standard classes are used.
// So classes in plugins are used.
BMPImageWriterSpi spi = new BMPImageWriterSpi();
BMPImageWriter writer = new BMPImageWriter(spi);
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
BMPImageWriteParam param = (BMPImageWriteParam) writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
}
if (attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
BMPMetadata metaData = (BMPMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metaData != null && !metaData.isReadOnly() && attributes != null && attributes.getDensity() > 0) {
String format = metaData.getNativeMetadataFormatName(); // "com_sun_media_imageio_plugins_bmp_image_1.0"
int dpm = dpi2dpm(attributes.getDensity());
// If set nodes' attributes in normal way, error will be popped about "Meta Data is read only"
// By setting its fields, the class will write resolution data under standard format "javax_imageio_1.0"
// but leave itself's section as empty~ Anyway, the data is record.
metaData.xPixelsPerMeter = dpm;
metaData.yPixelsPerMeter = dpm;
metaData.palette = null; // Error will happen if not define this for Black-white bmp.
IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(format);
metaData.mergeTree(format, tree);
}
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static boolean writeBmpImageFile(FxTask task, BufferedImage srcimage,
ImageAttributes attributes, File file) {
BufferedImage image = AlphaTools.removeAlpha(task, srcimage);
try {
ImageWriter writer = getWriter();
ImageWriteParam param = getPara(attributes, writer);
IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(metaData, new IIOImage(image, null, metaData), param);
out.flush();
}
writer.dispose();
return FileTools.override(tmpFile, file);
} catch (Exception e) {
try {
return ImageIO.write(image, attributes.getImageFormat(), file);
} catch (Exception e2) {
return false;
}
}
}
public static BMPMetadata getBmpIIOMetadata(File file) {
try {
BMPImageReader reader = new BMPImageReader(new BMPImageReaderSpi());
try (ImageInputStream iis = ImageIO.createImageInputStream(file)) {
reader.setInput(iis, false);
BMPMetadata metadata = (BMPMetadata) reader.getImageMetadata(0);
reader.dispose();
return metadata;
}
} catch (Exception e) {
// MyBoxLog.error(e.toString());
return null;
}
}
public static void explainBmpMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData,
ImageInformation info) {
try {
String format = "com_sun_media_imageio_plugins_bmp_image_1.0";
if (!metaData.containsKey(format)) {
return;
}
Map<String, List<Map<String, Object>>> javax_imageio_bmp = metaData.get(format);
if (javax_imageio_bmp.containsKey("Width")) {
Map<String, Object> Width = javax_imageio_bmp.get("Width").get(0);
if (Width.containsKey("value")) {
info.setWidth(Integer.parseInt((String) Width.get("value")));
}
}
if (javax_imageio_bmp.containsKey("Height")) {
Map<String, Object> Height = javax_imageio_bmp.get("Height").get(0);
if (Height.containsKey("value")) {
info.setHeight(Integer.parseInt((String) Height.get("value")));
}
}
if (javax_imageio_bmp.containsKey("X")) { // PixelsPerMeter
Map<String, Object> X = javax_imageio_bmp.get("X").get(0);
if (X.containsKey("value")) {
info.setXDpi(ImageConvertTools.dpm2dpi(Integer.parseInt((String) X.get("value"))));
}
}
if (javax_imageio_bmp.containsKey("Y")) { // PixelsPerMeter
Map<String, Object> Y = javax_imageio_bmp.get("Y").get(0);
if (Y.containsKey("value")) {
info.setYDpi(ImageConvertTools.dpm2dpi(Integer.parseInt((String) Y.get("value"))));
}
}
if (javax_imageio_bmp.containsKey("BitsPerPixel")) {
Map<String, Object> BitsPerPixel = javax_imageio_bmp.get("BitsPerPixel").get(0);
if (BitsPerPixel.containsKey("value")) {
info.setBitDepth(Integer.parseInt((String) BitsPerPixel.get("value")));
}
}
if (javax_imageio_bmp.containsKey("Compression")) {
Map<String, Object> Compression = javax_imageio_bmp.get("Compression").get(0);
if (Compression.containsKey("value")) {
info.setCompressionType((String) Compression.get("value"));
}
}
} catch (Exception e) {
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageRawFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageRawFile.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.raw.RawImageReader;
import com.github.jaiimageio.impl.plugins.raw.RawImageReaderSpi;
import com.github.jaiimageio.impl.plugins.raw.RawImageWriteParam;
import com.github.jaiimageio.impl.plugins.raw.RawImageWriter;
import com.github.jaiimageio.impl.plugins.raw.RawImageWriterSpi;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.FileTmpTools;
/**
* @Author Mara
* @CreateDate 2018-6-19
*
* @Description
* @License Apache License Version 2.0
*/
public class ImageRawFile {
public static ImageWriter getWriter() {
RawImageWriterSpi spi = new RawImageWriterSpi();
RawImageWriter writer = new RawImageWriter(spi);
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
RawImageWriteParam param = (RawImageWriteParam) writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
return writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static boolean writeRawImageFile(BufferedImage image,
ImageAttributes attributes, File file) {
try {
if (file == null) {
return false;
}
ImageWriter writer = getWriter();
ImageWriteParam param = getPara(attributes, writer);
IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(null, new IIOImage(image, null, metaData), param);
out.flush();
}
writer.dispose();
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static BufferedImage readRawData(File file) {
try {
RawImageReaderSpi tiffspi = new RawImageReaderSpi();
RawImageReader reader = new RawImageReader(tiffspi);
byte[] rawData;
try ( BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file))) {
rawData = new byte[fileInput.available()];
fileInput.read(rawData);
fileInput.close();
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(rawData);
reader.setInput(in);
}
return reader.read(0);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static File readRawData2(File file) {
try {
byte[] rawData;
try ( BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file))) {
rawData = new byte[fileInput.available()];
fileInput.read(rawData);
}
BufferedImage image;
try ( InputStream in = new ByteArrayInputStream(rawData)) {
image = ImageIO.read(in);
}
File newFile = new File(file.getPath() + ".png");
ImageIO.write(image, "png", newFile);
return newFile;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageWbmpFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageWbmpFile.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.wbmp.WBMPImageReader;
import com.github.jaiimageio.impl.plugins.wbmp.WBMPImageReaderSpi;
import com.github.jaiimageio.impl.plugins.wbmp.WBMPMetadata;
import java.io.File;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2018-6-24
* @Description
* @License Apache License Version 2.0
*/
public class ImageWbmpFile {
public static WBMPMetadata getWbmpMetadata(File file) {
try {
WBMPMetadata metadata;
WBMPImageReader reader = new WBMPImageReader(new WBMPImageReaderSpi());
try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) {
reader.setInput(iis, false);
metadata = (WBMPMetadata) reader.getImageMetadata(0);
reader.dispose();
}
return metadata;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageFileWriters.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageFileWriters.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.gif.GIFImageMetadata;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.data.ImageBinary;
import mara.mybox.image.data.ImageFileInformation;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.FileExtensions;
import static mara.mybox.value.Languages.message;
import thridparty.image4j.ICOEncoder;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
*
* @Description
* @License Apache License Version 2.0
*/
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html
public class ImageFileWriters {
public static boolean saveAs(FxTask task, File srcFile, String targetFile) {
try {
BufferedImage image = ImageFileReaders.readImage(task, srcFile);
if (image == null) {
return false;
}
return writeImageFile(task, image, targetFile);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean saveAs(FxTask task, File srcFile, File targetFile) {
try {
return saveAs(task, srcFile, targetFile.getAbsolutePath());
} catch (Exception e) {
return false;
}
}
public static boolean writeImageFile(FxTask task, BufferedImage image, File targetFile) {
try {
return writeImageFile(task, image, targetFile.getAbsolutePath());
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean writeImageFile(FxTask task, BufferedImage image, String targetFile) {
try {
return writeImageFile(task, image, FileNameTools.ext(targetFile), targetFile);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean writeImageFile(FxTask task, BufferedImage image,
String format, String targetFile) {
if (image == null || targetFile == null) {
return false;
}
try {
if (format == null || !FileExtensions.SupportedImages.contains(format)) {
format = FileNameTools.ext(targetFile);
}
format = format.toLowerCase();
ImageAttributes attributes = new ImageAttributes(image, format);
switch (format) {
case "jpx":
case "jpeg2000":
case "jpeg 2000":
case "jp2":
case "jpm":
return ImageIO.write(AlphaTools.removeAlpha(task, image), "JPEG2000", new File(targetFile));
case "wbmp":
image = ImageBinary.byteBinary(task, image);
break;
}
return writeImageFile(task, image, attributes, targetFile);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static ImageAttributes attributes(BufferedImage image, String format) {
try {
if (format == null || !FileExtensions.SupportedImages.contains(format)) {
format = "png";
}
format = format.toLowerCase();
ImageAttributes attributes = new ImageAttributes();
attributes.setImageFormat(format);
switch (format) {
case "jpg":
case "jpeg":
attributes.setCompressionType("JPEG");
break;
case "gif":
attributes.setCompressionType("LZW");
break;
case "tif":
case "tiff":
if (image != null && image.getType() == BufferedImage.TYPE_BYTE_BINARY) {
attributes.setCompressionType("CCITT T.6");
} else {
attributes.setCompressionType("Deflate");
}
break;
case "bmp":
attributes.setCompressionType("BI_RGB");
break;
}
attributes.setQuality(100);
return attributes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
// Not convert color space
public static boolean writeImageFile(FxTask task, BufferedImage srcImage,
ImageAttributes attributes, String targetFile) {
if (srcImage == null || targetFile == null) {
return false;
}
if (attributes == null) {
return writeImageFile(task, srcImage, targetFile);
}
try {
String targetFormat = attributes.getImageFormat().toLowerCase();
if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) {
return writeIcon(task, srcImage, attributes.getWidth(), new File(targetFile));
}
BufferedImage targetImage = AlphaTools.checkAlpha(task, srcImage, targetFormat);
if (targetImage == null || (task != null && !task.isWorking())) {
return false;
}
ImageWriter writer = getWriter(targetFormat);
ImageWriteParam param = getWriterParam(attributes, writer);
IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, targetImage, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(metaData, new IIOImage(targetImage, null, metaData), param);
out.flush();
writer.dispose();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
if (task != null && !task.isWorking()) {
return false;
}
File file = new File(targetFile);
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static boolean writeIcon(FxTask task, BufferedImage image, int width, File targetFile) {
try {
if (image == null || targetFile == null) {
return false;
}
int targetWidth = width;
if (targetWidth <= 0) {
targetWidth = Math.min(512, image.getWidth());
}
BufferedImage scaled = ScaleTools.scaleImageWidthKeep(image, targetWidth);
if (task != null && !task.isWorking()) {
return false;
}
ICOEncoder.write(scaled, targetFile);
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static String writeFrame(FxTask task, File sourcefile, int frameIndex, BufferedImage frameImage) {
return writeFrame(task, sourcefile, frameIndex, frameImage, sourcefile, null);
}
// Convert color space if inAttributes is not null
public static String writeFrame(FxTask task, File sourcefile, int frameIndex, BufferedImage frameImage,
File targetFile, ImageAttributes inAttributes) {
try {
if (frameImage == null || sourcefile == null || !sourcefile.exists()
|| targetFile == null || frameIndex < 0) {
return "InvalidParameters";
}
String targetFormat;
ImageAttributes targetAttributes = inAttributes;
if (targetAttributes == null) {
targetFormat = FileNameTools.ext(targetFile.getName()).toLowerCase();
targetAttributes = attributes(frameImage, targetFormat);
} else {
targetFormat = inAttributes.getImageFormat().toLowerCase();
}
if (!FileExtensions.MultiFramesImages.contains(targetFormat)) {
return writeImageFile(task, frameImage, targetAttributes, targetFile.getAbsolutePath()) ? null : "Failed";
}
List<ImageInformation> gifInfos = null;
if ("gif".equals(targetFormat)) {
ImageFileInformation imageFileInformation = ImageFileReaders.readImageFileMetaData(task, sourcefile);
if (task != null && !task.isWorking()) {
return message("Cancelled");
}
if (imageFileInformation == null || imageFileInformation.getImagesInformation() == null) {
return "InvalidData";
}
gifInfos = imageFileInformation.getImagesInformation();
}
File tmpFile = FileTmpTools.getTempFile();
try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(sourcefile)))) {
ImageReader reader = ImageFileReaders.getReader(iis, FileNameTools.ext(sourcefile.getName()));
if (reader == null) {
return "InvalidData";
}
reader.setInput(iis, false);
int size = reader.getNumImages(true);
try (ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)))) {
int readIndex = 0, duration;
ImageWriter writer = getWriter(targetFormat);
if (writer == null) {
return "InvalidData";
}
writer.setOutput(out);
ImageWriteParam param = getWriterParam(targetAttributes, writer);
writer.prepareWriteSequence(null);
ImageInformation info = new ImageInformation(sourcefile);
while (readIndex < size) {
if (task != null && !task.isWorking()) {
writer.dispose();
reader.dispose();
return message("Cancelled");
}
BufferedImage bufferedImage;
if (readIndex == frameIndex) {
bufferedImage = frameImage;
} else {
try {
bufferedImage = reader.read(readIndex);
} catch (Exception e) {
if (e.toString().contains("java.lang.IndexOutOfBoundsException")) {
break;
}
bufferedImage = ImageFileReaders.readBrokenImage(task, e, info.setIndex(readIndex));
}
}
if (task != null && !task.isWorking()) {
writer.dispose();
reader.dispose();
return message("Cancelled");
}
if (bufferedImage == null) {
break;
}
BufferedImage targetFrame = bufferedImage;
IIOMetadata metaData;
if (inAttributes != null) {
targetFrame = ImageConvertTools.convertColorSpace(task, targetFrame, inAttributes);
} else {
targetFrame = AlphaTools.checkAlpha(task, bufferedImage, targetFormat);
}
if (task != null && !task.isWorking()) {
writer.dispose();
reader.dispose();
return message("Cancelled");
}
if (targetFrame == null) {
break;
}
metaData = getWriterMetaData(targetFormat, targetAttributes, targetFrame, writer, param);
if (gifInfos != null) {
duration = 500;
try {
Object d = gifInfos.get(readIndex).getNativeAttribute("delayTime");
if (d != null) {
duration = Integer.parseInt((String) d) * 10;
}
} catch (Exception e) {
}
GIFImageMetadata gifMetaData = (GIFImageMetadata) metaData;
ImageGifFile.getParaMeta(duration, true, param, gifMetaData);
}
writer.writeToSequence(new IIOImage(targetFrame, null, metaData), param);
readIndex++;
}
writer.endWriteSequence();
out.flush();
writer.dispose();
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
reader.dispose();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return e.toString();
}
if (task != null && !task.isWorking()) {
return message("Cancelled");
}
if (FileTools.override(tmpFile, targetFile)) {
return null;
} else {
return "Failed";
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
return e.toString();
}
}
public static ImageWriter getWriter(String targetFormat) {
if (targetFormat == null) {
return null;
}
try {
ImageWriter writer;
switch (targetFormat.toLowerCase()) {
case "png":
writer = ImagePngFile.getWriter();
break;
case "jpg":
case "jpeg":
writer = ImageJpgFile.getWriter();
break;
case "tif":
case "tiff":
writer = ImageTiffFile.getWriter();
break;
case "raw":
writer = ImageRawFile.getWriter();
break;
case "bmp":
writer = ImageBmpFile.getWriter();
break;
case "gif":
writer = ImageGifFile.getWriter();
break;
default:
return ImageIO.getImageWritersByFormatName(targetFormat).next();
}
return writer;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ImageWriteParam getWriterParam(ImageAttributes attributes, ImageWriter writer) {
try {
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
} else {
String[] compressionTypes = param.getCompressionTypes();
if (compressionTypes != null) {
param.setCompressionType(compressionTypes[0]);
}
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMetaData(String targetFormat,
ImageAttributes attributes, BufferedImage image, ImageWriter writer,
ImageWriteParam param) {
try {
IIOMetadata metaData;
switch (targetFormat) {
case "png":
metaData = ImagePngFile.getWriterMeta(attributes, image, writer, param);
break;
case "gif":
metaData = ImageGifFile.getWriterMeta(attributes, image, writer, param);
break;
case "jpg":
case "jpeg":
metaData = ImageJpgFile.getWriterMeta(attributes, image, writer, param);
break;
case "tif":
case "tiff":
metaData = ImageTiffFile.getWriterMeta(attributes, image, writer, param);
break;
case "bmp":
metaData = ImageBmpFile.getWriterMeta(attributes, image, writer, param);
break;
default:
metaData = getWriterMetaData(attributes, image, writer, param);
}
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMetaData(ImageAttributes attributes,
BufferedImage image, ImageWriter writer, ImageWriteParam param) {
try {
IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metaData == null || metaData.isReadOnly() || attributes == null
|| !metaData.isStandardMetadataFormatSupported()) {
return metaData;
}
// This standard mothod does not write density into meta data of the image.
// If density data need be written, then use methods defined for different image format but not this method.
if (attributes.getDensity() > 0) {
try {
float pixelSizeMm = 25.4f / attributes.getDensity();
String metaFormat = IIOMetadataFormatImpl.standardMetadataFormatName; // "javax_imageio_1.0"
IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(metaFormat);
IIOMetadataNode Dimension = new IIOMetadataNode("Dimension");
IIOMetadataNode HorizontalPixelSize = new IIOMetadataNode("HorizontalPixelSize");
HorizontalPixelSize.setAttribute("value", pixelSizeMm + "");
Dimension.appendChild(HorizontalPixelSize);
IIOMetadataNode VerticalPixelSize = new IIOMetadataNode("VerticalPixelSize");
VerticalPixelSize.setAttribute("value", pixelSizeMm + "");
Dimension.appendChild(VerticalPixelSize);
tree.appendChild(Dimension);
metaData.mergeTree(metaFormat, tree);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageFileReaders.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageFileReaders.java | package mara.mybox.image.file;
import java.awt.Rectangle;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.data.ImageColor;
import static mara.mybox.image.tools.ImageConvertTools.pixelSizeMm2dpi;
import mara.mybox.image.data.ImageFileInformation;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.color.ColorBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.AppVariables.ImageHints;
import static mara.mybox.value.Languages.message;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import thridparty.image4j.ICODecoder;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @License Apache License Version 2.0
*/
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html
public class ImageFileReaders {
public static ImageReader getReader(ImageInputStream iis, String format) {
try {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers == null || !readers.hasNext()) {
return getReader(format);
}
return getReader(readers);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static ImageReader getReader(String format) {
try {
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format.toLowerCase());
return getReader(readers);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static ImageReader getReader(Iterator<ImageReader> readers) {
try {
if (readers == null || !readers.hasNext()) {
return null;
}
ImageReader reader = null;
while (readers.hasNext()) {
reader = readers.next();
if (!reader.getClass().toString().contains("TIFFImageReader")
|| reader instanceof com.github.jaiimageio.impl.plugins.tiff.TIFFImageReader) {
return reader;
}
}
return reader;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static BufferedImage readImage(FxTask task, File file) {
ImageInformation readInfo = new ImageInformation(file);
return readFrame(task, readInfo);
}
public static BufferedImage readImage(FxTask task, File file, int width) {
ImageInformation imageInfo = new ImageInformation(file);
imageInfo.setRequiredWidth(width);
return readFrame(task, imageInfo);
}
public static BufferedImage readFrame(FxTask task, File file, int index) {
ImageInformation imageInfo = new ImageInformation(file);
imageInfo.setIndex(index);
return readFrame(task, imageInfo);
}
public static BufferedImage readFrame(FxTask task, ImageInformation imageInfo) {
if (imageInfo == null) {
return null;
}
File file = imageInfo.getFile();
if (file == null) {
return null;
}
String format = imageInfo.getImageFormat();
if (task != null) {
task.setInfo(message("File") + ": " + file);
task.setInfo(message("FileSize") + ": " + FileTools.showFileSize(file.length()));
task.setInfo(message("Format") + ": " + format);
}
if ("ico".equals(format) || "icon".equals(format)) {
return readIcon(task, imageInfo);
}
BufferedImage bufferedImage = null;
try (ImageInputStream iis = ImageIO.createImageInputStream(
new BufferedInputStream(new FileInputStream(file)))) {
ImageReader reader = getReader(iis, format);
if (reader == null) {
return null;
}
reader.setInput(iis, true, true);
if (task != null && !task.isWorking()) {
return null;
}
bufferedImage = readFrame(task, reader, imageInfo);
reader.dispose();
} catch (Exception e) {
imageInfo.setError(e.toString());
}
return bufferedImage;
}
public static BufferedImage readFrame(FxTask task, ImageReader reader, ImageInformation imageInfo) {
if (reader == null || imageInfo == null) {
return null;
}
try {
double infoWidth = imageInfo.getWidth();
double requiredWidth = imageInfo.getRequiredWidth();
ImageReadParam param = reader.getDefaultReadParam();
Rectangle region = imageInfo.getIntRegion();
int xscale = imageInfo.getXscale();
if (xscale < 1) {
xscale = 1;
}
int yscale = imageInfo.getYscale();
if (yscale < 1) {
yscale = 1;
}
if (region != null) {
param.setSourceRegion(region);
if (task != null) {
task.setInfo(message("Region") + ": " + region.toString());
}
} else if (requiredWidth > 0 && infoWidth > requiredWidth && xscale <= 1 && yscale <= 1) {
xscale = (int) Math.ceil(infoWidth / requiredWidth);
yscale = xscale;
}
if (xscale > 1 || yscale > 1) {
param.setSourceSubsampling(xscale, yscale, 0, 0);
if (task != null) {
task.setInfo(message("Scale") + ": " + " xscale=" + xscale + " yscale= " + yscale);
}
} else if (region == null) {
ImageInformation.checkMem(task, imageInfo);
int sampleScale = imageInfo.getSampleScale();
if (sampleScale > 1) {
if (task != null) {
task.setInfo("sampleScale: " + sampleScale);
}
return null;
}
}
BufferedImage bufferedImage;
try {
if (task != null) {
task.setInfo(message("Reading") + ": " + message("Frame") + " " + imageInfo.getIndex());
}
bufferedImage = reader.read(imageInfo.getIndex(), param);
if (bufferedImage == null) {
return null;
}
if (task != null && !task.isWorking()) {
return null;
}
imageInfo.setImageType(bufferedImage.getType());
if (requiredWidth > 0 && bufferedImage.getWidth() != requiredWidth) {
if (task != null) {
task.setInfo(message("Scale") + ": " + message("Width") + " " + requiredWidth);
}
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, (int) requiredWidth);
} else if (ImageHints != null) {
bufferedImage = BufferedImageTools.applyRenderHints(bufferedImage, ImageHints);
}
return bufferedImage;
} catch (Exception e) {
if (task != null) {
task.setInfo(message("Error") + ": " + e.toString());
}
return readBrokenImage(task, e, imageInfo);
}
} catch (Exception e) {
imageInfo.setError(e.toString());
return null;
}
}
public static ImageInformation makeInfo(FxTask task, File file, int width) {
ImageInformation readInfo = new ImageInformation(file);
readInfo.setRequiredWidth(width);
return makeInfo(task, readInfo, false);
}
public static ImageInformation makeInfo(FxTask task, ImageInformation readInfo, boolean onlyInformation) {
try {
if (readInfo == null) {
return null;
}
File file = readInfo.getFile();
if (file == null) {
return null;
}
ImageFileInformation fileInfo = null;
ImageInformation imageInfo = null;
int index = readInfo.getIndex();
int requiredWidth = (int) readInfo.getRequiredWidth();
if (task != null) {
task.setInfo(message("File") + ": " + file);
task.setInfo(message("FileSize") + ": " + FileTools.showFileSize(file.length()));
task.setInfo(message("Frame") + ": " + (index + 1));
if (requiredWidth > 0) {
task.setInfo(message("LoadWidth") + ": " + requiredWidth);
}
}
String format = readInfo.getImageFormat();
if ("ico".equals(format) || "icon".equals(format)) {
if (fileInfo == null) {
fileInfo = new ImageFileInformation(file);
ImageFileReaders.readImageFileMetaData(task, null, fileInfo);
}
if (task != null && !task.isWorking()) {
return null;
}
if (fileInfo.getImagesInformation() == null) {
return null;
}
int framesNumber = fileInfo.getImagesInformation().size();
if (task != null) {
task.setInfo(message("FramesNumber") + ": " + framesNumber);
}
if (framesNumber > 0 && index < framesNumber) {
imageInfo = fileInfo.getImagesInformation().get(index);
if (task != null) {
task.setInfo(message("Pixels") + ": " + (int) imageInfo.getWidth() + "x" + (int) imageInfo.getHeight());
}
if (!onlyInformation) {
if (task != null) {
task.setInfo(message("Reading") + ": " + message("Frame")
+ " " + index + "/" + framesNumber);
}
imageInfo.setRequiredWidth(requiredWidth);
BufferedImage bufferedImage = readIcon(task, imageInfo);
if (task != null && !task.isWorking()) {
return null;
}
imageInfo.loadBufferedImage(bufferedImage);
}
}
} else {
try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) {
ImageReader reader = getReader(iis, format);
if (reader != null) {
reader.setInput(iis, false, false);
fileInfo = new ImageFileInformation(file);
if (task != null) {
task.setInfo(message("Reading") + ": " + message("MetaData"));
}
ImageFileReaders.readImageFileMetaData(task, reader, fileInfo);
if (task != null && !task.isWorking()) {
return null;
}
if (fileInfo.getImagesInformation() == null) {
return null;
}
int framesNumber = fileInfo.getImagesInformation().size();
if (task != null) {
task.setInfo(message("FramesNumber") + ": " + framesNumber);
}
if (framesNumber > 0 && index < framesNumber) {
imageInfo = fileInfo.getImagesInformation().get(index);
if (task != null) {
task.setInfo(message("Pixels") + ": " + (int) imageInfo.getWidth() + "x" + (int) imageInfo.getHeight());
}
if (!onlyInformation) {
if (task != null) {
task.setInfo(message("Reading") + ": " + message("Frame")
+ " " + index + "/" + framesNumber);
}
imageInfo.setRequiredWidth(requiredWidth);
BufferedImage bufferedImage = readFrame(task, reader, imageInfo);
if (task != null && !task.isWorking()) {
return null;
}
imageInfo.loadBufferedImage(bufferedImage);
}
}
reader.dispose();
} else {
if (task != null) {
task.setError("Fail to get reader");
}
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return null;
}
}
return imageInfo;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return null;
}
}
public static BufferedImage readIcon(FxTask task, File srcFile) {
return readIcon(task, srcFile, 0);
}
public static BufferedImage readIcon(FxTask task, File srcFile, int index) {
try {
if (srcFile == null || !srcFile.exists()) {
return null;
}
List<BufferedImage> frames = ICODecoder.read(srcFile);
if (frames == null || frames.isEmpty()) {
return null;
}
return frames.get(index >= 0 && index < frames.size() ? index : 0);
} catch (Exception e) {
String ex = e.toString() + ": " + srcFile;
if (task != null) {
task.setError(ex);
} else {
MyBoxLog.error(ex);
}
return null;
}
}
public static BufferedImage readIcon(FxTask task, ImageInformation imageInfo) {
try {
BufferedImage bufferedImage = readIcon(task, imageInfo.getFile(), imageInfo.getIndex());
if (task != null && !task.isWorking()) {
return null;
}
return adjust(task, imageInfo, bufferedImage);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return null;
}
}
// call this only when region and scale is not handled when create bufferedImage
public static BufferedImage adjust(FxTask task, ImageInformation imageInfo, BufferedImage bufferedImage) {
try {
if (imageInfo == null || bufferedImage == null) {
return bufferedImage;
}
int requiredWidth = (int) imageInfo.getRequiredWidth();
int bmWidth = bufferedImage.getWidth();
int xscale = imageInfo.getXscale();
int yscale = imageInfo.getYscale();
Rectangle region = imageInfo.getIntRegion();
if (region == null) {
if (xscale != 1 || yscale != 1) {
bufferedImage = ScaleTools.scaleImageByScale(bufferedImage, xscale, yscale);
} else if (requiredWidth > 0 && bmWidth != requiredWidth) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, requiredWidth);
}
} else {
if (xscale != 1 || yscale != 1) {
bufferedImage = mara.mybox.image.data.CropTools.sample(task, bufferedImage,
imageInfo.getRegion(), xscale, yscale);
} else {
bufferedImage = mara.mybox.image.data.CropTools.sample(task, bufferedImage,
imageInfo.getRegion(), requiredWidth);
}
}
return bufferedImage;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return null;
}
}
/*
Broken image
*/
public static BufferedImage readBrokenImage(FxTask task, Exception e, ImageInformation imageInfo) {
BufferedImage image = null;
try {
File file = imageInfo.getFile();
if (e == null || file == null) {
return null;
}
String format = FileNameTools.ext(file.getName()).toLowerCase();
if (task != null) {
task.setInfo("Reading broken image: " + format);
}
switch (format) {
case "gif":
// Read Gif with JDK api normally. When broken, use DhyanB's API.
// if (e.toString().contains("java.lang.ArrayIndexOutOfBoundsException: 4096")) {
image = ImageGifFile.readBrokenGifFile(task, imageInfo);
// if (e.toString().contains("java.lang.ArrayIndexOutOfBoundsException")) {
// image = ImageGifFile.readBrokenGifFile(imageInfo);
// }
break;
case "jpg":
case "jpeg":
image = ImageJpgFile.readBrokenJpgFile(task, imageInfo);
// if (e.toString().contains("Unsupported Image Type")) {
// image = ImageJpgFile.readBrokenJpgFile(imageInfo);
// }
break;
default:
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
} catch (Exception ex) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
return image;
}
/*
Meta data
*/
public static ImageFileInformation readImageFileMetaData(FxTask task, String fileName) {
return readImageFileMetaData(task, new File(fileName));
}
public static ImageFileInformation readImageFileMetaData(FxTask task, File file) {
if (file == null || !file.exists() || !file.isFile()) {
return null;
}
if (task != null) {
task.setInfo(message("ReadingMedia...") + ": " + file);
}
ImageFileInformation fileInfo = new ImageFileInformation(file);
String format = fileInfo.getImageFormat();
if ("ico".equals(format) || "icon".equals(format)) {
fileInfo = ImageFileInformation.readIconFile(task, file);
} else {
try (ImageInputStream iis = ImageIO.createImageInputStream(
new BufferedInputStream(new FileInputStream(file)))) {
ImageReader reader = getReader(iis, format);
if (reader == null) {
return null;
}
reader.setInput(iis, false, false);
readImageFileMetaData(task, reader, fileInfo);
reader.dispose();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
return fileInfo;
}
public static boolean readImageFileMetaData(FxTask task,
ImageReader reader, ImageFileInformation fileInfo) {
try {
if (fileInfo == null) {
return false;
}
String targetFormat = fileInfo.getImageFormat();
File file = fileInfo.getFile();
List<ImageInformation> imagesInfo = new ArrayList<>();
if (reader == null) {
if (task != null) {
task.setInfo("fail to get reader");
}
fileInfo.setNumberOfImages(1);
ImageInformation imageInfo = ImageInformation.create(targetFormat, file);
imageInfo.setImageFileInformation(fileInfo);
imageInfo.setImageFormat(targetFormat);
imageInfo.setFile(file);
imageInfo.setCreateTime(fileInfo.getCreateTime());
imageInfo.setModifyTime(fileInfo.getModifyTime());
imageInfo.setFileSize(fileInfo.getFileSize());
imageInfo.setIndex(0);
ImageInformation.checkMem(task, imageInfo);
imagesInfo.add(imageInfo);
fileInfo.setImagesInformation(imagesInfo);
fileInfo.setImageInformation(imageInfo);
return true;
}
String format = reader.getFormatName().toLowerCase();
fileInfo.setImageFormat(format);
int num = reader.getNumImages(true);
fileInfo.setNumberOfImages(num);
if (task != null) {
task.setInfo("Number Of Images: " + num);
}
ImageInformation imageInfo;
for (int i = 0; i < num; ++i) {
if (task != null && !task.isWorking()) {
return false;
}
if (task != null) {
task.setInfo(message("Handle") + ": " + i + "/" + num);
}
imageInfo = ImageInformation.create(format, file);
imageInfo.setImageFileInformation(fileInfo);
imageInfo.setImageFormat(format);
imageInfo.setFile(file);
imageInfo.setCreateTime(fileInfo.getCreateTime());
imageInfo.setModifyTime(fileInfo.getModifyTime());
imageInfo.setFileSize(fileInfo.getFileSize());
imageInfo.setWidth(reader.getWidth(i));
imageInfo.setHeight(reader.getHeight(i));
imageInfo.setPixelAspectRatio(reader.getAspectRatio(i));
imageInfo.setIsMultipleFrames(num > 1);
imageInfo.setIsTiled(reader.isImageTiled(i));
imageInfo.setIndex(i);
Iterator<ImageTypeSpecifier> types = reader.getImageTypes(i);
List<ImageTypeSpecifier> typesValue = new ArrayList<>();
if (types != null) {
while (types.hasNext()) {
if (task != null && !task.isWorking()) {
return false;
}
ImageTypeSpecifier t = types.next();
typesValue.add(t);
if (task != null) {
task.setInfo("ImageTypeSpecifier : " + t.getClass());
}
}
ImageTypeSpecifier imageType = reader.getRawImageType(i);
ColorModel colorModel = null;
if (imageType != null) {
imageInfo.setRawImageType(imageType);
colorModel = imageType.getColorModel();
}
if (colorModel == null) {
if (!typesValue.isEmpty()) {
colorModel = typesValue.get(0).getColorModel();
}
}
if (colorModel != null) {
ColorSpace colorSpace = colorModel.getColorSpace();
imageInfo.setColorSpace(ColorBase.colorSpaceType(colorSpace.getType()));
imageInfo.setColorChannels(colorModel.getNumComponents());
imageInfo.setBitDepth(colorModel.getPixelSize());
}
}
imageInfo.setImageTypeSpecifiers(typesValue);
try {
imageInfo.setPixelAspectRatio(reader.getAspectRatio(i));
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
try {
imageInfo.setHasThumbnails(reader.hasThumbnails(i));
imageInfo.setNumberOfThumbnails(reader.getNumThumbnails(i));
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
try {
readImageMetaData(task, format, imageInfo, reader.getImageMetadata(i));
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
ImageInformation.checkMem(task, imageInfo);
imagesInfo.add(imageInfo);
}
fileInfo.setImagesInformation(imagesInfo);
if (!imagesInfo.isEmpty()) {
fileInfo.setImageInformation(imagesInfo.get(0));
}
return task == null || task.isWorking();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return false;
}
}
public static boolean readImageMetaData(FxTask task, String format,
ImageInformation imageInfo, IIOMetadata iioMetaData) {
try {
if (imageInfo == null || iioMetaData == null) {
return false;
}
if (task != null) {
task.setInfo("read Image Meta Data : " + format);
}
StringBuilder metaDataXml = new StringBuilder();
String[] formatNames = iioMetaData.getMetadataFormatNames();
Map<String, Map<String, List<Map<String, Object>>>> metaData = new HashMap<>();
for (String formatName : formatNames) {
if (task != null && !task.isWorking()) {
return false;
}
Map<String, List<Map<String, Object>>> formatMetaData = new HashMap<>();
IIOMetadataNode tree = (IIOMetadataNode) iioMetaData.getAsTree(formatName);
readImageMetaData(task, formatMetaData, metaDataXml, tree, 2);
metaData.put(formatName, formatMetaData);
}
imageInfo.setMetaData(metaData);
imageInfo.setMetaDataXml(metaDataXml.toString());
explainCommonMetaData(metaData, imageInfo);
switch (format.toLowerCase()) {
case "png":
ImagePngFile.explainPngMetaData(metaData, imageInfo);
break;
case "jpg":
case "jpeg":
ImageJpgFile.explainJpegMetaData(metaData, imageInfo);
break;
case "gif":
ImageGifFile.explainGifMetaData(metaData, imageInfo);
break;
case "bmp":
ImageBmpFile.explainBmpMetaData(metaData, imageInfo);
break;
case "tif":
case "tiff":
ImageTiffFile.explainTiffMetaData(iioMetaData, imageInfo);
break;
default:
}
// MyBoxLog.debug(metaData);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return false;
}
}
public static boolean readImageMetaData(FxTask task, Map<String, List<Map<String, Object>>> formatMetaData,
StringBuilder metaDataXml, IIOMetadataNode node, int level) {
try {
String lineSeparator = System.getProperty("line.separator");
for (int i = 0; i < level; ++i) {
metaDataXml.append(" ");
}
metaDataXml.append("<").append(node.getNodeName());
Map<String, Object> nodeAttrs = new HashMap<>();
NamedNodeMap map = node.getAttributes();
boolean isTiff = "TIFFField".equals(node.getNodeName());
if (map != null && map.getLength() > 0) {
int length = map.getLength();
for (int i = 0; i < length; ++i) {
if (task != null && !task.isWorking()) {
return false;
}
Node attr = map.item(i);
String name = attr.getNodeName();
String value = attr.getNodeValue();
if (!isTiff) {
nodeAttrs.put(name, value);
}
metaDataXml.append(" ").append(name).append("=\"").append(value).append("\"");
if (isTiff && "ICC Profile".equals(value)) {
metaDataXml.append(" value=\"skip...\"/>").append(lineSeparator);
return true;
}
}
}
Object userObject = node.getUserObject();
if (userObject != null) {
if (!isTiff) {
nodeAttrs.put("UserObject", userObject);
}
metaDataXml.append(" ").append("UserObject=\"skip...\"");
}
if (!isTiff && !nodeAttrs.isEmpty()) {
List<Map<String, Object>> nodeAttrsList = formatMetaData.get(node.getNodeName());
if (nodeAttrsList == null) {
nodeAttrsList = new ArrayList<>();
}
nodeAttrsList.add(nodeAttrs);
formatMetaData.put(node.getNodeName(), nodeAttrsList);
}
IIOMetadataNode child = (IIOMetadataNode) node.getFirstChild();
if (child == null) {
metaDataXml.append("/>").append(lineSeparator);
return true;
}
metaDataXml.append(">").append(lineSeparator);
while (child != null) {
if (task != null && !task.isWorking()) {
return false;
}
readImageMetaData(task, formatMetaData, metaDataXml, child, level + 1);
child = (IIOMetadataNode) child.getNextSibling();
}
for (int i = 0; i < level; ++i) {
metaDataXml.append(" ");
}
metaDataXml.append("</").append(node.getNodeName()).append(">").append(lineSeparator);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return false;
}
}
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html
public static void explainCommonMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData,
ImageInformation imageInfo) {
try {
if (!metaData.containsKey("javax_imageio_1.0")) {
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePngFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePngFile.java | package mara.mybox.image.file;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.color.CIEData;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.data.ImageColor;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.image.data.ImageInformationPng;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.tools.ByteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2018-6-19
*
* @Description
* @License Apache License Version 2.0
*/
public class ImagePngFile {
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image
public static ImageWriter getWriter() {
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metaData == null || metaData.isReadOnly() || attributes == null) {
return metaData;
}
String nativeFormat = metaData.getNativeMetadataFormatName(); // "javax_imageio_png_1.0"
IIOMetadataNode nativeTree = (IIOMetadataNode) metaData.getAsTree(nativeFormat);
if (attributes.getDensity() > 0) {
NodeList pHYsNode = nativeTree.getElementsByTagName("pHYs");
IIOMetadataNode pHYs;
if (pHYsNode != null && pHYsNode.getLength() > 0) {
pHYs = (IIOMetadataNode) pHYsNode.item(0);
} else {
pHYs = new IIOMetadataNode("pHYs");
nativeTree.appendChild(pHYs);
}
String dpm = ImageConvertTools.dpi2dpm(attributes.getDensity()) + "";
pHYs.setAttribute("pixelsPerUnitXAxis", dpm);
pHYs.setAttribute("pixelsPerUnitYAxis", dpm);
pHYs.setAttribute("unitSpecifier", "meter"); // density is dots per !Meter!
}
if (attributes.isEmbedProfile()
&& attributes.getProfile() != null && attributes.getProfileName() != null) {
NodeList iCCPsNode = nativeTree.getElementsByTagName("iCCP");
IIOMetadataNode iCCP;
if (iCCPsNode != null && iCCPsNode.getLength() > 0) {
iCCP = (IIOMetadataNode) iCCPsNode.item(0);
} else {
iCCP = new IIOMetadataNode("iCCP");
nativeTree.appendChild(iCCP);
}
iCCP.setUserObject(ByteTools.deflate(attributes.getProfile().getData()));
iCCP.setAttribute("profileName", attributes.getProfileName());
iCCP.setAttribute("compressionMethod", "deflate");
}
metaData.mergeTree(nativeFormat, nativeTree);
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static boolean writePNGImageFile(BufferedImage image,
ImageAttributes attributes, File file) {
try {
ImageWriter writer = getWriter();
ImageWriteParam param = getPara(attributes, writer);
IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(metaData, new IIOImage(image, null, metaData), param);
out.flush();
}
writer.dispose();
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image
// http://www.libpng.org/pub/png/spec/iso/index-object.html
// http://www.libpng.org/pub/png/spec/1.2/PNG-ColorAppendix.html
// http://www.libpng.org/pub/png/spec/1.2/PNG-GammaAppendix.html
public static void explainPngMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData,
ImageInformation info) {
try {
if (!metaData.containsKey("javax_imageio_png_1.0")) {
return;
}
ImageInformationPng pngInfo = (ImageInformationPng) info;
// MyBoxLog.debug("explainPngMetaData");
Map<String, List<Map<String, Object>>> javax_imageio_png = metaData.get("javax_imageio_png_1.0");
if (javax_imageio_png.containsKey("IHDR")) {
Map<String, Object> IHDR = javax_imageio_png.get("IHDR").get(0);
if (IHDR.containsKey("width")) {
pngInfo.setWidth(Integer.parseInt((String) IHDR.get("width")));
}
if (IHDR.containsKey("height")) {
pngInfo.setHeight(Integer.parseInt((String) IHDR.get("height")));
}
if (IHDR.containsKey("bitDepth")) {
pngInfo.setBitDepth(Integer.parseInt((String) IHDR.get("bitDepth")));
}
if (IHDR.containsKey("colorType")) {
pngInfo.setColorType((String) IHDR.get("colorType"));
}
if (IHDR.containsKey("compressionMethod")) {
pngInfo.setCompressionMethod((String) IHDR.get("compressionMethod"));
}
if (IHDR.containsKey("filterMethod")) {
pngInfo.setFilterMethod((String) IHDR.get("filterMethod"));
}
if (IHDR.containsKey("interlaceMethod")) {
pngInfo.setInterlaceMethod((String) IHDR.get("interlaceMethod"));
}
}
if (javax_imageio_png.containsKey("PLTEEntry")) {
List<Map<String, Object>> PaletteEntryList = javax_imageio_png.get("PLTEEntry");
pngInfo.setPngPaletteSize(PaletteEntryList.size());
// List<ImageColor> Palette = new ArrayList<>();
// for (Map<String, Object> PaletteEntry : PaletteEntryList) {
// int index = Integer.parseInt(PaletteEntry.get("index"));
// int red = Integer.parseInt(PaletteEntry.get("red"));
// int green = Integer.parseInt(PaletteEntry.get("green"));
// int blue = Integer.parseInt(PaletteEntry.get("blue"));
// int alpha = 255;
// Palette.add(new ImageColor(index, red, green, blue, alpha));
// }
// pngInfo.setPngPalette(Palette);
}
if (javax_imageio_png.containsKey("bKGD_Grayscale")) {
Map<String, Object> bKGD_Grayscale = javax_imageio_png.get("bKGD_Grayscale").get(0);
pngInfo.setbKGD_Grayscale(Integer.parseInt((String) bKGD_Grayscale.get("gray")));
}
if (javax_imageio_png.containsKey("bKGD_RGB")) {
Map<String, Object> bKGD_RGB = javax_imageio_png.get("bKGD_RGB").get(0);
int red = Integer.parseInt((String) bKGD_RGB.get("red"));
int green = Integer.parseInt((String) bKGD_RGB.get("green"));
int blue = Integer.parseInt((String) bKGD_RGB.get("blue"));
int alpha = 255;
pngInfo.setbKGD_RGB(new ImageColor(red, green, blue, alpha));
}
if (javax_imageio_png.containsKey("bKGD_Palette")) {
Map<String, Object> bKGD_Palette = javax_imageio_png.get("bKGD_Palette").get(0);
pngInfo.setbKGD_Palette(Integer.parseInt((String) bKGD_Palette.get("index")));
}
if (javax_imageio_png.containsKey("cHRM")) {
Map<String, Object> cHRM = javax_imageio_png.get("cHRM").get(0);
double x = 0.00001d * Integer.parseInt((String) cHRM.get("whitePointX"));
double y = 0.00001d * Integer.parseInt((String) cHRM.get("whitePointY"));
pngInfo.setWhite(new CIEData(x, y));
x = 0.00001d * Integer.parseInt((String) cHRM.get("redX"));
y = 0.00001d * Integer.parseInt((String) cHRM.get("redY"));
pngInfo.setRed(new CIEData(x, y));
x = 0.00001d * Integer.parseInt((String) cHRM.get("greenX"));
y = 0.00001d * Integer.parseInt((String) cHRM.get("greenY"));
pngInfo.setGreen(new CIEData(x, y));
x = 0.00001d * Integer.parseInt((String) cHRM.get("blueX"));
y = 0.00001d * Integer.parseInt((String) cHRM.get("blueY"));
pngInfo.setBlue(new CIEData(x, y));
}
if (javax_imageio_png.containsKey("gAMA")) {
Map<String, Object> gAMA = javax_imageio_png.get("gAMA").get(0);
float g = 0.00001f * Integer.parseInt((String) gAMA.get("value"));
pngInfo.setGamma(g);
}
if (javax_imageio_png.containsKey("iCCP")) {
Map<String, Object> iCCP = javax_imageio_png.get("iCCP").get(0);
pngInfo.setProfileName((String) iCCP.get("profileName"));
pngInfo.setProfileCompressionMethod((String) iCCP.get("compressionMethod"));
pngInfo.setIccProfile(ByteTools.inflate((byte[]) iCCP.get("UserObject")));
}
if (javax_imageio_png.containsKey("pHYs")) {
Map<String, Object> pHYs = javax_imageio_png.get("pHYs").get(0);
if (pHYs.containsKey("unitSpecifier")) {
pngInfo.setUnitSpecifier((String) pHYs.get("unitSpecifier"));
boolean isMeter = "meter".equals(pHYs.get("unitSpecifier"));
if (pHYs.containsKey("pixelsPerUnitXAxis")) {
int v = Integer.parseInt((String) pHYs.get("pixelsPerUnitXAxis"));
pngInfo.setPixelsPerUnitXAxis(v);
if (isMeter) {
pngInfo.setXDpi(ImageConvertTools.dpm2dpi(v)); // resolution value should be dpi
} else {
pngInfo.setXDpi(v);
}
// MyBoxLog.debug("pixelsPerUnitXAxis:" + pngInfo.gethResolution());
}
if (pHYs.containsKey("pixelsPerUnitYAxis")) {
int v = Integer.parseInt((String) pHYs.get("pixelsPerUnitYAxis"));
pngInfo.setPixelsPerUnitYAxis(v);
if (isMeter) {
pngInfo.setYDpi(ImageConvertTools.dpm2dpi(v)); // resolution value should be dpi
} else {
pngInfo.setYDpi(v);
}
// MyBoxLog.debug("pixelsPerUnitYAxis:" + pngInfo.getvResolution());
}
}
}
if (javax_imageio_png.containsKey("sBIT_Grayscale")) {
Map<String, Object> sBIT_Grayscale = javax_imageio_png.get("sBIT_Grayscale").get(0);
pngInfo.setsBIT_Grayscale(Integer.parseInt((String) sBIT_Grayscale.get("gray")));
}
if (javax_imageio_png.containsKey("sBIT_GrayAlpha")) {
Map<String, Object> sBIT_GrayAlpha = javax_imageio_png.get("sBIT_GrayAlpha").get(0);
pngInfo.setsBIT_GrayAlpha_gray(Integer.parseInt((String) sBIT_GrayAlpha.get("gray")));
pngInfo.setsBIT_GrayAlpha_alpha(Integer.parseInt((String) sBIT_GrayAlpha.get("alpha")));
}
if (javax_imageio_png.containsKey("sBIT_RGB")) {
Map<String, Object> sBIT_RGB = javax_imageio_png.get("sBIT_RGB").get(0);
pngInfo.setsBIT_RGB_red(Integer.parseInt((String) sBIT_RGB.get("red")));
pngInfo.setsBIT_RGB_green(Integer.parseInt((String) sBIT_RGB.get("green")));
pngInfo.setsBIT_RGB_blue(Integer.parseInt((String) sBIT_RGB.get("blue")));
}
if (javax_imageio_png.containsKey("sBIT_RGBAlpha")) {
Map<String, Object> sBIT_RGBAlpha = javax_imageio_png.get("sBIT_RGBAlpha").get(0);
pngInfo.setsBIT_RGBAlpha_red(Integer.parseInt((String) sBIT_RGBAlpha.get("red")));
pngInfo.setsBIT_RGBAlpha_green(Integer.parseInt((String) sBIT_RGBAlpha.get("green")));
pngInfo.setsBIT_RGBAlpha_blue(Integer.parseInt((String) sBIT_RGBAlpha.get("blue")));
pngInfo.setsBIT_RGBAlpha_alpha(Integer.parseInt((String) sBIT_RGBAlpha.get("alpha")));
}
if (javax_imageio_png.containsKey("sBIT_Palette")) {
Map<String, Object> sBIT_Palette = javax_imageio_png.get("sBIT_Palette").get(0);
pngInfo.setsBIT_Palette_red(Integer.parseInt((String) sBIT_Palette.get("red")));
pngInfo.setsBIT_Palette_green(Integer.parseInt((String) sBIT_Palette.get("green")));
pngInfo.setsBIT_Palette_blue(Integer.parseInt((String) sBIT_Palette.get("blue")));
}
if (javax_imageio_png.containsKey("sPLTEntry")) {
List<Map<String, Object>> sPLTEntryList = javax_imageio_png.get("sPLTEntry");
pngInfo.setSuggestedPaletteSize(sPLTEntryList.size());
// List<ImageColor> Palette = new ArrayList<>();
// for (Map<String, Object> PaletteEntry : sPLTEntryList) {
// int index = Integer.parseInt(PaletteEntry.get("index"));
// int red = Integer.parseInt(PaletteEntry.get("red"));
// int green = Integer.parseInt(PaletteEntry.get("green"));
// int blue = Integer.parseInt(PaletteEntry.get("blue"));
// int alpha = 255;
// Palette.add(new ImageColor(index, red, green, blue, alpha));
// }
// pngInfo.setSuggestedPalette(Palette);
}
if (javax_imageio_png.containsKey("sRGB")) {
Map<String, Object> sRGB = javax_imageio_png.get("sRGB").get(0);
pngInfo.setRenderingIntent((String) sRGB.get("renderingIntent"));
}
if (javax_imageio_png.containsKey("tIME")) {
Map<String, Object> ImageModificationTime = javax_imageio_png.get("tIME").get(0);
String t = ImageModificationTime.get("year") + "-" + ImageModificationTime.get("month") + "-"
+ ImageModificationTime.get("day") + " " + ImageModificationTime.get("hour")
+ ":" + ImageModificationTime.get("minute") + ":" + ImageModificationTime.get("second");
pngInfo.setImageModificationTime(t);
}
if (javax_imageio_png.containsKey("tRNS_Grayscale")) {
Map<String, Object> tRNS_Grayscale = javax_imageio_png.get("tRNS_Grayscale").get(0);
pngInfo.settRNS_Grayscale(Integer.parseInt((String) tRNS_Grayscale.get("gray")));
}
if (javax_imageio_png.containsKey("tRNS_RGB")) {
Map<String, Object> tRNS_RGB = javax_imageio_png.get("tRNS_RGB").get(0);
int red = Integer.parseInt((String) tRNS_RGB.get("red"));
int green = Integer.parseInt((String) tRNS_RGB.get("green"));
int blue = Integer.parseInt((String) tRNS_RGB.get("blue"));
int alpha = 255;
pngInfo.settRNS_RGB(new ImageColor(red, green, blue, alpha));
}
if (javax_imageio_png.containsKey("tRNS_Palette")) {
Map<String, Object> tRNS_Palette = javax_imageio_png.get("tRNS_Palette").get(0);
pngInfo.settRNS_Palette_index(Integer.parseInt((String) tRNS_Palette.get("index")));
pngInfo.settRNS_Palette_alpha(Integer.parseInt((String) tRNS_Palette.get("alpha")));
}
} catch (Exception e) {
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePnmFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePnmFile.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageReader;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageReaderSpi;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriter;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriterSpi;
import com.github.jaiimageio.impl.plugins.pnm.PNMMetadata;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.FileTmpTools;
/**
* @Author Mara
* @CreateDate 2018-6-19
*
* @Description
* @License Apache License Version 2.0
*/
public class ImagePnmFile {
public static ImageWriter getWriter() {
PNMImageWriter writer = new PNMImageWriter(new PNMImageWriterSpi());
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
PNMMetadata metaData = (PNMMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static boolean writePnmImageFile(BufferedImage image,
ImageAttributes attributes, String outFile) {
try {
ImageWriter writer = getWriter();
ImageWriteParam param = getPara(attributes, writer);
IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(metaData, new IIOImage(image, null, metaData), param);
out.flush();
}
writer.dispose();
File file = new File(outFile);
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static PNMMetadata getPnmMetadata(File file) {
try {
PNMMetadata metadata;
PNMImageReader reader = new PNMImageReader(new PNMImageReaderSpi());
try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) {
reader.setInput(iis, false);
metadata = (PNMMetadata) reader.getImageMetadata(0);
reader.dispose();
}
return metadata;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageJpgFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageJpgFile.java | package mara.mybox.image.file;
import java.awt.Rectangle;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.data.ImageColorSpace;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.image.data.ImageFileInformation;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.Languages;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2018-6-19
*
* @Description
* @License Apache License Version 2.0
*/
public class ImageJpgFile {
public static String[] getJpegCompressionTypes() {
return new JPEGImageWriteParam(null).getCompressionTypes();
}
public static BufferedImage readBrokenJpgFile(FxTask task, ImageInformation imageInfo) {
if (imageInfo == null) {
return null;
}
File file = imageInfo.getFile();
try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
ImageReader reader = null;
while (readers.hasNext()) {
reader = readers.next();
if (reader.canReadRaster()) {
break;
}
}
if (reader == null) {
iis.close();
return null;
}
reader.setInput(iis);
ImageFileInformation fileInfo = new ImageFileInformation(file);
ImageFileReaders.readImageFileMetaData(task, reader, fileInfo);
if (task != null && !task.isWorking()) {
return null;
}
ImageInformation fileImageInfo = fileInfo.getImagesInformation().get(imageInfo.getIndex());
imageInfo.setWidth(fileImageInfo.getWidth());
imageInfo.setHeight(fileImageInfo.getHeight());
imageInfo.setColorSpace(fileImageInfo.getColorSpace());
imageInfo.setColorChannels(fileImageInfo.getColorChannels());
imageInfo.setNativeAttribute("Adobe", fileImageInfo.getNativeAttribute("Adobe"));
BufferedImage bufferedImage = readBrokenJpgFile(task, reader, imageInfo);
if (task != null && !task.isWorking()) {
return null;
}
int requiredWidth = (int) imageInfo.getRequiredWidth();
if (requiredWidth > 0 && bufferedImage.getWidth() != requiredWidth) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, requiredWidth);
}
return bufferedImage;
} catch (Exception ex) {
imageInfo.setError(ex.toString());
return null;
}
}
private static BufferedImage readBrokenJpgFile(FxTask task, ImageReader reader, ImageInformation imageInfo) {
if (reader == null || imageInfo == null || imageInfo.getColorChannels() != 4) {
return null;
}
BufferedImage bufferedImage = null;
try {
ImageReadParam param = reader.getDefaultReadParam();
Rectangle region = imageInfo.getIntRegion();
if (region != null) {
param.setSourceRegion(region);
}
int xscale = imageInfo.getXscale();
int yscale = imageInfo.getYscale();
if (xscale != 1 || yscale != 1) {
param.setSourceSubsampling(xscale, yscale, 0, 0);
} else {
ImageInformation.checkMem(task, imageInfo);
int sampleScale = imageInfo.getSampleScale();
if (sampleScale > 1) {
param.setSourceSubsampling(sampleScale, sampleScale, 0, 0);
}
}
if (task != null && !task.isWorking()) {
return null;
}
WritableRaster srcRaster = (WritableRaster) reader.readRaster(imageInfo.getIndex(), param);
if (task != null && !task.isWorking()) {
return null;
}
boolean isAdobe = (boolean) imageInfo.getNativeAttribute("Adobe");
if ("YCCK".equals(imageInfo.getColorSpace())) {
ImageConvertTools.ycck2cmyk(task, srcRaster, isAdobe);
} else if (isAdobe) {
ImageConvertTools.invertPixelValue(task, srcRaster);
}
if (task != null && !task.isWorking()) {
return null;
}
bufferedImage = new BufferedImage(srcRaster.getWidth(), srcRaster.getHeight(), BufferedImage.TYPE_INT_RGB);
WritableRaster rgbRaster = bufferedImage.getRaster();
ColorSpace cmykCS;
if (isAdobe) {
cmykCS = ImageColorSpace.adobeCmykColorSpace();
} else {
cmykCS = ImageColorSpace.eciCmykColorSpace();
}
ColorSpace rgbCS = bufferedImage.getColorModel().getColorSpace();
ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null);
if (task != null && !task.isWorking()) {
return null;
}
cmykToRgb.filter(srcRaster, rgbRaster);
} catch (Exception ex) {
imageInfo.setError(ex.toString());
}
return bufferedImage;
}
public static ImageWriter getWriter() {
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#image
public static IIOMetadata getWriterMeta2(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metaData == null || metaData.isReadOnly() || attributes == null) {
return metaData;
}
String nativeFormat = metaData.getNativeMetadataFormatName();// "javax_imageio_jpeg_image_1.0"
IIOMetadataNode root = new IIOMetadataNode(nativeFormat);
IIOMetadataNode jpegVariety = new IIOMetadataNode("JPEGvariety");
IIOMetadataNode markerSequence = new IIOMetadataNode("markerSequence");
IIOMetadataNode app0JFIF = new IIOMetadataNode("app0JFIF");
root.appendChild(jpegVariety);
root.appendChild(markerSequence);
jpegVariety.appendChild(app0JFIF);
app0JFIF.setAttribute("majorVersion", "1");
app0JFIF.setAttribute("minorVersion", "2");
app0JFIF.setAttribute("thumbWidth", "0");
app0JFIF.setAttribute("thumbHeight", "0");
if (attributes.getDensity() > 0) {
app0JFIF.setAttribute("Xdensity", attributes.getDensity() + "");
app0JFIF.setAttribute("Ydensity", attributes.getDensity() + "");
app0JFIF.setAttribute("resUnits", "1"); // density is dots per inch
}
if (attributes.isEmbedProfile() && attributes.getProfile() != null) {
IIOMetadataNode app2ICC = new IIOMetadataNode("app2ICC");
app0JFIF.appendChild(app2ICC);
app2ICC.setUserObject(attributes.getProfile());
}
metaData.mergeTree(nativeFormat, root);
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metaData == null || metaData.isReadOnly() || attributes == null) {
return metaData;
}
String nativeFormat = metaData.getNativeMetadataFormatName();// "javax_imageio_jpeg_image_1.0"
IIOMetadataNode nativeTree = (IIOMetadataNode) metaData.getAsTree(nativeFormat);
if (nativeTree == null) {
return metaData;
}
IIOMetadataNode JPEGvariety, markerSequence;
NodeList JPEGvarietyNode = nativeTree.getElementsByTagName("JPEGvariety");
if (JPEGvarietyNode != null && JPEGvarietyNode.getLength() > 0) {
JPEGvariety = (IIOMetadataNode) JPEGvarietyNode.item(0);
} else {
JPEGvariety = new IIOMetadataNode("JPEGvariety");
nativeTree.appendChild(JPEGvariety);
}
NodeList markerSequenceNode = nativeTree.getElementsByTagName("markerSequence");
if (markerSequenceNode == null) {
markerSequence = new IIOMetadataNode("markerSequence");
nativeTree.appendChild(markerSequence);
}
IIOMetadataNode app0JFIF;
NodeList app0JFIFNode = nativeTree.getElementsByTagName("app0JFIF");
if (app0JFIFNode != null && app0JFIFNode.getLength() > 0) {
app0JFIF = (IIOMetadataNode) app0JFIFNode.item(0);
} else {
app0JFIF = new IIOMetadataNode("app0JFIF");
JPEGvariety.appendChild(app0JFIF);
}
if (attributes.getDensity() > 0) {
app0JFIF.setAttribute("Xdensity", attributes.getDensity() + "");
app0JFIF.setAttribute("Ydensity", attributes.getDensity() + "");
app0JFIF.setAttribute("resUnits", "1"); // density is dots per inch
}
if (attributes.isEmbedProfile() && attributes.getProfile() != null) {
IIOMetadataNode app2ICC;
NodeList app2ICCNode = nativeTree.getElementsByTagName("app2ICC");
if (app2ICCNode != null && app2ICCNode.getLength() > 0) {
app2ICC = (IIOMetadataNode) app2ICCNode.item(0);
} else {
app2ICC = new IIOMetadataNode("app2ICC");
app0JFIF.appendChild(app2ICC);
}
app2ICC.setUserObject(attributes.getProfile());
}
metaData.mergeTree(nativeFormat, nativeTree);
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static boolean writeJPEGImageFile(BufferedImage image,
ImageAttributes attributes, File file) {
try {
ImageWriter writer = getWriter();
ImageWriteParam param = getPara(attributes, writer);
IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);
File tmpFile = FileTmpTools.getTempFile();
try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(metaData, new IIOImage(image, null, metaData), param);
out.flush();
}
writer.dispose();
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static void explainJpegMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData,
ImageInformation info) {
try {
if (!metaData.containsKey("javax_imageio_jpeg_image_1.0")) {
return;
}
Map<String, List<Map<String, Object>>> javax_imageio_jpeg = metaData.get("javax_imageio_jpeg_image_1.0");
if (javax_imageio_jpeg.containsKey("app0JFIF")) {
Map<String, Object> app0JFIF = javax_imageio_jpeg.get("app0JFIF").get(0);
if (app0JFIF.containsKey("majorVersion")) {
info.setNativeAttribute("majorVersion", Integer.parseInt((String) app0JFIF.get("majorVersion")));
}
if (app0JFIF.containsKey("minorVersion")) {
info.setNativeAttribute("minorVersion", Integer.parseInt((String) app0JFIF.get("minorVersion")));
}
if (app0JFIF.containsKey("resUnits")) {
int u = Integer.parseInt((String) app0JFIF.get("resUnits"));
info.setNativeAttribute("resUnits", u);
switch (u) {
case 1:
info.setNativeAttribute("resUnits", Languages.message("DotsPerInch"));
break;
case 2:
info.setNativeAttribute("resUnits", Languages.message("DotsPerCentimeter"));
break;
case 0:
info.setNativeAttribute("resUnits", Languages.message("None"));
}
if (app0JFIF.containsKey("Xdensity")) {
int v = Integer.parseInt((String) app0JFIF.get("Xdensity"));
info.setNativeAttribute("Xdensity", v);
if (u == 2) {
info.setXDpi(ImageConvertTools.dpi2dpcm(v)); // density value should be dpi
} else if (u == 1) {
info.setXDpi(v);
}
}
if (app0JFIF.containsKey("Ydensity")) {
int v = Integer.parseInt((String) app0JFIF.get("Ydensity"));
info.setNativeAttribute("Ydensity", v);
if (u == 2) {
info.setYDpi(ImageConvertTools.dpi2dpcm(v)); // density value should be dpi
} else if (u == 1) {
info.setYDpi(v);
}
}
}
if (app0JFIF.containsKey("thumbWidth")) {
info.setNativeAttribute("thumbWidth", Integer.parseInt((String) app0JFIF.get("thumbWidth")));
}
if (app0JFIF.containsKey("thumbHeight")) {
info.setNativeAttribute("thumbHeight", Integer.parseInt((String) app0JFIF.get("thumbHeight")));
}
}
if (javax_imageio_jpeg.containsKey("app0JFXX")) {
Map<String, Object> app0JFXX = javax_imageio_jpeg.get("app0JFXX").get(0);
if (app0JFXX.containsKey("extensionCode")) {
info.setNativeAttribute("extensionCode", app0JFXX.get("extensionCode"));
}
}
if (javax_imageio_jpeg.containsKey("JFIFthumbPalette")) {
Map<String, Object> JFIFthumbPalette = javax_imageio_jpeg.get("JFIFthumbPalette").get(0);
if (JFIFthumbPalette.containsKey("thumbWidth")) {
info.setNativeAttribute("thumbWidth", JFIFthumbPalette.get("thumbWidth"));
}
if (JFIFthumbPalette.containsKey("thumbHeight")) {
info.setNativeAttribute("thumbHeight", JFIFthumbPalette.get("thumbHeight"));
}
}
if (javax_imageio_jpeg.containsKey("JFIFthumbRGB")) {
Map<String, Object> JFIFthumbRGB = javax_imageio_jpeg.get("JFIFthumbRGB").get(0);
if (JFIFthumbRGB.containsKey("thumbWidth")) {
info.setNativeAttribute("thumbWidth", JFIFthumbRGB.get("thumbWidth"));
}
if (JFIFthumbRGB.containsKey("thumbHeight")) {
info.setNativeAttribute("thumbHeight", JFIFthumbRGB.get("thumbHeight"));
}
}
if (javax_imageio_jpeg.containsKey("app2ICC")) {
Map<String, Object> app2ICC = javax_imageio_jpeg.get("app2ICC").get(0);
ICC_Profile p = (ICC_Profile) app2ICC.get("UserObject");
info.setIccProfile(p.getData());
}
if (javax_imageio_jpeg.containsKey("dqtable")) {
Map<String, Object> dqtable = javax_imageio_jpeg.get("dqtable").get(0);
if (dqtable.containsKey("elementPrecision")) {
info.setNativeAttribute("dqtableElementPrecision", dqtable.get("elementPrecision"));
}
if (dqtable.containsKey("qtableId")) {
info.setNativeAttribute("qtableId", dqtable.get("qtableId"));
}
}
if (javax_imageio_jpeg.containsKey("dhtable")) {
Map<String, Object> dhtable = javax_imageio_jpeg.get("dhtable").get(0);
if (dhtable.containsKey("class")) {
info.setNativeAttribute("dhtableClass", dhtable.get("class"));
}
if (dhtable.containsKey("htableId")) {
info.setNativeAttribute("htableId", dhtable.get("htableId"));
}
}
if (javax_imageio_jpeg.containsKey("dri")) {
Map<String, Object> dri = javax_imageio_jpeg.get("dri").get(0);
if (dri.containsKey("interval")) {
info.setNativeAttribute("driInterval", dri.get("interval"));
}
}
if (javax_imageio_jpeg.containsKey("com")) {
Map<String, Object> com = javax_imageio_jpeg.get("com").get(0);
if (com.containsKey("comment")) {
info.setNativeAttribute("comment", com.get("comment"));
}
}
if (javax_imageio_jpeg.containsKey("unknown")) {
Map<String, Object> unknown = javax_imageio_jpeg.get("unknown").get(0);
if (unknown.containsKey("MarkerTag")) {
info.setNativeAttribute("unknownMarkerTag", unknown.get("MarkerTag"));
}
}
if (javax_imageio_jpeg.containsKey("app14Adobe")) {
info.setNativeAttribute("Adobe", true);
Map<String, Object> app14Adobe = javax_imageio_jpeg.get("app14Adobe").get(0);
if (app14Adobe.containsKey("version")) {
info.setNativeAttribute("AdobeVersion", app14Adobe.get("version"));
}
if (app14Adobe.containsKey("flags0")) {
info.setNativeAttribute("AdobeFlags0", app14Adobe.get("flags0"));
}
if (app14Adobe.containsKey("flags1")) {
info.setNativeAttribute("AdobeFlags1", app14Adobe.get("flags1"));
}
/*
https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#image
2 - The image is encoded as YCCK (implicitly converted from CMYK on encoding).
1 - The image is encoded as YCbCr (implicitly converted from RGB on encoding).
0 - Unknown. 3-channel images are assumed to be RGB, 4-channel images are assumed to be CMYK.
*/
if (app14Adobe.containsKey("transform")) {
info.setNativeAttribute("AdobeTransform", app14Adobe.get("transform"));
}
}
if (javax_imageio_jpeg.containsKey("sof")) {
Map<String, Object> sof = javax_imageio_jpeg.get("sof").get(0);
if (sof.containsKey("process")) {
info.setNativeAttribute("FrameProcess", sof.get("process"));
}
if (sof.containsKey("samplePrecision")) {
info.setNativeAttribute("FrameSamplePrecision", sof.get("samplePrecision"));
}
if (sof.containsKey("numLines")) {
info.setNativeAttribute("FrameNumLines", sof.get("numLines"));
}
if (sof.containsKey("samplesPerLine")) {
info.setNativeAttribute("FrameSamplesPerLine", sof.get("samplesPerLine"));
}
if (sof.containsKey("numFrameComponents")) {
info.setNativeAttribute("FrameNumFrameComponents", sof.get("numFrameComponents"));
}
}
if (javax_imageio_jpeg.containsKey("componentSpec")) {
Map<String, Object> componentSpec = javax_imageio_jpeg.get("componentSpec").get(0);
if (componentSpec.containsKey("componentId")) {
info.setNativeAttribute("FrameComponentId", componentSpec.get("componentId"));
}
if (componentSpec.containsKey("HsamplingFactor")) {
info.setNativeAttribute("FrameHsamplingFactor", componentSpec.get("HsamplingFactor"));
}
if (componentSpec.containsKey("VsamplingFactor")) {
info.setNativeAttribute("FrameVsamplingFactor", componentSpec.get("VsamplingFactor"));
}
if (componentSpec.containsKey("QtableSelector")) {
info.setNativeAttribute("FrameQtableSelector", componentSpec.get("QtableSelector"));
}
}
if (javax_imageio_jpeg.containsKey("sos")) {
Map<String, Object> sos = javax_imageio_jpeg.get("sos").get(0);
if (sos.containsKey("numScanComponents")) {
info.setNativeAttribute("NumScanComponents", sos.get("numScanComponents"));
}
if (sos.containsKey("startSpectralSelection")) {
info.setNativeAttribute("ScanStartSpectralSelection", sos.get("startSpectralSelection"));
}
if (sos.containsKey("endSpectralSelection")) {
info.setNativeAttribute("ScanEndSpectralSelection", sos.get("endSpectralSelection"));
}
if (sos.containsKey("approxHigh")) {
info.setNativeAttribute("ScanApproxHigh", sos.get("approxHigh"));
}
if (sos.containsKey("approxLow")) {
info.setNativeAttribute("ScanApproxLow", sos.get("approxLow"));
}
}
if (javax_imageio_jpeg.containsKey("scanComponentSpec")) {
Map<String, Object> scanComponentSpec = javax_imageio_jpeg.get("scanComponentSpec").get(0);
if (scanComponentSpec.containsKey("componentSelector")) {
info.setNativeAttribute("ScanComponentSelector", scanComponentSpec.get("componentSelector"));
}
if (scanComponentSpec.containsKey("dcHuffTable")) {
info.setNativeAttribute("ScanDcHuffTable", scanComponentSpec.get("dcHuffTable"));
}
if (scanComponentSpec.containsKey("acHuffTable")) {
info.setNativeAttribute("ScanAcHuffTable", scanComponentSpec.get("acHuffTable"));
}
}
} catch (Exception e) {
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePcxFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImagePcxFile.java | package mara.mybox.image.file;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageReader;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageReaderSpi;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriter;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriterSpi;
import com.github.jaiimageio.impl.plugins.pcx.PCXMetadata;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.FileTmpTools;
/**
* @Author Mara
* @CreateDate 2018-6-19
*
* @Description
* @License Apache License Version 2.0
*/
public class ImagePcxFile {
public static ImageWriter getWriter() {
PCXImageWriter writer = new PCXImageWriter(new PCXImageWriterSpi());
return writer;
}
public static boolean writePcxImageFile(BufferedImage image,
ImageAttributes attributes, File file) {
try {
ImageWriter writer = getWriter();
File tmpFile = FileTmpTools.getTempFile();
try ( ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) {
writer.setOutput(out);
writer.write(null, new IIOImage(image, null, null), null);
out.flush();
}
writer.dispose();
return FileTools.override(tmpFile, file);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static PCXMetadata getPcxMetadata(File file) {
try {
PCXMetadata metadata = null;
PCXImageReader reader = new PCXImageReader(new PCXImageReaderSpi());
try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) {
reader.setInput(iis, false);
metadata = (PCXMetadata) reader.getImageMetadata(0);
reader.dispose();
}
return metadata;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageTiffFile.java | alpha/MyBox/src/main/java/mara/mybox/image/file/ImageTiffFile.java | package mara.mybox.image.file;
//import com.github.jaiimageio.impl.plugins.tiff.IIOMetadata;
//import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReader;
//import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReaderSpi;
//import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriter;
//import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriterSpi;
//import com.github.jaiimageio.plugins.tiff.BaselineTIFFTagSet;
//import com.github.jaiimageio.plugins.tiff.TIFFField;
//import com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam;
//import com.github.jaiimageio.plugins.tiff.TIFFTag;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.tiff.BaselineTIFFTagSet;
import javax.imageio.plugins.tiff.TIFFField;
import javax.imageio.plugins.tiff.TIFFTag;
import javax.imageio.stream.ImageInputStream;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileNameTools;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2018-6-19
* @License Apache License Version 2.0
*/
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/tiff_metadata.html#image
public class ImageTiffFile {
public static IIOMetadata getTiffIIOMetadata(File file) {
try {
IIOMetadata metadata;
try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) {
ImageReader reader = ImageFileReaders.getReader(iis, FileNameTools.ext(file.getName()));
if (reader == null) {
return null;
}
reader.setInput(iis, false);
metadata = reader.getImageMetadata(0);
reader.dispose();
}
return metadata;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ImageWriter getWriter() {
ImageWriter writer = ImageIO.getImageWritersByFormatName("tif").next();
return writer;
}
public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) {
try {
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (attributes != null && attributes.getCompressionType() != null) {
param.setCompressionType(attributes.getCompressionType());
} else {
param.setCompressionType("LZW");
}
if (attributes != null && attributes.getQuality() > 0) {
param.setCompressionQuality(attributes.getQuality() / 100.0f);
} else {
param.setCompressionQuality(1.0f);
}
}
return param;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
ImageWriter writer, ImageWriteParam param) {
try {
IIOMetadata metaData;
if (attributes != null && attributes.getColorType() != null) {
ImageTypeSpecifier imageTypeSpecifier;
switch (attributes.getColorType()) {
case ARGB:
imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
break;
case RGB:
imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
break;
case BINARY:
imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
break;
case GRAY:
imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY);
break;
default:
imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
break;
}
metaData = writer.getDefaultImageMetadata(imageTypeSpecifier, param);
} else if (image != null) {
metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
} else {
metaData = writer.getDefaultImageMetadata(
ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB), param);
}
if (metaData == null || metaData.isReadOnly() || attributes == null) {
return metaData;
}
if (attributes.getDensity() > 0) {
String nativeName = metaData.getNativeMetadataFormatName(); // javax_imageio_tiff_image_1.0
Node nativeTree = metaData.getAsTree(nativeName);
long[] xRes = new long[]{attributes.getDensity(), 1};
long[] yRes = new long[]{attributes.getDensity(), 1};
TIFFField fieldXRes = new TIFFField(
BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION),
TIFFTag.TIFF_RATIONAL, 1, new long[][]{xRes});
TIFFField fieldYRes = new TIFFField(
BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION),
TIFFTag.TIFF_RATIONAL, 1, new long[][]{yRes});
nativeTree.getFirstChild().appendChild(fieldXRes.getAsNativeNode());
nativeTree.getFirstChild().appendChild(fieldYRes.getAsNativeNode());
char[] fieldUnit = new char[]{
BaselineTIFFTagSet.RESOLUTION_UNIT_INCH};
TIFFField fieldResUnit = new TIFFField(
BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT),
TIFFTag.TIFF_SHORT, 1, fieldUnit);
nativeTree.getFirstChild().appendChild(fieldResUnit.getAsNativeNode());
metaData.mergeTree(nativeName, nativeTree);
}
return metaData;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Node findNode(Node nativeTree, String name) {
try {
NodeList nodes = nativeTree.getFirstChild().getChildNodes();
for (int i = 0; i < nodes.getLength(); ++i) {
Node node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
for (int j = 0; j < attrs.getLength(); ++j) {
Node attr = attrs.item(j);
if ("name".equals(attr.getNodeName()) && name.equals(attr.getNodeValue())) {
return node;
}
}
}
return null;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// Ignore list values, which can be anaylse if need in future.
public static void explainTiffMetaData(IIOMetadata iioMetaData, ImageInformation info) {
try {
String nativeName = iioMetaData.getNativeMetadataFormatName(); // javax_imageio_tiff_image_1.0
Node nativeTree = iioMetaData.getAsTree(nativeName);
NodeList nodes = nativeTree.getFirstChild().getChildNodes();
BaselineTIFFTagSet tagsSet = BaselineTIFFTagSet.getInstance();
int unit = -1, x = -1, y = -1;
for (int i = 0; i < nodes.getLength(); ++i) {
Node node = nodes.item(i);
TIFFField field = TIFFField.createFromMetadataNode(tagsSet, node);
String name = field.getTag().getName();
if ("ICC Profile".equals(name)) {
info.setIccProfile(field.getAsBytes());
info.setNativeAttribute(name, "skip...");
} else {
String des = null;
try {
des = node.getFirstChild().getFirstChild().getAttributes().item(1).getNodeValue();
} catch (Exception e) {
}
List<String> values = new ArrayList<>();
for (int j = 0; j < field.getCount(); ++j) {
values.add(field.getValueAsString(j));
}
if (values.isEmpty()) {
continue;
} else if (values.size() == 1) {
if (des != null) {
info.setNativeAttribute(name, des + "(" + values.get(0) + ")");
} else {
info.setNativeAttribute(name, values.get(0));
}
} else {
info.setNativeAttribute(name, values);
}
switch (name) {
case "ImageWidth":
info.setWidth(Integer.parseInt(values.get(0)));
break;
case "ImageLength":
info.setHeight(Integer.parseInt(values.get(0)));
break;
case "ResolutionUnit":
unit = Integer.parseInt(values.get(0));
break;
case "XResolution":
x = getRationalValue(values.get(0));
break;
case "YResolution":
y = getRationalValue(values.get(0));
break;
}
}
}
if (x > 0 && y > 0) {
if (BaselineTIFFTagSet.RESOLUTION_UNIT_CENTIMETER == unit) {
info.setXDpi(ImageConvertTools.dpcm2dpi(x));
info.setYDpi(ImageConvertTools.dpcm2dpi(y));
} else if (BaselineTIFFTagSet.RESOLUTION_UNIT_INCH == unit) {
info.setXDpi(x);
info.setYDpi(y);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
private static int getRationalValue(String v) {
int pos = v.indexOf('/');
String vv = v;
if (pos > 0) {
vv = v.substring(0, pos);
}
return Integer.parseInt(vv);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsBlend.java | alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsBlend.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.data.DoubleShape;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2019-3-24 11:24:03
* @License Apache License Version 2.0
*/
public abstract class PixelsBlend {
public enum ImagesBlendMode {
KubelkaMunk, CMYK, CMYK_WEIGHTED, MULTIPLY, NORMAL, DISSOLVE,
DARKEN, COLOR_BURN, LINEAR_BURN, LIGHTEN, SCREEN,
COLOR_DODGE, LINEAR_DODGE, DIVIDE, VIVID_LIGHT, LINEAR_LIGHT,
SUBTRACT, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DIFFERENCE,
EXCLUSION, HUE, SATURATION, COLOR, LUMINOSITY
}
protected ImagesBlendMode blendMode;
protected float weight;
protected boolean baseAbove = false;
protected Color foreColor, backColor;
protected int red, green, blue, alpha;
protected TransparentAs baseTransparentAs = TransparentAs.Transparent,
overlayTransparentAs = TransparentAs.Another;
public enum TransparentAs {
Another, Transparent, Blend
}
public PixelsBlend() {
}
public int blend(int overlayPixel, int basePixel) {
if (basePixel == 0) {
if (baseTransparentAs == TransparentAs.Transparent) {
return 0;
} else if (baseTransparentAs == TransparentAs.Another) {
return overlayPixel;
}
}
if (overlayPixel == 0) {
if (overlayTransparentAs == TransparentAs.Another) {
return basePixel;
} else if (overlayTransparentAs == TransparentAs.Transparent) {
return 0;
}
}
if (baseAbove) {
foreColor = new Color(basePixel, true);
backColor = new Color(overlayPixel, true);
} else {
foreColor = new Color(overlayPixel, true);
backColor = new Color(basePixel, true);
}
makeRGB();
makeAlpha();
Color newColor = new Color(
Math.min(Math.max(red, 0), 255),
Math.min(Math.max(green, 0), 255),
Math.min(Math.max(blue, 0), 255),
Math.min(Math.max(alpha, 0), 255));
return newColor.getRGB();
}
public Color blend(Color overlayColor, Color baseColor) {
if (overlayColor == null) {
return baseColor;
}
if (baseColor == null) {
return overlayColor;
}
int b = blend(overlayColor.getRGB(), baseColor.getRGB());
return new Color(b, true);
}
// replace this in different blend mode. Refer to "PixelsBlendFactory"
public void makeRGB() {
red = blendValues(foreColor.getRed(), backColor.getRed(), weight);
green = blendValues(foreColor.getGreen(), backColor.getGreen(), weight);
blue = blendValues(foreColor.getBlue(), backColor.getBlue(), weight);
}
protected void makeAlpha() {
alpha = blendValues(foreColor.getAlpha(), backColor.getAlpha(), weight);
}
public BufferedImage blend(FxTask task, BufferedImage overlay, BufferedImage baseImage, int x, int y) {
try {
if (overlay == null || baseImage == null) {
return null;
}
int imageType = BufferedImage.TYPE_INT_ARGB;
DoubleRectangle rect = DoubleRectangle.xywh(x, y, overlay.getWidth(), overlay.getHeight());
BufferedImage target = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(), imageType);
int height = baseImage.getHeight();
int width = baseImage.getWidth();
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
int basePixel = baseImage.getRGB(i, j);
if (DoubleShape.contains(rect, i, j)) {
int overlayPixel = overlay.getRGB(i - x, j - y);
target.setRGB(i, j, blend(overlayPixel, basePixel));
} else {
target.setRGB(i, j, basePixel);
}
}
}
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return overlay;
}
}
public String modeName() {
return blendMode != null ? PixelsBlendFactory.modeName(blendMode) : null;
}
/*
static
*/
public static Color blend2(Color foreColor, Color backColor, float weight, boolean ignoreTransparency) {
if (backColor.getRGB() == 0 && ignoreTransparency) {
return backColor;
}
return blend(foreColor, backColor, weight);
}
public static Color blend(Color foreColor, Color backColor, float weight) {
int red = blendValues(foreColor.getRed(), backColor.getRed(), weight);
int green = blendValues(foreColor.getGreen(), backColor.getRed(), weight);
int blue = blendValues(foreColor.getBlue(), backColor.getRed(), weight);
int alpha = blendValues(foreColor.getAlpha(), backColor.getRed(), weight);
Color newColor = new Color(
Math.min(Math.max(red, 0), 255),
Math.min(Math.max(green, 0), 255),
Math.min(Math.max(blue, 0), 255),
Math.min(Math.max(alpha, 0), 255));
return newColor;
}
public static float fixWeight(float v) {
if (v > 1f) {
return 1f;
} else if (v < 0) {
return 0f;
} else {
return v;
}
}
public static int blendValues(int A, int B, float weight) {
float w = fixWeight(weight);
return (int) (A * w + B * (1.0f - w));
}
public static BufferedImage blend(FxTask task, BufferedImage overlay, BufferedImage baseImage,
int x, int y, PixelsBlend blender) {
try {
if (overlay == null || baseImage == null || blender == null) {
return null;
}
int imageType = BufferedImage.TYPE_INT_ARGB;
DoubleRectangle rect = DoubleRectangle.xywh(x, y, overlay.getWidth(), overlay.getHeight());
BufferedImage target = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(), imageType);
for (int j = 0; j < baseImage.getHeight(); ++j) {
if (task != null && !task.isWorking()) {
return null;
}
for (int i = 0; i < baseImage.getWidth(); ++i) {
if (task != null && !task.isWorking()) {
return null;
}
int basePixel = baseImage.getRGB(i, j);
if (DoubleShape.contains(rect, i, j)) {
int overlayPixel = overlay.getRGB(i - x, j - y);
target.setRGB(i, j, blender.blend(overlayPixel, basePixel));
} else {
target.setRGB(i, j, basePixel);
}
}
}
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return overlay;
}
}
/*
get/set
*/
public ImagesBlendMode getBlendMode() {
return blendMode;
}
public PixelsBlend setBlendMode(ImagesBlendMode blendMode) {
this.blendMode = blendMode;
return this;
}
public float getWeight() {
return weight;
}
public PixelsBlend setWeight(float weight) {
this.weight = fixWeight(weight);
return this;
}
public boolean isBaseAbove() {
return baseAbove;
}
public PixelsBlend setBaseAbove(boolean orderReversed) {
this.baseAbove = orderReversed;
return this;
}
public TransparentAs getBaseTransparentAs() {
return baseTransparentAs;
}
public PixelsBlend setBaseTransparentAs(TransparentAs baseTransparentAs) {
this.baseTransparentAs = baseTransparentAs;
return this;
}
public TransparentAs getOverlayTransparentAs() {
return overlayTransparentAs;
}
public PixelsBlend setOverlayTransparentAs(TransparentAs overlayTransparentAs) {
this.overlayTransparentAs = overlayTransparentAs;
return this;
}
public Color getForeColor() {
return foreColor;
}
public void setForeColor(Color foreColor) {
this.foreColor = foreColor;
}
public Color getBackColor() {
return backColor;
}
public void setBackColor(Color backColor) {
this.backColor = backColor;
}
public int getRed() {
return red;
}
public void setRed(int red) {
this.red = red;
}
public int getGreen() {
return green;
}
public void setGreen(int green) {
this.green = green;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
public int getAlpha() {
return alpha;
}
public void setAlpha(int alpha) {
this.alpha = alpha;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageBinary.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageBinary.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.image.tools.AlphaTools;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2019-2-15
* @License Apache License Version 2.0
*/
public class ImageBinary extends PixelsOperation {
protected BinaryAlgorithm algorithm;
private BufferedImage defaultBinary;
private int threshold, blackInt;
public static enum BinaryAlgorithm {
OTSU, Threshold, Default
}
public ImageBinary() {
init();
}
final public void init() {
intPara1 = -1;
defaultBinary = null;
operationType = OperationType.BlackOrWhite;
algorithm = BinaryAlgorithm.Default;
blackInt = Color.BLACK.getRGB();
}
public ImageBinary(Image image) {
init();
this.image = SwingFXUtils.fromFXImage(image, null);
}
@Override
public BufferedImage start() {
if (image == null || operationType == null
|| operationType != OperationType.BlackOrWhite) {
return image;
}
threshold = -1;
if (algorithm == BinaryAlgorithm.OTSU) {
threshold = threshold(task, image);
} else if (algorithm == BinaryAlgorithm.Threshold) {
threshold = intPara1;
}
if (threshold <= 0) {
algorithm = BinaryAlgorithm.Default;
defaultBinary = byteBinary(task, image);
}
return operateImage();
}
@Override
protected Color operateColor(Color color) {
Color newColor;
if (algorithm == BinaryAlgorithm.Default) {
if (blackInt == defaultBinary.getRGB(currentX, currentY)) {
newColor = Color.BLACK;
} else {
newColor = Color.WHITE;
}
} else {
if (ColorConvertTools.color2grayValue(color) < threshold) {
newColor = Color.BLACK;
} else {
newColor = Color.WHITE;
}
}
return newColor;
}
/*
static
*/
public static BufferedImage byteBinary(FxTask task, BufferedImage srcImage) {
try {
int width = srcImage.getWidth();
int height = srcImage.getHeight();
BufferedImage naImage = AlphaTools.removeAlpha(task, srcImage, Color.WHITE);
BufferedImage binImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = binImage.createGraphics();
if (AppVariables.ImageHints != null) {
g.addRenderingHints(AppVariables.ImageHints);
}
g.drawImage(naImage, 0, 0, null);
g.dispose();
return binImage;
} catch (Exception e) {
MyBoxLog.error(e);
return srcImage;
}
}
public static BufferedImage intBinary(FxTask task, BufferedImage image) {
try {
int width = image.getWidth();
int height = image.getHeight();
int threshold = threshold(task, image);
if (threshold < 0) {
return null;
}
int WHITE = Color.WHITE.getRGB();
int BLACK = Color.BLACK.getRGB();
BufferedImage binImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
binImage.setRGB(x, y, 0);
} else {
int grey = ColorConvertTools.pixel2grayValue(p);
if (grey > threshold) {
binImage.setRGB(x, y, WHITE);
} else {
binImage.setRGB(x, y, BLACK);
}
}
}
}
return binImage;
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
public static Image binary(FxTask task, Image image) {
try {
BufferedImage bm = SwingFXUtils.fromFXImage(image, null);
bm = byteBinary(task, bm);
return SwingFXUtils.toFXImage(bm, null);
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
// OTSU algorithm: ICV=PA∗(MA−M)2+PB∗(MB−M)2
// https://blog.csdn.net/taoyanbian1022/article/details/9030825
// https://blog.csdn.net/liyuanbhu/article/details/49387483
public static int threshold(FxTask task, BufferedImage image) {
try {
if (image == null) {
return -1;
}
int width = image.getWidth();
int height = image.getHeight();
int[] grayNumber = new int[256];
float pixelTotal = 0;
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return -1;
}
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return -1;
}
int p = image.getRGB(i, j);
if (p == 0) {
continue;
}
pixelTotal++;
int gray = ColorConvertTools.pixel2grayValue(p);
grayNumber[gray]++;
}
}
float[] grayRadio = new float[256];
for (int i = 0; i < 256; ++i) {
if (task != null && !task.isWorking()) {
return -1;
}
grayRadio[i] = grayNumber[i] / pixelTotal;
}
float backgroundNumber, foregroundNumber, backgoundValue, foregroundValue;
float backgoundAverage, foregroundAverage, imageAverage, delta, deltaMax = 0;
int threshold = 0;
for (int gray = 0; gray < 256; gray++) {
if (task != null && !task.isWorking()) {
return -1;
}
backgroundNumber = 0;
foregroundNumber = 0;
backgoundValue = 0;
foregroundValue = 0;
for (int i = 0; i < 256; ++i) {
if (task != null && !task.isWorking()) {
return -1;
}
if (i <= gray) {
backgroundNumber += grayRadio[i];
backgoundValue += i * grayRadio[i];
} else {
foregroundNumber += grayRadio[i];
foregroundValue += i * grayRadio[i];
}
}
backgoundAverage = backgoundValue / backgroundNumber;
foregroundAverage = foregroundValue / foregroundNumber;
imageAverage = backgoundValue + foregroundValue;
delta = backgroundNumber * (backgoundAverage - imageAverage) * (backgoundAverage - imageAverage)
+ foregroundNumber * (foregroundAverage - imageAverage) * (foregroundAverage - imageAverage);
if (delta > deltaMax) {
deltaMax = delta;
threshold = gray;
}
}
// MyBoxLog.debug("threshold:" + threshold);
return threshold;
} catch (Exception e) {
MyBoxLog.error(e);
return -1;
}
}
public static int threshold(FxTask task, File file) {
try {
BufferedImage bufferImage = ImageFileReaders.readImage(task, file);
return threshold(task, bufferImage);
} catch (Exception e) {
MyBoxLog.error(e);
return -1;
}
}
public static int threshold(FxTask task, Image image) {
try {
return threshold(task, SwingFXUtils.fromFXImage(image, null));
} catch (Exception e) {
MyBoxLog.error(e);
return -1;
}
}
/*
get/set
*/
public BinaryAlgorithm getAlgorithm() {
return algorithm;
}
public ImageBinary setAlgorithm(BinaryAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public int getThreshold() {
return threshold;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageCombine.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageCombine.java | package mara.mybox.image.data;
import javafx.scene.paint.Color;
/**
* @Author Mara
* @CreateDate 2018-9-6 9:08:16
* @License Apache License Version 2.0
*/
public class ImageCombine {
private int columnsValue, intervalValue, MarginsValue, arrayType, sizeType;
private int eachWidthValue, eachHeightValue, totalWidthValue, totalHeightValue;
private Color bgColor = Color.WHITE;
public static class ArrayType {
public static int SingleColumn = 0;
public static int SingleRow = 1;
public static int ColumnsNumber = 2;
}
public static class CombineSizeType {
public static int KeepSize = 0;
public static int AlignAsBigger = 1;
public static int AlignAsSmaller = 2;
public static int EachWidth = 3;
public static int EachHeight = 4;
public static int TotalWidth = 5;
public static int TotalHeight = 6;
}
public ImageCombine() {
}
public int getColumnsValue() {
return columnsValue;
}
public void setColumnsValue(int columnsValue) {
this.columnsValue = columnsValue;
}
public int getIntervalValue() {
return intervalValue;
}
public void setIntervalValue(int intervalValue) {
this.intervalValue = intervalValue;
}
public int getMarginsValue() {
return MarginsValue;
}
public void setMarginsValue(int MarginsValue) {
this.MarginsValue = MarginsValue;
}
public int getArrayType() {
return arrayType;
}
public void setArrayType(int arrayType) {
this.arrayType = arrayType;
}
public int getSizeType() {
return sizeType;
}
public void setSizeType(int sizeType) {
this.sizeType = sizeType;
}
public int getEachWidthValue() {
return eachWidthValue;
}
public void setEachWidthValue(int eachWidthValue) {
this.eachWidthValue = eachWidthValue;
}
public int getEachHeightValue() {
return eachHeightValue;
}
public void setEachHeightValue(int eachHeightValue) {
this.eachHeightValue = eachHeightValue;
}
public int getTotalWidthValue() {
return totalWidthValue;
}
public void setTotalWidthValue(int totalWidthValue) {
this.totalWidthValue = totalWidthValue;
}
public int getTotalHeightValue() {
return totalHeightValue;
}
public void setTotalHeightValue(int totalHeightValue) {
this.totalHeightValue = totalHeightValue;
}
public Color getBgColor() {
return bgColor;
}
public void setBgColor(Color bgColor) {
this.bgColor = bgColor;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageKMeans.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageKMeans.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
import mara.mybox.color.ColorMatch;
import mara.mybox.data.ListKMeans;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-2-20
* @License Apache License Version 2.0
*/
public class ImageKMeans extends ListKMeans<Color> {
protected ColorMatch colorMatch;
protected Color[] colors;
protected int dataSize; // can not handle big image
public ImageKMeans() {
}
public static ImageKMeans create() {
return new ImageKMeans();
}
public ImageKMeans init(BufferedImage image, ColorMatch match) {
try {
int w = image.getWidth();
int h = image.getHeight();
if (1l * w * h >= Integer.MAX_VALUE) {
if (task != null) {
task.setError(message("TooLargeToHandle"));
} else {
MyBoxLog.error(message("TooLargeToHandle"));
}
return null;
}
colorMatch = match != null ? match : new ColorMatch();
dataSize = w * h;
colors = new Color[dataSize];
int index = 0;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
colors[index++] = new Color(image.getRGB(x, y));
}
}
return this;
} catch (Exception e) {
return null;
}
}
@Override
public boolean isDataEmpty() {
return colors == null;
}
@Override
public int dataSize() {
return dataSize;
}
@Override
public Color getData(int index) {
try {
return colors[index];
} catch (Exception e) {
return null;
}
}
@Override
public List<Color> allData() {
return Arrays.asList(colors);
}
@Override
public boolean run() {
if (colorMatch == null || isDataEmpty()) {
return false;
}
return super.run();
}
@Override
public double distance(Color p1, Color p2) {
try {
if (p1 == null || p2 == null) {
return Double.MAX_VALUE;
}
return colorMatch.distance(p1, p2);
} catch (Exception e) {
MyBoxLog.debug(e);
return Double.MAX_VALUE;
}
}
@Override
public boolean equal(Color p1, Color p2) {
try {
if (p1 == null || p2 == null) {
return false;
}
return colorMatch.isMatch(p1, p2);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public Color calculateCenters(List<Integer> cluster) {
try {
if (cluster == null || cluster.isEmpty()) {
return null;
}
Color color;
int r = 0, g = 0, b = 0;
for (Integer index : cluster) {
if (task != null && !task.isWorking()) {
return null;
}
color = getData(index);
if (color == null) {
continue;
}
r += color.getRed();
g += color.getGreen();
b += color.getBlue();
}
int size = cluster.size();
color = new Color(r / size, g / size, b / size);
return color;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
get/set
*/
public double getThreshold() {
return colorMatch.getThreshold();
}
public ImageKMeans setThreshold(double threshold) {
colorMatch.setThreshold(threshold);
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageScopeFactory.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageScopeFactory.java | package mara.mybox.image.data;
import javafx.scene.image.Image;
import mara.mybox.data.DoubleCircle;
import mara.mybox.data.DoublePolygon;
import mara.mybox.image.data.ImageScope.ShapeType;
import mara.mybox.image.tools.ImageScopeTools;
/**
* @Author Mara
* @CreateDate 2018-8-1 16:22:41
* @License Apache License Version 2.0
*/
public class ImageScopeFactory {
public static ImageScope create(ImageScope sourceScope) {
try {
ImageScope newScope;
Image image = sourceScope.getImage();
ShapeType shapeType = sourceScope.getShapeType();
if (shapeType == null) {
shapeType = ShapeType.Whole;
}
switch (shapeType) {
case Whole:
newScope = new Whole(image);
break;
case Rectangle:
newScope = new Rectangle(image);
break;
case Circle:
newScope = new Circle(image);
break;
case Ellipse:
newScope = new Ellipse(image);
break;
case Polygon:
newScope = new Polygon(image);
break;
case Matting4:
newScope = new Matting4(image);
break;
case Matting8:
newScope = new Matting8(image);
break;
case Outline:
newScope = new Outline(image);
break;
default:
newScope = new Whole(image);
}
ImageScopeTools.cloneValues(newScope, sourceScope);
return newScope;
} catch (Exception e) {
// MyBoxLog.debug(e);
return sourceScope;
}
}
static class Whole extends ImageScope {
public Whole(Image image) {
this.image = image;
this.shapeType = ShapeType.Whole;
}
}
static class Rectangle extends ImageScope {
public Rectangle(Image image) {
this.image = image;
this.shapeType = ShapeType.Rectangle;
}
@Override
public boolean inShape(int x, int y) {
return ImageScopeTools.inShape(rectangle, shapeExcluded, x, y);
}
}
static class Circle extends ImageScope {
public Circle(Image image) {
this.image = image;
this.shapeType = ShapeType.Circle;
if (image != null) {
circle = new DoubleCircle(image.getWidth() / 2, image.getHeight() / 2,
image.getHeight() / 4);
} else {
circle = new DoubleCircle();
}
}
@Override
public boolean inShape(int x, int y) {
return ImageScopeTools.inShape(circle, shapeExcluded, x, y);
}
}
static class Ellipse extends ImageScope {
public Ellipse(Image image) {
this.image = image;
this.shapeType = ShapeType.Ellipse;
}
@Override
public boolean inShape(int x, int y) {
return ImageScopeTools.inShape(ellipse, shapeExcluded, x, y);
}
}
static class Polygon extends ImageScope {
public Polygon(Image image) {
this.image = image;
this.shapeType = ShapeType.Polygon;
if (image != null) {
polygon = new DoublePolygon();
}
}
@Override
public boolean inShape(int x, int y) {
return ImageScopeTools.inShape(polygon, shapeExcluded, x, y);
}
}
static class Outline extends ImageScope {
public Outline(Image image) {
this.image = image;
this.shapeType = ShapeType.Outline;
}
@Override
public boolean inShape(int x, int y) {
boolean in = outline != null && outline.getRGB(x, y) > 0;
return shapeExcluded ? !in : in;
}
}
static class Matting4 extends ImageScope {
public Matting4(Image image) {
this.image = image;
this.shapeType = ShapeType.Matting4;
}
}
static class Matting8 extends ImageScope {
public Matting8(Image image) {
this.image = image;
this.shapeType = ShapeType.Matting8;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageRegionKMeans.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageRegionKMeans.java | package mara.mybox.image.data;
import java.awt.Color;
import java.util.List;
import mara.mybox.color.ColorMatch;
import mara.mybox.data.ListKMeans;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.image.data.ImageQuantizationFactory.KMeansRegion;
/**
* @Author Mara
* @CreateDate 2019-10-7
* @Version 1.0
* @License Apache License Version 2.0
*/
public class ImageRegionKMeans extends ListKMeans<Color> {
protected KMeansRegion regionQuantization;
protected ColorMatch colorMatch;
protected List<Color> colors;
public ImageRegionKMeans() {
}
public static ImageRegionKMeans create() {
return new ImageRegionKMeans();
}
public ImageRegionKMeans init(KMeansRegion quantization) {
try {
if (quantization == null) {
return this;
}
regionQuantization = quantization;
colorMatch = quantization.colorMatch;
colors = regionQuantization.regionColors;
} catch (Exception e) {
MyBoxLog.debug(e);
}
return this;
}
@Override
public boolean isDataEmpty() {
return colors == null || colors.isEmpty();
}
@Override
public int dataSize() {
return colors.size();
}
@Override
public Color getData(int index) {
return colors.get(index);
}
@Override
public List<Color> allData() {
return regionQuantization.regionColors;
}
@Override
public boolean run() {
if (colorMatch == null
|| regionQuantization == null || isDataEmpty()
|| regionQuantization.rgbPalette.counts == null) {
return false;
}
return super.run();
}
@Override
public double distance(Color p1, Color p2) {
try {
if (p1 == null || p2 == null) {
return Double.MAX_VALUE;
}
return colorMatch.distance(p1, p2);
} catch (Exception e) {
MyBoxLog.debug(e);
return Double.MAX_VALUE;
}
}
@Override
public boolean equal(Color p1, Color p2) {
try {
if (p1 == null || p2 == null) {
return false;
}
return colorMatch.isMatch(p1, p2);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public Color calculateCenters(List<Integer> cluster) {
try {
if (cluster == null || cluster.isEmpty()) {
return null;
}
long maxCount = 0;
Color centerColor = null;
for (Integer index : cluster) {
if (task != null && !task.isWorking()) {
return null;
}
Color regionColor = getData(index);
Long colorCount = regionQuantization.rgbPalette.counts.get(regionColor);
if (colorCount != null && colorCount > maxCount) {
centerColor = regionColor;
maxCount = colorCount;
}
}
return centerColor;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
@Override
public Color preProcess(Color color) {
return regionQuantization.map(new Color(color.getRGB(), false));
}
/*
get/set
*/
public double getThreshold() {
return colorMatch.getThreshold();
}
public ImageRegionKMeans setThreshold(double threshold) {
colorMatch.setThreshold(threshold);
return this;
}
public KMeansRegion getRegionQuantization() {
return regionQuantization;
}
public ImageRegionKMeans setRegionQuantization(KMeansRegion regionQuantization) {
this.regionQuantization = regionQuantization;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageFileInformation.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageFileInformation.java | package mara.mybox.image.data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data.FileInformation;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.tools.FileNameTools;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import thridparty.image4j.ICODecoder;
/**
* @Author Mara
* @CreateDate 2018-6-19
* @License Apache License Version 2.0
*/
public class ImageFileInformation extends FileInformation {
protected String imageFormat, password;
protected ImageInformation imageInformation;
protected List<ImageInformation> imagesInformation;
protected int numberOfImages;
public ImageFileInformation() {
}
public ImageFileInformation(File file) {
super(file);
if (file != null) {
imageFormat = FileNameTools.ext(file.getName()).toLowerCase();
}
}
/*
static methods
*/
public static ImageFileInformation create(FxTask task, File file) {
return create(task, file, null);
}
public static ImageFileInformation create(FxTask task, File file, String password) {
try {
if (file == null || !file.exists()) {
return null;
}
String suffix = FileNameTools.ext(file.getName());
if (suffix != null && suffix.equalsIgnoreCase("pdf")) {
return readPDF(task, file, password);
} else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) {
return readPPT(task, file);
} else if (suffix != null && (suffix.equalsIgnoreCase("ico") || suffix.equalsIgnoreCase("icon"))) {
return readIconFile(task, file);
} else {
return readImageFile(task, file);
}
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static ImageFileInformation clone(ImageFileInformation sourceInfo, ImageFileInformation targetInfo) {
if (sourceInfo == null || targetInfo == null) {
return null;
}
FileInformation.clone(sourceInfo, targetInfo);
targetInfo.imageFormat = sourceInfo.imageFormat;
targetInfo.password = sourceInfo.password;
targetInfo.imageInformation = sourceInfo.imageInformation;
targetInfo.imagesInformation = sourceInfo.imagesInformation;
targetInfo.createTime = sourceInfo.createTime;
targetInfo.numberOfImages = sourceInfo.numberOfImages;
return targetInfo;
}
public static ImageFileInformation readImageFile(FxTask task, File file) {
return ImageFileReaders.readImageFileMetaData(task, file);
}
public static ImageFileInformation readIconFile(FxTask task, File file) {
ImageFileInformation fileInfo = new ImageFileInformation(file);
String format = "ico";
fileInfo.setImageFormat(format);
try {
List<BufferedImage> frames = ICODecoder.read(file);
if (frames != null) {
int num = frames.size();
fileInfo.setNumberOfImages(num);
List<ImageInformation> imagesInfo = new ArrayList<>();
ImageInformation imageInfo;
for (int i = 0; i < num; i++) {
if (task != null && !task.isWorking()) {
return null;
}
BufferedImage bufferedImage = frames.get(i);
imageInfo = ImageInformation.create(format, file);
imageInfo.setImageFileInformation(fileInfo);
imageInfo.setImageFormat(format);
imageInfo.setFile(file);
imageInfo.setCreateTime(fileInfo.getCreateTime());
imageInfo.setModifyTime(fileInfo.getModifyTime());
imageInfo.setFileSize(fileInfo.getFileSize());
imageInfo.setWidth(bufferedImage.getWidth());
imageInfo.setHeight(bufferedImage.getHeight());
imageInfo.setIsMultipleFrames(num > 1);
imageInfo.setIndex(i);
imageInfo.setImageType(BufferedImage.TYPE_INT_ARGB);
imageInfo.loadBufferedImage(bufferedImage);
imagesInfo.add(imageInfo);
}
fileInfo.setImagesInformation(imagesInfo);
if (!imagesInfo.isEmpty()) {
fileInfo.setImageInformation(imagesInfo.get(0));
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return fileInfo;
}
public static ImageFileInformation readPDF(FxTask task, File file, String password) {
ImageFileInformation fileInfo = new ImageFileInformation(file);
String format = "png";
fileInfo.setImageFormat(format);
fileInfo.setPassword(password);
try (PDDocument doc = Loader.loadPDF(file, password)) {
int num = doc.getNumberOfPages();
fileInfo.setNumberOfImages(num);
List<ImageInformation> imagesInfo = new ArrayList<>();
ImageInformation imageInfo;
for (int i = 0; i < num; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
PDPage page = doc.getPage(i);
PDRectangle rect = page.getBleedBox();
imageInfo = ImageInformation.create(format, file);
imageInfo.setImageFileInformation(fileInfo);
imageInfo.setImageFormat(format);
imageInfo.setPassword(password);
imageInfo.setFile(file);
imageInfo.setCreateTime(fileInfo.getCreateTime());
imageInfo.setModifyTime(fileInfo.getModifyTime());
imageInfo.setFileSize(fileInfo.getFileSize());
imageInfo.setWidth(Math.round(rect.getWidth()));
imageInfo.setHeight(Math.round(rect.getHeight()));
imageInfo.setIsMultipleFrames(num > 1);
imageInfo.setIndex(i);
imageInfo.setImageType(BufferedImage.TYPE_INT_RGB);
ImageInformation.checkMem(task, imageInfo);
imagesInfo.add(imageInfo);
}
fileInfo.setImagesInformation(imagesInfo);
if (!imagesInfo.isEmpty()) {
fileInfo.setImageInformation(imagesInfo.get(0));
}
doc.close();
} catch (Exception e) {
MyBoxLog.error(e);
}
return fileInfo;
}
public static ImageFileInformation readPPT(FxTask task, File file) {
ImageFileInformation fileInfo = new ImageFileInformation(file);
String format = "png";
fileInfo.setImageFormat(format);
try (SlideShow ppt = SlideShowFactory.create(file)) {
List<Slide> slides = ppt.getSlides();
int num = slides.size();
slides = null;
fileInfo.setNumberOfImages(num);
List<ImageInformation> imagesInfo = new ArrayList<>();
ImageInformation imageInfo;
int width = (int) Math.ceil(ppt.getPageSize().getWidth());
int height = (int) Math.ceil(ppt.getPageSize().getHeight());
for (int i = 0; i < num; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
imageInfo = ImageInformation.create(format, file);
imageInfo.setImageFileInformation(fileInfo);
imageInfo.setImageFormat(format);
imageInfo.setFile(file);
imageInfo.setCreateTime(fileInfo.getCreateTime());
imageInfo.setModifyTime(fileInfo.getModifyTime());
imageInfo.setFileSize(fileInfo.getFileSize());
imageInfo.setWidth(width);
imageInfo.setHeight(height);
imageInfo.setIsMultipleFrames(num > 1);
imageInfo.setIndex(i);
imageInfo.setImageType(BufferedImage.TYPE_INT_ARGB);
ImageInformation.checkMem(task, imageInfo);
imagesInfo.add(imageInfo);
}
fileInfo.setImagesInformation(imagesInfo);
if (!imagesInfo.isEmpty()) {
fileInfo.setImageInformation(imagesInfo.get(0));
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return fileInfo;
}
/*
get/set
*/
public String getImageFormat() {
return imageFormat;
}
public void setImageFormat(String imageFormat) {
this.imageFormat = imageFormat;
}
public List<ImageInformation> getImagesInformation() {
return imagesInformation;
}
public void setImagesInformation(List<ImageInformation> imagesInformation) {
this.imagesInformation = imagesInformation;
}
public ImageInformation getImageInformation() {
return imageInformation;
}
public void setImageInformation(ImageInformation imageInformation) {
this.imageInformation = imageInformation;
}
public int getNumberOfImages() {
return numberOfImages;
}
public void setNumberOfImages(int numberOfImages) {
this.numberOfImages = numberOfImages;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageInformationPng.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageInformationPng.java | package mara.mybox.image.data;
import java.io.File;
import java.util.List;
import mara.mybox.color.CIEData;
/**
* @Author Mara
* @CreateDate 2018-6-19
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/png_metadata.html#image
public class ImageInformationPng extends ImageInformation {
protected String colorType, compressionMethod, unitSpecifier, filterMethod, interlaceMethod,
renderingIntent;
protected int pixelsPerUnitXAxis = -1, pixelsPerUnitYAxis = -1, bKGD_Grayscale = -1, bKGD_Palette = -1,
sBIT_Grayscale = -1, sBIT_GrayAlpha_gray = -1, sBIT_GrayAlpha_alpha = -1,
sBIT_RGB_red = -1, sBIT_RGB_green = -1, sBIT_RGB_blue = -1,
sBIT_RGBAlpha_red = -1, sBIT_RGBAlpha_green = -1, sBIT_RGBAlpha_blue = -1, sBIT_RGBAlpha_alpha = -1,
sBIT_Palette_red = -1, sBIT_Palette_green = -1, sBIT_Palette_blue = -1, tRNS_Grayscale = -1,
tRNS_Palette_index = -1, tRNS_Palette_alpha = -1;
protected ImageColor bKGD_RGB, tRNS_RGB;
protected List<ImageColor> pngPalette, suggestedPalette;
protected int pngPaletteSize, suggestedPaletteSize;
protected CIEData white, red, blue, green;
public ImageInformationPng(File file) {
super(file);
}
/*
get/set
*/
public String getColorType() {
return colorType;
}
public void setColorType(String colorType) {
this.colorType = colorType;
}
public String getCompressionMethod() {
return compressionMethod;
}
public void setCompressionMethod(String compressionMethod) {
this.compressionMethod = compressionMethod;
}
public String getUnitSpecifier() {
return unitSpecifier;
}
public void setUnitSpecifier(String unitSpecifier) {
this.unitSpecifier = unitSpecifier;
}
public int getPixelsPerUnitXAxis() {
return pixelsPerUnitXAxis;
}
public void setPixelsPerUnitXAxis(int pixelsPerUnitXAxis) {
this.pixelsPerUnitXAxis = pixelsPerUnitXAxis;
}
public int getPixelsPerUnitYAxis() {
return pixelsPerUnitYAxis;
}
public void setPixelsPerUnitYAxis(int pixelsPerUnitYAxis) {
this.pixelsPerUnitYAxis = pixelsPerUnitYAxis;
}
public String getFilterMethod() {
return filterMethod;
}
public void setFilterMethod(String filterMethod) {
this.filterMethod = filterMethod;
}
public String getInterlaceMethod() {
return interlaceMethod;
}
public void setInterlaceMethod(String interlaceMethod) {
this.interlaceMethod = interlaceMethod;
}
public List<ImageColor> getPngPalette() {
return pngPalette;
}
public void setPngPalette(List<ImageColor> pngPalette) {
this.pngPalette = pngPalette;
}
public int getbKGD_Grayscale() {
return bKGD_Grayscale;
}
public void setbKGD_Grayscale(int bKGD_Grayscale) {
this.bKGD_Grayscale = bKGD_Grayscale;
}
public int getbKGD_Palette() {
return bKGD_Palette;
}
public void setbKGD_Palette(int bKGD_Palette) {
this.bKGD_Palette = bKGD_Palette;
}
public ImageColor getbKGD_RGB() {
return bKGD_RGB;
}
public void setbKGD_RGB(ImageColor bKGD_RGB) {
this.bKGD_RGB = bKGD_RGB;
}
public CIEData getWhite() {
return white;
}
public void setWhite(CIEData white) {
this.white = white;
}
public CIEData getRed() {
return red;
}
public void setRed(CIEData red) {
this.red = red;
}
public CIEData getBlue() {
return blue;
}
public void setBlue(CIEData blue) {
this.blue = blue;
}
public CIEData getGreen() {
return green;
}
public void setGreen(CIEData green) {
this.green = green;
}
public String getRenderingIntent() {
return renderingIntent;
}
public void setRenderingIntent(String renderingIntent) {
this.renderingIntent = renderingIntent;
}
public int getsBIT_Grayscale() {
return sBIT_Grayscale;
}
public void setsBIT_Grayscale(int sBIT_Grayscale) {
this.sBIT_Grayscale = sBIT_Grayscale;
}
public int getsBIT_GrayAlpha_gray() {
return sBIT_GrayAlpha_gray;
}
public void setsBIT_GrayAlpha_gray(int sBIT_GrayAlpha_gray) {
this.sBIT_GrayAlpha_gray = sBIT_GrayAlpha_gray;
}
public int getsBIT_GrayAlpha_alpha() {
return sBIT_GrayAlpha_alpha;
}
public void setsBIT_GrayAlpha_alpha(int sBIT_GrayAlpha_alpha) {
this.sBIT_GrayAlpha_alpha = sBIT_GrayAlpha_alpha;
}
public int getsBIT_RGB_red() {
return sBIT_RGB_red;
}
public void setsBIT_RGB_red(int sBIT_RGB_red) {
this.sBIT_RGB_red = sBIT_RGB_red;
}
public int getsBIT_RGB_green() {
return sBIT_RGB_green;
}
public void setsBIT_RGB_green(int sBIT_RGB_green) {
this.sBIT_RGB_green = sBIT_RGB_green;
}
public int getsBIT_RGB_blue() {
return sBIT_RGB_blue;
}
public void setsBIT_RGB_blue(int sBIT_RGB_blue) {
this.sBIT_RGB_blue = sBIT_RGB_blue;
}
public int getsBIT_RGBAlpha_red() {
return sBIT_RGBAlpha_red;
}
public void setsBIT_RGBAlpha_red(int sBIT_RGBAlpha_red) {
this.sBIT_RGBAlpha_red = sBIT_RGBAlpha_red;
}
public int getsBIT_RGBAlpha_green() {
return sBIT_RGBAlpha_green;
}
public void setsBIT_RGBAlpha_green(int sBIT_RGBAlpha_green) {
this.sBIT_RGBAlpha_green = sBIT_RGBAlpha_green;
}
public int getsBIT_RGBAlpha_blue() {
return sBIT_RGBAlpha_blue;
}
public void setsBIT_RGBAlpha_blue(int sBIT_RGBAlpha_blue) {
this.sBIT_RGBAlpha_blue = sBIT_RGBAlpha_blue;
}
public int getsBIT_RGBAlpha_alpha() {
return sBIT_RGBAlpha_alpha;
}
public void setsBIT_RGBAlpha_alpha(int sBIT_RGBAlpha_alpha) {
this.sBIT_RGBAlpha_alpha = sBIT_RGBAlpha_alpha;
}
public int getsBIT_Palette_red() {
return sBIT_Palette_red;
}
public void setsBIT_Palette_red(int sBIT_Palette_red) {
this.sBIT_Palette_red = sBIT_Palette_red;
}
public int getsBIT_Palette_green() {
return sBIT_Palette_green;
}
public void setsBIT_Palette_green(int sBIT_Palette_green) {
this.sBIT_Palette_green = sBIT_Palette_green;
}
public int getsBIT_Palette_blue() {
return sBIT_Palette_blue;
}
public void setsBIT_Palette_blue(int sBIT_Palette_blue) {
this.sBIT_Palette_blue = sBIT_Palette_blue;
}
public List<ImageColor> getSuggestedPalette() {
return suggestedPalette;
}
public void setSuggestedPalette(List<ImageColor> suggestedPalette) {
this.suggestedPalette = suggestedPalette;
}
public int gettRNS_Grayscale() {
return tRNS_Grayscale;
}
public void settRNS_Grayscale(int tRNS_Grayscale) {
this.tRNS_Grayscale = tRNS_Grayscale;
}
public int gettRNS_Palette_index() {
return tRNS_Palette_index;
}
public void settRNS_Palette_index(int tRNS_Palette_index) {
this.tRNS_Palette_index = tRNS_Palette_index;
}
public int gettRNS_Palette_alpha() {
return tRNS_Palette_alpha;
}
public void settRNS_Palette_alpha(int tRNS_Palette_alpha) {
this.tRNS_Palette_alpha = tRNS_Palette_alpha;
}
public ImageColor gettRNS_RGB() {
return tRNS_RGB;
}
public void settRNS_RGB(ImageColor tRNS_RGB) {
this.tRNS_RGB = tRNS_RGB;
}
public int getPngPaletteSize() {
return pngPaletteSize;
}
public void setPngPaletteSize(int pngPaletteSize) {
this.pngPaletteSize = pngPaletteSize;
}
public int getSuggestedPaletteSize() {
return suggestedPaletteSize;
}
public void setSuggestedPaletteSize(int suggestedPaletteSize) {
this.suggestedPaletteSize = suggestedPaletteSize;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageStatistic.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageStatistic.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ColorConvertTools;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import mara.mybox.image.tools.ColorComponentTools.ColorComponent;
import mara.mybox.calculation.IntStatistic;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2019-2-8 19:26:01
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ImageStatistic {
protected BufferedImage image;
protected Map<ColorComponent, ComponentStatistic> data;
protected long nonTransparent;
public ImageStatistic analyze(FxTask task) {
try {
if (image == null) {
return null;
}
Color color;
long redSum, greenSum, blueSum, alphaSum, hueSum, saturationSum, brightnessSum, graySum;
redSum = greenSum = blueSum = alphaSum = hueSum = saturationSum = brightnessSum = graySum = 0;
int redMaximum, greenMaximum, blueMaximum, alphaMaximum, hueMaximum, saturationMaximum, brightnessMaximum, grayMaximum;
redMaximum = greenMaximum = blueMaximum = alphaMaximum = hueMaximum = saturationMaximum = brightnessMaximum = grayMaximum = 0;
int redMinimum, greenMinimum, blueMinimum, alphaMinimum, hueMinimum, saturationMinimum, brightnessMinimum, grayMinimum;
redMinimum = greenMinimum = blueMinimum = alphaMinimum = hueMinimum = saturationMinimum = brightnessMinimum = grayMinimum = 255;
int v;
int[] grayHistogram = new int[256];
int[] redHistogram = new int[256];
int[] greenHistogram = new int[256];
int[] blueHistogram = new int[256];
int[] alphaHistogram = new int[256];
int[] hueHistogram = new int[361];
int[] saturationHistogram = new int[101];
int[] brightnessHistogram = new int[101];
nonTransparent = 0;
for (int y = 0; y < image.getHeight(); y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < image.getWidth(); x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
continue;
}
nonTransparent++;
color = new Color(p, true);
v = color.getRed();
redHistogram[v]++;
redSum += v;
if (v > redMaximum) {
redMaximum = v;
}
if (v < redMinimum) {
redMinimum = v;
}
v = color.getGreen();
greenHistogram[v]++;
greenSum += v;
if (v > greenMaximum) {
greenMaximum = v;
}
if (v < greenMinimum) {
greenMinimum = v;
}
v = color.getBlue();
blueHistogram[v]++;
blueSum += v;
if (v > blueMaximum) {
blueMaximum = v;
}
if (v < blueMinimum) {
blueMinimum = v;
}
v = color.getAlpha();
alphaHistogram[v]++;
alphaSum += v;
if (v > alphaMaximum) {
alphaMaximum = v;
}
if (v < alphaMinimum) {
alphaMinimum = v;
}
v = (int) (ColorConvertTools.getHue(color) * 360);
hueHistogram[v]++;
hueSum += v;
if (v > hueMaximum) {
hueMaximum = v;
}
if (v < hueMinimum) {
hueMinimum = v;
}
v = (int) (ColorConvertTools.getSaturation(color) * 100);
saturationHistogram[v]++;
saturationSum += v;
if (v > saturationMaximum) {
saturationMaximum = v;
}
if (v < saturationMinimum) {
saturationMinimum = v;
}
v = (int) (ColorConvertTools.getBrightness(color) * 100);
brightnessHistogram[v]++;
brightnessSum += v;
if (v > brightnessMaximum) {
brightnessMaximum = v;
}
if (v < brightnessMinimum) {
brightnessMinimum = v;
}
v = ColorConvertTools.color2grayValue(color);
grayHistogram[v]++;
graySum += v;
if (v > grayMaximum) {
grayMaximum = v;
}
if (v < grayMinimum) {
grayMinimum = v;
}
}
}
if (nonTransparent == 0) {
return null;
}
int redMean = (int) (redSum / nonTransparent);
int greenMean = (int) (greenSum / nonTransparent);
int blueMean = (int) (blueSum / nonTransparent);
int alphaMean = (int) (alphaSum / nonTransparent);
int hueMean = (int) (hueSum / nonTransparent);
int saturationMean = (int) (saturationSum / nonTransparent);
int brightnessMean = (int) (brightnessSum / nonTransparent);
int grayMean = (int) (graySum / nonTransparent);
double redVariable, greenVariable, blueVariable, alphaVariable, hueVariable, saturationVariable, brightnessVariable, grayVariable;
redVariable = greenVariable = blueVariable = alphaVariable = hueVariable = saturationVariable = brightnessVariable = grayVariable = 0;
double redSkewness, greenSkewness, blueSkewness, alphaSkewness, hueSkewness, saturationSkewness, brightnessSkewness, graySkewness;
redSkewness = greenSkewness = blueSkewness = alphaSkewness = hueSkewness = saturationSkewness = brightnessSkewness = graySkewness = 0;
double d;
for (int y = 0; y < image.getHeight(); y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < image.getWidth(); x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
continue;
}
color = new Color(p, true);
d = color.getRed();
redVariable += Math.pow(d - redMean, 2);
redSkewness += Math.pow(d - redMean, 3);
d = color.getGreen();
greenVariable += Math.pow(d - greenMean, 2);
greenSkewness += Math.pow(d - greenMean, 3);
d = color.getBlue();
blueVariable += Math.pow(d - blueMean, 2);
blueSkewness += Math.pow(d - blueMean, 3);
d = color.getAlpha();
alphaVariable += Math.pow(d - alphaMean, 2);
alphaSkewness += Math.pow(d - alphaMean, 3);
d = ColorConvertTools.getHue(color) * 100;
hueVariable += Math.pow(d - hueMean, 2);
hueSkewness += Math.pow(d - hueMean, 3);
d = ColorConvertTools.getSaturation(color) * 100;
saturationVariable += Math.pow(d - saturationMean, 2);
saturationSkewness += Math.pow(d - saturationMean, 3);
d = ColorConvertTools.getBrightness(color) * 100;
brightnessVariable += Math.pow(d - brightnessMean, 2);
brightnessSkewness += Math.pow(d - brightnessMean, 3);
d = ColorConvertTools.color2grayValue(color);
grayVariable += Math.pow(d - grayMean, 2);
graySkewness += Math.pow(d - grayMean, 3);
}
}
double p = 1d / nonTransparent;
redVariable = Math.sqrt(redVariable * p);
greenVariable = Math.sqrt(greenVariable * p);
blueVariable = Math.sqrt(blueVariable * p);
alphaVariable = Math.sqrt(alphaVariable * p);
hueVariable = Math.sqrt(hueVariable * p);
saturationVariable = Math.sqrt(saturationVariable * p);
brightnessVariable = Math.sqrt(brightnessVariable * p);
grayVariable = Math.sqrt(grayVariable * p);
redSkewness = Math.abs(Math.cbrt(redSkewness * p));
greenSkewness = Math.abs(Math.cbrt(greenSkewness * p));
blueSkewness = Math.abs(Math.cbrt(blueSkewness * p));
alphaSkewness = Math.abs(Math.cbrt(alphaSkewness * p));
hueSkewness = Math.abs(Math.cbrt(hueSkewness * p));
saturationSkewness = Math.abs(Math.cbrt(saturationSkewness * p));
brightnessSkewness = Math.abs(Math.cbrt(brightnessSkewness * p));
graySkewness = Math.abs(Math.cbrt(graySkewness * p));
IntStatistic grayStatistic = new IntStatistic(ColorComponent.Gray.name(),
graySum, grayMean, (int) grayVariable, (int) graySkewness,
grayMinimum, grayMaximum, grayHistogram);
ComponentStatistic grayData = ComponentStatistic.create().setComponent(ColorComponent.Gray).
setHistogram(grayHistogram).setStatistic(grayStatistic);
data.put(ColorComponent.Gray, grayData);
IntStatistic redStatistic = new IntStatistic(ColorComponent.RedChannel.name(),
redSum, redMean, (int) redVariable, (int) redSkewness,
redMinimum, redMaximum, redHistogram);
ComponentStatistic redData = ComponentStatistic.create().setComponent(ColorComponent.RedChannel).
setHistogram(redHistogram).setStatistic(redStatistic);
data.put(ColorComponent.RedChannel, redData);
IntStatistic greenStatistic = new IntStatistic(ColorComponent.GreenChannel.name(),
greenSum, greenMean, (int) greenVariable, (int) greenSkewness,
greenMinimum, greenMaximum, greenHistogram);
ComponentStatistic greenData = ComponentStatistic.create().setComponent(ColorComponent.GreenChannel).
setHistogram(greenHistogram).setStatistic(greenStatistic);
data.put(ColorComponent.GreenChannel, greenData);
IntStatistic blueStatistic = new IntStatistic(ColorComponent.BlueChannel.name(),
blueSum, blueMean, (int) blueVariable, (int) blueSkewness,
blueMinimum, blueMaximum, blueHistogram);
ComponentStatistic blueData = ComponentStatistic.create().setComponent(ColorComponent.BlueChannel).
setHistogram(blueHistogram).setStatistic(blueStatistic);
data.put(ColorComponent.BlueChannel, blueData);
IntStatistic hueStatistic = new IntStatistic(ColorComponent.Hue.name(),
hueSum, hueMean, (int) hueVariable, (int) hueSkewness,
hueMinimum, hueMaximum, hueHistogram);
ComponentStatistic hueData = ComponentStatistic.create().setComponent(ColorComponent.Hue).
setHistogram(hueHistogram).setStatistic(hueStatistic);
data.put(ColorComponent.Hue, hueData);
IntStatistic saturationStatistic = new IntStatistic(ColorComponent.Saturation.name(),
saturationSum, saturationMean, (int) saturationVariable, (int) saturationSkewness,
saturationMinimum, saturationMaximum, saturationHistogram);
ComponentStatistic saturationData = ComponentStatistic.create().setComponent(ColorComponent.Saturation).
setHistogram(saturationHistogram).setStatistic(saturationStatistic);
data.put(ColorComponent.Saturation, saturationData);
IntStatistic brightnessStatistic = new IntStatistic(ColorComponent.Brightness.name(),
brightnessSum, brightnessMean, (int) brightnessVariable, (int) brightnessSkewness,
brightnessMinimum, brightnessMaximum, brightnessHistogram);
ComponentStatistic brightnessData = ComponentStatistic.create().setComponent(ColorComponent.Brightness).
setHistogram(brightnessHistogram).setStatistic(brightnessStatistic);
data.put(ColorComponent.Brightness, brightnessData);
IntStatistic alphaStatistic = new IntStatistic(ColorComponent.AlphaChannel.name(),
alphaSum, alphaMean, (int) alphaVariable, (int) alphaSkewness,
alphaMinimum, alphaMaximum, alphaHistogram);
ComponentStatistic alphaData = ComponentStatistic.create().setComponent(ColorComponent.AlphaChannel).
setHistogram(alphaHistogram).setStatistic(alphaStatistic);
data.put(ColorComponent.AlphaChannel, alphaData);
return this;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public ComponentStatistic data(ColorComponent component) {
return data.get(component);
}
public int[] histogram(ColorComponent component) {
ComponentStatistic s = data.get(component);
return s.getHistogram();
}
public IntStatistic statistic(ColorComponent component) {
ComponentStatistic s = data.get(component);
return s.getStatistic();
}
public static int[] grayHistogram(FxTask task, BufferedImage image) {
if (image == null) {
return null;
}
BufferedImage grayImage = ImageGray.byteGray(task, image);
int[] histogram = new int[256];
for (int y = 0; y < image.getHeight(); y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < image.getWidth(); x++) {
int gray = new Color(grayImage.getRGB(x, y)).getRed();
histogram[gray]++;
}
}
return histogram;
}
/*
static
*/
public static ImageStatistic create(BufferedImage image) {
return new ImageStatistic().setImage(image).setData(new HashMap<>());
}
public static long nonTransparent(FxTask task, BufferedImage image) {
if (image == null) {
return 0;
}
long nonTransparent = 0;
for (int y = 0; y < image.getHeight(); y++) {
if (task != null && !task.isWorking()) {
return -1;
}
for (int x = 0; x < image.getWidth(); x++) {
if (task != null && !task.isWorking()) {
return -1;
}
if (image.getRGB(x, y) == 0) {
nonTransparent++;
}
}
}
return nonTransparent;
}
/*
get/set
*/
public BufferedImage getImage() {
return image;
}
public ImageStatistic setImage(BufferedImage image) {
this.image = image;
return this;
}
public Map<ColorComponent, ComponentStatistic> getData() {
return data;
}
public ImageStatistic setData(Map<ColorComponent, ComponentStatistic> data) {
this.data = data;
return this;
}
public long getNonTransparent() {
return nonTransparent;
}
public void setNonTransparent(long nonTransparent) {
this.nonTransparent = nonTransparent;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImagePixel.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImagePixel.java | package mara.mybox.image.data;
import java.awt.Color;
/**
* @Author Mara
* @CreateDate 2019-10-19
* @Version 1.0
* @License Apache License Version 2.0
*/
public class ImagePixel {
protected int x, y;
protected Color color;
public static ImagePixel create(int x, int y, Color color) {
return new ImagePixel().setX(x).setY(y).setColor(color);
}
public static ImagePixel create(Color color) {
return new ImagePixel().setColor(color);
}
public int getX() {
return x;
}
public ImagePixel setX(int x) {
this.x = x;
return this;
}
public int getY() {
return y;
}
public ImagePixel setY(int y) {
this.y = y;
return this;
}
public Color getColor() {
return color;
}
public ImagePixel setColor(Color color) {
this.color = color;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageInformation.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageInformation.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.image.tools.BufferedImageTools;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.CropTools;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.AppVariables.ImageHints;
import static mara.mybox.value.Languages.message;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
/**
* @Author Mara
* @CreateDate 2018-6-19
* @License Apache License Version 2.0
*/
public class ImageInformation extends ImageFileInformation {
protected ImageFileInformation imageFileInformation;
protected ImageInformation self;
protected int index, imageType, sampleScale, dpi, xscale, yscale;
protected double width, height, requiredWidth, maxWidth, thumbnailRotation;
protected String colorSpace, pixelsString, loadSizeString, fileSizeString,
profileName, profileCompressionMethod, metaDataXml, error;
protected boolean isMultipleFrames, isSampled, isScaled, needSample;
protected List<ImageTypeSpecifier> imageTypes;
protected ImageTypeSpecifier rawImageType;
protected LinkedHashMap<String, Object> standardAttributes, nativeAttributes;
protected Map<String, Map<String, List<Map<String, Object>>>> metaData;
protected Image image, thumbnail, regionImage;
protected long availableMem, bytesSize, requiredMem, totalRequiredMem;
protected byte[] iccProfile;
protected DoubleRectangle region;
public ImageInformation() {
initImage();
}
public ImageInformation(File file) {
super(file);
initImage();
if (file != null) {
imageFormat = FileNameTools.ext(file.getName());
}
if (imageFormat != null) {
imageFormat = imageFormat.toLowerCase();
}
}
public ImageInformation(Image image) {
this.image = image;
if (image != null) {
width = (int) image.getWidth();
height = (int) image.getHeight();
}
}
public final void initImage() {
standardAttributes = new LinkedHashMap();
nativeAttributes = new LinkedHashMap();
imageType = -1;
index = 0;
duration = 500;
dpi = 72;
requiredWidth = -1;
sampleScale = xscale = yscale = 1;
image = null;
thumbnail = null;
regionImage = null;
self = this;
}
public ImageInformation cloneAttributes() {
ImageInformation info = new ImageInformation();
return clone(this, info);
}
public static ImageInformation clone(ImageInformation sourceInfo, ImageInformation targetInfo) {
if (sourceInfo == null || targetInfo == null) {
return null;
}
ImageFileInformation.clone(sourceInfo, targetInfo);
if (sourceInfo.imageFileInformation != null) {
targetInfo.imageFileInformation = new ImageFileInformation();
ImageFileInformation.clone(sourceInfo.imageFileInformation, targetInfo.imageFileInformation);
}
targetInfo.self = targetInfo;
targetInfo.index = sourceInfo.index;
targetInfo.imageType = sourceInfo.imageType;
targetInfo.sampleScale = sourceInfo.sampleScale;
targetInfo.dpi = sourceInfo.dpi;
targetInfo.xscale = sourceInfo.xscale;
targetInfo.yscale = sourceInfo.yscale;
targetInfo.width = sourceInfo.width;
targetInfo.height = sourceInfo.height;
targetInfo.requiredWidth = sourceInfo.requiredWidth;
targetInfo.maxWidth = sourceInfo.maxWidth;
targetInfo.thumbnailRotation = sourceInfo.thumbnailRotation;
targetInfo.colorSpace = sourceInfo.colorSpace;
targetInfo.pixelsString = sourceInfo.pixelsString;
targetInfo.loadSizeString = sourceInfo.loadSizeString;
targetInfo.pixelsString = sourceInfo.pixelsString;
targetInfo.fileSizeString = sourceInfo.fileSizeString;
targetInfo.profileName = sourceInfo.profileName;
targetInfo.profileCompressionMethod = sourceInfo.profileCompressionMethod;
targetInfo.metaDataXml = sourceInfo.metaDataXml;
targetInfo.error = sourceInfo.error;
targetInfo.isMultipleFrames = sourceInfo.isMultipleFrames;
targetInfo.isSampled = sourceInfo.isSampled;
targetInfo.isScaled = sourceInfo.isScaled;
targetInfo.needSample = sourceInfo.needSample;
targetInfo.region = sourceInfo.region;
targetInfo.availableMem = sourceInfo.availableMem;
targetInfo.bytesSize = sourceInfo.bytesSize;
targetInfo.requiredMem = sourceInfo.requiredMem;
targetInfo.totalRequiredMem = sourceInfo.totalRequiredMem;
targetInfo.image = sourceInfo.image;
targetInfo.thumbnail = sourceInfo.thumbnail;
targetInfo.regionImage = sourceInfo.regionImage;
targetInfo.metaData = sourceInfo.metaData;
targetInfo.standardAttributes = sourceInfo.standardAttributes;
targetInfo.nativeAttributes = sourceInfo.nativeAttributes;
targetInfo.imageTypes = sourceInfo.imageTypes;
targetInfo.rawImageType = sourceInfo.rawImageType;
return targetInfo;
}
public ImageInformation as() {
switch (imageFormat.toLowerCase()) {
case "png":
return (ImageInformationPng) this;
default:
return this;
}
}
public Image loadImage(FxTask task) {
if (region != null) {
return readRegion(task, this, -1);
}
if (image == null || image.getWidth() != width) {
image = readImage(task, this);
}
return image;
}
public Image loadThumbnail(FxTask task, int thumbWidth) {
if (region != null) {
thumbnail = readRegion(task, this, thumbWidth);
}
if (thumbnail == null || (int) (thumbnail.getWidth()) != thumbWidth) {
thumbnail = readImage(task, this, thumbWidth);
}
if (image == null && thumbnail != null && (int) (thumbnail.getWidth()) == width) {
image = thumbnail;
}
return thumbnail;
}
public Image loadThumbnail(FxTask task) {
return loadThumbnail(task, AppVariables.thumbnailWidth);
}
public void loadBufferedImage(BufferedImage bufferedImage) {
if (bufferedImage != null) {
thumbnail = SwingFXUtils.toFXImage(bufferedImage, null);
isScaled = width > 0 && bufferedImage.getWidth() != (int) width;
if (imageType < 0) {
imageType = bufferedImage.getType();
}
if (width <= 0) {
width = bufferedImage.getWidth();
height = bufferedImage.getHeight();
image = thumbnail;
} else if (!isScaled) {
image = thumbnail;
}
} else {
thumbnail = null;
isScaled = false;
}
}
public String sampleInformation(FxTask task, Image image) {
int sampledWidth, sampledHeight, sampledSize;
if (image != null) {
sampledWidth = (int) image.getWidth();
sampledHeight = (int) image.getHeight();
} else {
if (width <= 0) {
width = 512;
}
checkMem(task, this);
sampledWidth = (int) maxWidth;
sampledHeight = (int) (maxWidth * height / width);
}
int channels = getColorChannels();
int mb = 1024 * 1024;
sampledSize = (int) (sampledWidth * sampledHeight * channels / mb);
String msg = MessageFormat.format(message("ImageTooLarge"),
width, height, channels,
bytesSize / mb, requiredMem / mb, availableMem / mb,
sampleScale, sampledWidth, sampledHeight, sampledSize);
return msg;
}
@Override
public void setFile(File file) {
if (imageFileInformation != null) {
imageFileInformation.setFile(file);
}
super.setFile(file);
}
/*
static methods
*/
public static ImageInformation create(String format, File file) {
switch (format.toLowerCase()) {
case "png":
return new ImageInformationPng(file);
default:
return new ImageInformation(file);
}
}
public static Image readImage(FxTask task, ImageInformation imageInfo) {
if (imageInfo == null) {
return null;
}
return readImage(task, imageInfo, -1);
}
public static Image readImage(FxTask task, ImageInformation imageInfo, int requiredWidth) {
if (imageInfo == null) {
return null;
}
if (imageInfo.getRegion() != null) {
return readRegion(task, imageInfo, requiredWidth);
}
imageInfo.setIsSampled(false);
imageInfo.setIsScaled(false);
Image targetImage = null;
try {
int infoWidth = (int) imageInfo.getWidth();
int targetWidth = requiredWidth <= 0 ? infoWidth : requiredWidth;
Image image = imageInfo.getImage();
File file = imageInfo.getFile();
if (image != null) {
int imageWidth = (int) image.getWidth();
if (imageWidth == targetWidth) {
targetImage = image;
} else if (file == null || (requiredWidth > 0 && imageWidth > targetWidth)) {
targetImage = mara.mybox.fxml.image.ScaleTools.scaleImage(image, targetWidth);
}
}
if (targetImage == null) {
Image thumb = imageInfo.getThumbnail();
if (thumb != null) {
int thumbWidth = (int) thumb.getWidth();
if (image == null && thumbWidth == infoWidth) {
imageInfo.setImage(image);
}
if (thumbWidth == targetWidth) {
targetImage = thumb;
} else if (file == null || (requiredWidth > 0 && thumbWidth > targetWidth)) {
targetImage = mara.mybox.fxml.image.ScaleTools.scaleImage(thumb, targetWidth);
}
}
}
if (targetImage == null && file != null) {
BufferedImage bufferedImage;
String suffix = FileNameTools.ext(file.getName());
if (suffix != null && suffix.equalsIgnoreCase("pdf")) {
bufferedImage = readPDF(imageInfo, targetWidth);
} else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) {
bufferedImage = readPPT(imageInfo, targetWidth);
} else {
imageInfo.setRequiredWidth(requiredWidth);
bufferedImage = ImageFileReaders.readFrame(task, imageInfo);
}
if (bufferedImage != null) {
targetImage = SwingFXUtils.toFXImage(bufferedImage, null);
if (imageInfo.getImageType() < 0) {
imageInfo.setImageType(bufferedImage.getType());
}
}
}
if (targetImage != null && infoWidth != (int) targetImage.getWidth()) {
imageInfo.setIsScaled(true);
if (imageInfo.isNeedSample()) {
imageInfo.setIsSampled(true);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return targetImage;
}
public static BufferedImage readPDF(ImageInformation imageInfo, int width) {
BufferedImage bufferedImage = null;
try (PDDocument pdfDoc = Loader.loadPDF(imageInfo.getFile(), imageInfo.getPassword())) {
bufferedImage = readPDF(null, new PDFRenderer(pdfDoc), ImageType.RGB, imageInfo, width);
pdfDoc.close();
} catch (Exception e) {
MyBoxLog.error(e);
}
return bufferedImage;
}
public static BufferedImage readPDF(FxTask task, PDFRenderer renderer, ImageType imageType,
ImageInformation imageInfo, int targetWidth) {
if (renderer == null || imageInfo == null) {
return null;
}
BufferedImage bufferedImage = null;
try {
int dpi = imageInfo.getDpi();
if (dpi <= 0) {
dpi = 72;
}
if (imageType == null) {
imageType = ImageType.RGB;
}
bufferedImage = renderer.renderImageWithDPI(imageInfo.getIndex(), dpi, imageType);
if (task != null && task.isCancelled()) {
return null;
}
bufferedImage = scaleImage(task, bufferedImage, imageInfo, targetWidth);
} catch (Exception e) {
MyBoxLog.debug(e);
if (task != null) {
task.setError(e.toString());
}
}
return bufferedImage;
}
public static BufferedImage scaleImage(FxTask task, BufferedImage inImage,
ImageInformation imageInfo, int targetWidth) {
if (imageInfo == null) {
return null;
}
try {
imageInfo.setThumbnail(null);
BufferedImage bufferedImage = inImage;
int imageWidth = bufferedImage.getWidth();
imageInfo.setWidth(imageWidth);
imageInfo.setHeight(bufferedImage.getHeight());
imageInfo.setImageType(bufferedImage.getType());
DoubleRectangle region = imageInfo.getRegion();
if (region != null) {
bufferedImage = mara.mybox.image.data.CropTools.cropOutside(task, inImage, region);
if (task != null && task.isCancelled()) {
return null;
}
}
if (targetWidth > 0 && imageWidth != targetWidth) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, targetWidth);
if (task != null && task.isCancelled()) {
return null;
}
}
if (ImageHints != null) {
bufferedImage = BufferedImageTools.applyRenderHints(bufferedImage, ImageHints);
if (task != null && task.isCancelled()) {
return null;
}
}
imageInfo.setThumbnail(SwingFXUtils.toFXImage(bufferedImage, null));
return bufferedImage;
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
return inImage;
}
}
public static BufferedImage readPPT(ImageInformation imageInfo, int width) {
BufferedImage bufferedImage = null;
try (SlideShow ppt = SlideShowFactory.create(imageInfo.getFile())) {
bufferedImage = readPPT(null, ppt, imageInfo, width);
} catch (Exception e) {
MyBoxLog.error(e);
}
return bufferedImage;
}
public static BufferedImage readPPT(FxTask task, SlideShow ppt, ImageInformation imageInfo, int targetWidth) {
if (ppt == null || imageInfo == null) {
return null;
}
BufferedImage bufferedImage = null;
try {
List<Slide> slides = ppt.getSlides();
int pptWidth = ppt.getPageSize().width;
int pptHeight = ppt.getPageSize().height;
Slide slide = slides.get(imageInfo.getIndex());
bufferedImage = new BufferedImage(pptWidth, pptHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bufferedImage.createGraphics();
if (AppVariables.ImageHints != null) {
g.addRenderingHints(AppVariables.ImageHints);
}
if (task != null && task.isCancelled()) {
return null;
}
slide.draw(g);
if (task != null && task.isCancelled()) {
return null;
}
bufferedImage = scaleImage(task, bufferedImage, imageInfo, targetWidth);
} catch (Exception e) {
MyBoxLog.debug(e);
if (task != null) {
task.setError(e.toString());
}
}
return bufferedImage;
}
public static BufferedImage readImage(FxTask task,
ImageReader reader, ImageInformation imageInfo, int targetWidth) {
if (reader == null || imageInfo == null) {
return null;
}
BufferedImage bufferedImage = null;
try {
imageInfo.setThumbnail(null);
imageInfo.setRequiredWidth(targetWidth);
bufferedImage = ImageFileReaders.readFrame(task, reader, imageInfo);
if (bufferedImage != null) {
imageInfo.setThumbnail(SwingFXUtils.toFXImage(bufferedImage, null));
}
} catch (Exception e) {
MyBoxLog.debug(e);
if (task != null) {
task.setError(e.toString());
}
}
return bufferedImage;
}
public static Image readRegion(FxTask task, ImageInformation imageInfo, int requireWidth) {
if (imageInfo == null) {
return null;
}
DoubleRectangle region = imageInfo.getRegion();
if (region == null) {
return readImage(task, imageInfo, requireWidth);
}
Image regionImage = imageInfo.getRegionImage();
try {
int infoWidth = (int) imageInfo.getWidth();
int targetWidth = requireWidth <= 0 ? (int) region.getWidth() : requireWidth;
if (regionImage != null && (int) regionImage.getWidth() == targetWidth) {
return regionImage;
}
regionImage = null;
imageInfo.setRequiredWidth(targetWidth);
Image image = imageInfo.getImage();
if (image != null && (int) image.getWidth() == infoWidth) {
regionImage = CropTools.cropOutsideFx(task, image, region);
regionImage = mara.mybox.fxml.image.ScaleTools.scaleImage(regionImage, targetWidth);
}
if (regionImage == null) {
Image thumb = imageInfo.getThumbnail();
if (thumb != null && (int) thumb.getWidth() == infoWidth) {
regionImage = CropTools.cropOutsideFx(task, thumb, region);
regionImage = mara.mybox.fxml.image.ScaleTools.scaleImage(regionImage, targetWidth);
}
}
if (regionImage == null) {
File file = imageInfo.getFile();
if (file != null) {
BufferedImage bufferedImage;
String suffix = FileNameTools.ext(file.getName());
if (suffix != null && suffix.equalsIgnoreCase("pdf")) {
bufferedImage = readPDF(imageInfo, targetWidth);
} else if (suffix != null && (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"))) {
bufferedImage = readPPT(imageInfo, targetWidth);
} else {
bufferedImage = ImageFileReaders.readFrame(task, imageInfo);
}
if (bufferedImage != null) {
regionImage = SwingFXUtils.toFXImage(bufferedImage, null);
}
}
}
imageInfo.setRegionImage(regionImage);
} catch (Exception e) {
MyBoxLog.error(e);
}
return regionImage;
}
public static BufferedImage readBufferedImage(FxTask task, ImageInformation info) {
Image image = readImage(task, info);
if (image != null) {
return SwingFXUtils.fromFXImage(image, null);
} else {
return null;
}
}
public static boolean checkMem(FxTask task, ImageInformation imageInfo) {
if (imageInfo == null) {
return false;
}
try {
if (imageInfo.getWidth() > 0 && imageInfo.getHeight() > 0) {
long channels = imageInfo.getColorChannels() > 0 ? imageInfo.getColorChannels() : 4;
long bytesSize = (long) (channels * imageInfo.getHeight() * imageInfo.getWidth());
long requiredMem = bytesSize * 6L;
Runtime r = Runtime.getRuntime();
long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory());
if (availableMem < requiredMem) {
System.gc();
availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory());
}
imageInfo.setAvailableMem(availableMem);
imageInfo.setBytesSize(bytesSize);
imageInfo.setRequiredMem(requiredMem);
if (availableMem < requiredMem) {
int scale = (int) Math.ceil(1d * requiredMem / availableMem);
// int scale = (int) Math.sqrt(1d * requiredMem / availableMem);
imageInfo.setNeedSample(true);
imageInfo.setSampleScale(scale);
imageInfo.setMaxWidth(imageInfo.getWidth() / scale);
if (task != null) {
int sampledWidth = (int) (imageInfo.getWidth() / scale);
int sampledHeight = (int) (imageInfo.getHeight() / scale);
int sampledSize = (int) (sampledWidth * sampledHeight * imageInfo.getColorChannels() / (1024 * 1024));
String msg = MessageFormat.format(message("ImageTooLarge"),
imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getColorChannels(),
bytesSize / (1024 * 1024), requiredMem / (1024 * 1024), availableMem / (1024 * 1024),
sampledWidth, sampledHeight, sampledSize);
task.setInfo(msg);
}
} else {
double ratio = Math.sqrt(1d * availableMem / requiredMem);
imageInfo.setSampleScale(1);
imageInfo.setNeedSample(false);
imageInfo.setMaxWidth(imageInfo.getWidth() * ratio);
if (task != null) {
String msg = message("AvaliableMemory") + ": " + availableMem / (1024 * 1024) + "MB" + "\n"
+ message("RequireMemory") + ": " + requiredMem / (1024 * 1024) + "MB";
task.setInfo(msg);
}
}
}
return true;
} catch (Exception e) {
imageInfo.setError(e.toString());
MyBoxLog.debug(e);
return false;
}
}
/*
customized get/set
*/
public double getWidth() {
if (width <= 0 && image != null) {
width = (int) image.getWidth();
}
return width;
}
public double getPickedWidth() {
return region != null ? region.getWidth() : getWidth();
}
public double getHeight() {
if (height <= 0 && image != null) {
height = image.getHeight();
}
return height;
}
public double getPickedHeight() {
return region != null ? region.getHeight() : getHeight();
}
public String getPixelsString() {
if (region == null) {
pixelsString = (int) width + "x" + (int) height;
} else {
pixelsString = message("Region") + " " + (int) region.getWidth() + "x" + (int) region.getHeight();
}
return pixelsString;
}
public String getLoadSizeString() {
if (thumbnail != null) {
loadSizeString = (int) thumbnail.getWidth() + "x" + (int) thumbnail.getHeight();
} else {
loadSizeString = "";
}
return loadSizeString;
}
public String getFileSizeString() {
if (imageFileInformation != null) {
fileSizeString = FileTools.showFileSize(imageFileInformation.getFileSize());
} else {
fileSizeString = "";
}
return fileSizeString;
}
public ImageInformation setRegion(double x1, double y1, double x2, double y2) {
region = DoubleRectangle.xy12(x1, y1, x2, y2);
regionImage = null;
return this;
}
/*
get/set
*/
public ImageFileInformation getImageFileInformation() {
return imageFileInformation;
}
public void setImageFileInformation(ImageFileInformation imageFileInformation) {
this.imageFileInformation = imageFileInformation;
}
public int getIndex() {
return index;
}
public ImageInformation setIndex(int index) {
this.index = index;
return this;
}
public int getImageType() {
return imageType;
}
public void setImageType(int imageType) {
this.imageType = imageType;
}
public ImageInformation setWidth(double width) {
this.width = width;
return this;
}
public void setHeight(double height) {
this.height = height;
}
public String getMetaDataXml() {
return metaDataXml;
}
public void setMetaDataXml(String metaDataXml) {
this.metaDataXml = metaDataXml;
}
public void setImage(Image image) {
this.image = image;
}
public Image getImage() {
return image;
}
public Image getThumbnail() {
return thumbnail;
}
public Map<String, Map<String, List<Map<String, Object>>>> getMetaData() {
return metaData;
}
public void setMetaData(
Map<String, Map<String, List<Map<String, Object>>>> metaData) {
this.metaData = metaData;
}
public void setPixelsString(String pixelsString) {
this.pixelsString = pixelsString;
}
public void setLoadSizeString(String loadSizeString) {
this.loadSizeString = loadSizeString;
}
public void setFileSizeString(String fileSizeString) {
this.fileSizeString = fileSizeString;
}
public boolean isIsMultipleFrames() {
return isMultipleFrames;
}
public void setIsMultipleFrames(boolean isMultipleFrames) {
this.isMultipleFrames = isMultipleFrames;
}
public boolean isIsSampled() {
return isSampled;
}
public void setIsSampled(boolean isSampled) {
this.isSampled = isSampled;
}
public boolean isIsScaled() {
return isScaled;
}
public void setIsScaled(boolean isScaled) {
this.isScaled = isScaled;
}
public ImageTypeSpecifier getRawImageType() {
return rawImageType;
}
public void setRawImageType(ImageTypeSpecifier rawImageType) {
this.rawImageType = rawImageType;
}
public List<ImageTypeSpecifier> getImageTypeSpecifiers() {
return imageTypes;
}
public void setImageTypeSpecifiers(List<ImageTypeSpecifier> imageTypes) {
this.imageTypes = imageTypes;
}
public boolean isNeedSample() {
return needSample;
}
public void setNeedSample(boolean needSample) {
this.needSample = needSample;
}
public void setThumbnail(Image thumbnail) {
this.thumbnail = thumbnail;
}
public ImageInformation getSelf() {
return self;
}
public void setSelf(ImageInformation self) {
this.self = self;
}
public long getAvailableMem() {
return availableMem;
}
public void setAvailableMem(long availableMem) {
this.availableMem = availableMem;
}
public long getBytesSize() {
return bytesSize;
}
public void setBytesSize(long bytesSize) {
this.bytesSize = bytesSize;
}
public long getRequiredMem() {
return requiredMem;
}
public void setRequiredMem(long requiredMem) {
this.requiredMem = requiredMem;
}
public long getTotalRequiredMem() {
return totalRequiredMem;
}
public void setTotalRequiredMem(long totalRequiredMem) {
this.totalRequiredMem = totalRequiredMem;
}
public int getSampleScale() {
return sampleScale;
}
public void setSampleScale(int sampleScale) {
this.sampleScale = sampleScale;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getXscale() {
return xscale;
}
public ImageInformation setXscale(int xscale) {
this.xscale = xscale;
return this;
}
public int getYscale() {
return yscale;
}
public ImageInformation setYscale(int yscale) {
this.yscale = yscale;
return this;
}
public double getRequiredWidth() {
return requiredWidth;
}
public ImageInformation setRequiredWidth(double requiredWidth) {
this.requiredWidth = requiredWidth;
return this;
}
public double getMaxWidth() {
return maxWidth;
}
public void setMaxWidth(double maxWidth) {
this.maxWidth = maxWidth;
}
/*
attributes
*/
public LinkedHashMap<String, Object> getStandardAttributes() {
return standardAttributes;
}
public void setStandardAttributes(LinkedHashMap<String, Object> attributes) {
this.standardAttributes = attributes;
}
public Object getStandardAttribute(String key) {
try {
return standardAttributes.get(key);
} catch (Exception e) {
return null;
}
}
public String getStandardStringAttribute(String key) {
try {
return (String) standardAttributes.get(key);
} catch (Exception e) {
return null;
}
}
public int getStandardIntAttribute(String key) {
try {
return (int) standardAttributes.get(key);
} catch (Exception e) {
return -1;
}
}
public float getStandardFloatAttribute(String key) {
try {
return (float) standardAttributes.get(key);
} catch (Exception e) {
return -1;
}
}
public boolean getStandardBooleanAttribute(String key) {
try {
return (boolean) standardAttributes.get(key);
} catch (Exception e) {
return false;
}
}
public void setStandardAttribute(String key, Object value) {
standardAttributes.put(key, value);
}
public LinkedHashMap<String, Object> getNativeAttributes() {
return nativeAttributes;
}
public void setNativeAttributes(
LinkedHashMap<String, Object> nativeAttributes) {
this.nativeAttributes = nativeAttributes;
}
public void setNativeAttribute(String key, Object value) {
nativeAttributes.put(key, value);
}
public Object getNativeAttribute(String key) {
try {
return nativeAttributes.get(key);
} catch (Exception e) {
return null;
}
}
public String getColorSpace() {
try {
return (String) standardAttributes.get("ColorSpace");
} catch (Exception e) {
return null;
}
}
public void setColorSpace(String colorSpace) {
standardAttributes.put("ColorSpace", colorSpace);
}
public String getImageRotation() {
try {
return (String) standardAttributes.get("ImageRotation");
} catch (Exception e) {
return null;
}
}
public void setImageRotation(String imageRotation) {
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageGray.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageGray.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.image.tools.AlphaTools;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2019-2-15
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ImageGray extends PixelsOperation {
public ImageGray() {
operationType = OperationType.Gray;
}
public ImageGray(BufferedImage image) {
this.image = image;
this.operationType = OperationType.Gray;
}
public ImageGray(Image image) {
this.image = SwingFXUtils.fromFXImage(image, null);
this.operationType = OperationType.Gray;
}
public ImageGray(Image image, ImageScope scope) {
this.image = SwingFXUtils.fromFXImage(image, null);
this.operationType = OperationType.Gray;
this.scope = scope;
}
public ImageGray(BufferedImage image, ImageScope scope) {
this.image = image;
this.operationType = OperationType.Gray;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return ColorConvertTools.color2gray(color);
}
public static BufferedImage byteGray(FxTask task, BufferedImage srcImage) {
try {
int width = srcImage.getWidth();
int height = srcImage.getHeight();
BufferedImage naImage = AlphaTools.removeAlpha(task, srcImage, Color.WHITE);
BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = grayImage.createGraphics();
if (AppVariables.ImageHints != null) {
g.addRenderingHints(AppVariables.ImageHints);
}
g.drawImage(naImage, 0, 0, null);
g.dispose();
return grayImage;
} catch (Exception e) {
MyBoxLog.error(e);
return srcImage;
}
}
public static BufferedImage intGray(FxTask task, BufferedImage image) {
try {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
grayImage.setRGB(x, y, 0);
} else {
grayImage.setRGB(x, y, ColorConvertTools.pixel2GrayPixel(p));
}
}
}
return grayImage;
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
public static Image gray(FxTask task, Image image) {
try {
BufferedImage bm = SwingFXUtils.fromFXImage(image, null);
bm = intGray(task, bm);
if (bm == null || (task != null && !task.isWorking())) {
return null;
}
return SwingFXUtils.toFXImage(bm, null);
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsBlendFactory.java | alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsBlendFactory.java | package mara.mybox.image.data;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import mara.mybox.image.data.PixelsBlend.ImagesBlendMode;
import static mara.mybox.image.data.PixelsBlend.ImagesBlendMode.MULTIPLY;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2019-3-24 11:24:03
* @License Apache License Version 2.0
*/
// https://en.wikipedia.org/wiki/Blend_modes
// https://blog.csdn.net/bravebean/article/details/51392440
// https://www.cnblogs.com/bigdream6/p/8385886.html
// https://baike.baidu.com/item/%E6%B7%B7%E5%90%88%E6%A8%A1%E5%BC%8F/6700481?fr=aladdin
public class PixelsBlendFactory {
public static List<String> blendModes() {
List<String> names = new ArrayList<>();
for (ImagesBlendMode mode : ImagesBlendMode.values()) {
names.add(modeName(mode));
}
return names;
}
public static ImagesBlendMode blendMode(String name) {
if (name == null) {
return ImagesBlendMode.MULTIPLY;
}
for (ImagesBlendMode mode : ImagesBlendMode.values()) {
if (Languages.matchIgnoreCase(name, modeName(mode))) {
return mode;
}
}
return ImagesBlendMode.MULTIPLY;
}
public static String modeName(ImagesBlendMode mode) {
if (mode == null) {
return message("MultiplyMode");
}
switch (mode) {
case KubelkaMunk:
return message("KubelkaMunkMode");
case CMYK:
return message("CMYKMode");
case CMYK_WEIGHTED:
return message("CMYKWeightedMode");
case MULTIPLY:
return message("MultiplyMode");
case NORMAL:
return message("NormalMode");
case DISSOLVE:
return message("DissolveMode");
case DARKEN:
return message("DarkenMode");
case COLOR_BURN:
return message("ColorBurnMode");
case LINEAR_BURN:
return message("LinearBurnMode");
case LIGHTEN:
return message("LightenMode");
case SCREEN:
return message("ScreenMode");
case COLOR_DODGE:
return message("ColorDodgeMode");
case LINEAR_DODGE:
return message("LinearDodgeMode");
case DIVIDE:
return message("DivideMode");
case VIVID_LIGHT:
return message("VividLightMode");
case LINEAR_LIGHT:
return message("LinearLightMode");
case SUBTRACT:
return message("SubtractMode");
case OVERLAY:
return message("OverlayMode");
case HARD_LIGHT:
return message("HardLightMode");
case SOFT_LIGHT:
return message("SoftLightMode");
case DIFFERENCE:
return message("DifferenceMode");
case EXCLUSION:
return message("ExclusionMode");
case HUE:
return message("HueMode");
case SATURATION:
return message("SaturationMode");
case COLOR:
return message("ColorMode");
case LUMINOSITY:
return message("LuminosityMode");
}
return message("MultiplyMode");
}
public static PixelsBlend create(ImagesBlendMode blendMode) {
if (blendMode == null) {
return new MultiplyBlend();
}
switch (blendMode) {
case KubelkaMunk:
return new KubelkaMunkBlend();
case CMYK:
return new CMYKBlend(false);
case CMYK_WEIGHTED:
return new CMYKBlend(true);
case NORMAL:
return new NormalBlend();
case DISSOLVE:
return new DissolveBlend();
case MULTIPLY:
return new MultiplyBlend();
case SCREEN:
return new ScreenBlend();
case OVERLAY:
return new OverlayBlend();
case HARD_LIGHT:
return new HardLightBlend();
case SOFT_LIGHT:
return new SoftLightBlend();
case COLOR_DODGE:
return new ColorDodgeBlend();
case LINEAR_DODGE:
return new LinearDodgeBlend();
case DIVIDE:
return new DivideBlend();
case COLOR_BURN:
return new ColorBurnBlend();
case LINEAR_BURN:
return new LinearBurnBlend();
case VIVID_LIGHT:
return new VividLightBlend();
case LINEAR_LIGHT:
return new LinearLightBlend();
case SUBTRACT:
return new SubtractBlend();
case DIFFERENCE:
return new DifferenceBlend();
case EXCLUSION:
return new ExclusionBlend();
case DARKEN:
return new DarkenBlend();
case LIGHTEN:
return new LightenBlend();
case HUE:
return new HueBlend();
case SATURATION:
return new SaturationBlend();
case LUMINOSITY:
return new LuminosityBlend();
case COLOR:
return new ColorBlend();
default:
return new MultiplyBlend();
}
}
public static class NormalBlend extends PixelsBlend {
public NormalBlend() {
this.blendMode = ImagesBlendMode.NORMAL;
}
}
public static class DissolveBlend extends PixelsBlend {
public DissolveBlend() {
this.blendMode = ImagesBlendMode.DISSOLVE;
}
@Override
public void makeRGB() {
float random = new Random().nextInt(101) / 100.0f;
red = (int) (foreColor.getRed() * random + backColor.getRed() * (1.0f - random));
green = (int) (foreColor.getGreen() * random + backColor.getGreen() * (1.0f - random));
blue = (int) (foreColor.getBlue() * random + backColor.getBlue() * (1.0f - random));
}
}
public static class KubelkaMunkBlend extends PixelsBlend {
public KubelkaMunkBlend() {
this.blendMode = ImagesBlendMode.KubelkaMunk;
}
@Override
public void makeRGB() {
Color blended = mixPigments(foreColor, backColor, weight);
red = blended.getRed();
green = blended.getGreen();
blue = blended.getBlue();
}
// Provided by deepseek.
public static Color mixPigments(Color color1, Color color2, double ratio) {
// 1. 将RGB转换为反射率(0-255 -> 0.0-1.0)
double[] reflectance1 = toReflectance(color1);
double[] reflectance2 = toReflectance(color2);
// 2. 使用Kubelka-Munk公式计算混合后的吸收/散射
double[] mixed = new double[3];
for (int i = 0; i < 3; i++) {
double k1 = kmTransform(reflectance1[i]);
double k2 = kmTransform(reflectance2[i]);
// 3. 按比例混合K值
double kmMixed = ratio * k1 + (1 - ratio) * k2;
// 4. 反向转换回反射率
mixed[i] = inverseKmTransform(kmMixed);
}
// 5. 将反射率转回RGB
return toColor(mixed);
}
// RGB转反射率(简单线性转换)
private static double[] toReflectance(Color color) {
return new double[]{
color.getRed() / 255.0,
color.getGreen() / 255.0,
color.getBlue() / 255.0
};
}
// Kubelka-Munk变换:反射率 -> K/S值
private static double kmTransform(double reflectance) {
return (1 - reflectance) * (1 - reflectance) / (2 * reflectance);
}
// 反向Kubelka-Munk变换
private static double inverseKmTransform(double km) {
double r = 1 + km - Math.sqrt(km * km + 2 * km);
// 限制在有效范围内
return Math.max(0, Math.min(1, r));
}
// 反射率转RGB
private static Color toColor(double[] reflectance) {
int r = (int) Math.round(reflectance[0] * 255);
int g = (int) Math.round(reflectance[1] * 255);
int b = (int) Math.round(reflectance[2] * 255);
return new Color(
Math.max(0, Math.min(255, r)),
Math.max(0, Math.min(255, g)),
Math.max(0, Math.min(255, b))
);
}
public static void main(String[] args) {
// 测试颜料混合
Color cyan = new Color(0, 183, 235); // 青色颜料
Color magenta = new Color(213, 0, 143); // 品红颜料
Color yellow = new Color(252, 220, 0); // 黄色颜料
// 青 + 品红 = 蓝色
Color blue = mixPigments(cyan, magenta, 0.5);
System.out.println("Cyan + Magenta = " + formatColor(blue));
// 品红 + 黄 = 红色
Color red = mixPigments(magenta, yellow, 0.5);
System.out.println("Magenta + Yellow = " + formatColor(red));
// 青 + 黄 = 绿色
Color green = mixPigments(cyan, yellow, 0.5);
System.out.println("Cyan + Yellow = " + formatColor(green));
// 三原色混合 = 黑色
Color black = mixPigments(blue, yellow, 0.5);
System.out.println("Blue + Yellow = " + formatColor(black));
}
private static String formatColor(Color color) {
return String.format("[R=%d, G=%d, B=%d]",
color.getRed(), color.getGreen(), color.getBlue());
}
}
public static class CMYKBlend extends PixelsBlend {
private final boolean isWeighted;
public CMYKBlend(boolean weighted) {
isWeighted = weighted;
this.blendMode = isWeighted
? ImagesBlendMode.CMYK_WEIGHTED : ImagesBlendMode.CMYK;
}
@Override
public void makeRGB() {
Color blended = isWeighted
? mix(foreColor, backColor, weight) : mix(foreColor, backColor);
red = blended.getRed();
green = blended.getGreen();
blue = blended.getBlue();
}
// Provided by deepseek.
public static Color mix(Color color1, Color color2) {
return cmyToRgb(mixColors(rgbToCmy(color1), rgbToCmy(color2)));
}
public static Color mix(Color color1, Color color2, double w) {
return cmyToRgb(mixColors(rgbToCmy(color1), rgbToCmy(color2), w));
}
// CMY颜色类(0.0-1.0范围)
public static class CMYColor {
public double c; // 青
public double m; // 品红
public double y; // 黄
public CMYColor(double c, double m, double y) {
this.c = clamp(c);
this.m = clamp(m);
this.y = clamp(y);
}
private double clamp(double value) {
return Math.max(0.0, Math.min(1.0, value));
}
}
// RGB转CMY(基于减色原理)
public static CMYColor rgbToCmy(Color rgb) {
double r = rgb.getRed() / 255.0;
double g = rgb.getGreen() / 255.0;
double b = rgb.getBlue() / 255.0;
double c = 1.0 - r;
double m = 1.0 - g;
double y = 1.0 - b;
return new CMYColor(c, m, y);
}
// CMY转RGB
public static Color cmyToRgb(CMYColor cmy) {
double r = (1.0 - cmy.c) * 255;
double g = (1.0 - cmy.m) * 255;
double b = (1.0 - cmy.y) * 255;
return new Color((int) Math.round(r), (int) Math.round(g), (int) Math.round(b));
}
// 减色混合核心算法(CMY混合)
public static CMYColor mixColors(CMYColor color1, CMYColor color2) {
// 减色混合公式:混合后吸收率 = 1 - (1 - c1) * (1 - c2)
double c = 1 - (1 - color1.c) * (1 - color2.c);
double m = 1 - (1 - color1.m) * (1 - color2.m);
double y = 1 - (1 - color1.y) * (1 - color2.y);
return new CMYColor(c, m, y);
}
public static CMYColor mixColors(CMYColor color1, CMYColor color2, double w) {
// 减色混合公式:混合后吸收率 = 1 - (1 - c1) * (1 - c2)
double w2 = 1 - w;
double c = 1 - (1 - color1.c * w) * (1 - color2.c * w2);
double m = 1 - (1 - color1.m * w) * (1 - color2.m * w2);
double y = 1 - (1 - color1.y * w) * (1 - color2.y * w2);
return new CMYColor(c, m, y);
}
// 调整颜色饱和度(添加补色)
public static CMYColor adjustSaturation(CMYColor color, double percent) {
// 计算补色(取反)
double gray = (color.c + color.m + color.y) / 3.0;
CMYColor complementary = new CMYColor(
gray + (gray - color.c) * percent,
gray + (gray - color.m) * percent,
gray + (gray - color.y) * percent
);
return mixColors(color, complementary);
}
// 调整明度(添加黑/白)
public static CMYColor adjustBrightness(CMYColor color, double whiteAmount, double blackAmount) {
// 添加白色 = 减少CMY值
double c = color.c * (1 - whiteAmount);
double m = color.m * (1 - whiteAmount);
double y = color.y * (1 - whiteAmount);
// 添加黑色 = 增加CMY值
c = c + (1 - c) * blackAmount;
m = m + (1 - m) * blackAmount;
y = y + (1 - y) * blackAmount;
return new CMYColor(c, m, y);
}
// 示例使用
public static void main(String[] args) {
// 创建基础颜色(青、品红、黄)
Color cyanRgb = new Color(0, 255, 255);
Color magentaRgb = new Color(255, 0, 255);
Color yellowRgb = new Color(255, 255, 0);
// 转换为CMY
CMYColor cyan = rgbToCmy(cyanRgb);
CMYColor magenta = rgbToCmy(magentaRgb);
CMYColor yellow = rgbToCmy(yellowRgb);
// 示例1: 青 + 黄 = 绿
CMYColor green = mixColors(cyan, yellow);
Color greenRgb = cmyToRgb(green);
System.out.println("青 + 黄 = 绿: RGB("
+ greenRgb.getRed() + ", " + greenRgb.getGreen() + ", " + greenRgb.getBlue() + ")");
// 示例2: 品红 + 青 = 蓝
CMYColor blue = mixColors(magenta, cyan);
Color blueRgb = cmyToRgb(blue);
System.out.println("品红 + 青 = 蓝: RGB("
+ blueRgb.getRed() + ", " + blueRgb.getGreen() + ", " + blueRgb.getBlue() + ")");
// 示例3: 调整饱和度
CMYColor desaturated = adjustSaturation(green, -0.5); // 降低50%饱和度
Color desaturatedRgb = cmyToRgb(desaturated);
System.out.println("降低饱和度: RGB("
+ desaturatedRgb.getRed() + ", " + desaturatedRgb.getGreen() + ", " + desaturatedRgb.getBlue() + ")");
// 示例4: 调整明度
CMYColor darkened = adjustBrightness(green, 0.0, 0.3); // 添加30%黑色
Color darkenedRgb = cmyToRgb(darkened);
System.out.println("变暗效果: RGB("
+ darkenedRgb.getRed() + ", " + darkenedRgb.getGreen() + ", " + darkenedRgb.getBlue() + ")");
}
}
public static class MultiplyBlend extends PixelsBlend {
public MultiplyBlend() {
this.blendMode = ImagesBlendMode.MULTIPLY;
}
@Override
public void makeRGB() {
red = foreColor.getRed() * backColor.getRed() / 255;
green = foreColor.getGreen() * backColor.getGreen() / 255;
blue = foreColor.getBlue() * backColor.getBlue() / 255;
}
}
public static class ScreenBlend extends PixelsBlend {
public ScreenBlend() {
this.blendMode = ImagesBlendMode.SCREEN;
}
@Override
public void makeRGB() {
red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 255;
green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 255;
blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 255;
}
}
public static class OverlayBlend extends PixelsBlend {
public OverlayBlend() {
this.blendMode = ImagesBlendMode.OVERLAY;
}
@Override
public void makeRGB() {
if (backColor.getRed() < 128) {
red = foreColor.getRed() * backColor.getRed() / 128;
} else {
red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 128;
}
if (backColor.getGreen() < 128) {
green = foreColor.getGreen() * backColor.getGreen() / 128;
} else {
green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 128;
}
if (backColor.getBlue() < 128) {
blue = foreColor.getBlue() * backColor.getBlue() / 128;
} else {
blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 128;
}
}
}
public static class HardLightBlend extends PixelsBlend {
public HardLightBlend() {
this.blendMode = ImagesBlendMode.HARD_LIGHT;
}
@Override
public void makeRGB() {
if (foreColor.getRed() < 128) {
red = foreColor.getRed() * backColor.getRed() / 128;
} else {
red = 255 - (255 - foreColor.getRed()) * (255 - backColor.getRed()) / 128;
}
if (foreColor.getGreen() < 128) {
green = foreColor.getGreen() * backColor.getGreen() / 128;
} else {
green = 255 - (255 - foreColor.getGreen()) * (255 - backColor.getGreen()) / 128;
}
if (foreColor.getBlue() < 128) {
blue = foreColor.getBlue() * backColor.getBlue() / 128;
} else {
blue = 255 - (255 - foreColor.getBlue()) * (255 - backColor.getBlue()) / 128;
}
}
}
public static class SoftLightBlend extends PixelsBlend {
public SoftLightBlend() {
this.blendMode = ImagesBlendMode.SOFT_LIGHT;
}
@Override
public void makeRGB() {
if (foreColor.getRed() < 128) {
red = backColor.getRed()
+ (2 * foreColor.getRed() - 255) * (backColor.getRed() - backColor.getRed() * backColor.getRed() / 255) / 255;
} else {
red = (int) (backColor.getRed()
+ (2 * foreColor.getRed() - 255) * (Math.sqrt(backColor.getRed() / 255.0f) * 255 - backColor.getRed()) / 255);
}
if (foreColor.getGreen() < 128) {
green = backColor.getGreen()
+ (2 * foreColor.getGreen() - 255) * (backColor.getGreen() - backColor.getGreen() * backColor.getGreen() / 255) / 255;
} else {
green = (int) (backColor.getGreen()
+ (2 * foreColor.getGreen() - 255) * (Math.sqrt(backColor.getGreen() / 255.0f) * 255 - backColor.getGreen()) / 255);
}
if (foreColor.getBlue() < 128) {
blue = backColor.getBlue()
+ (2 * foreColor.getBlue() - 255) * (backColor.getBlue() - backColor.getBlue() * backColor.getBlue() / 255) / 255;
} else {
blue = (int) (backColor.getBlue()
+ (2 * foreColor.getBlue() - 255) * (Math.sqrt(backColor.getBlue() / 255.0f) * 255 - backColor.getBlue()) / 255);
}
}
}
public static class ColorDodgeBlend extends PixelsBlend {
public ColorDodgeBlend() {
this.blendMode = ImagesBlendMode.COLOR_DODGE;
}
@Override
public void makeRGB() {
red = foreColor.getRed() == 255 ? 255
: (backColor.getRed() + (foreColor.getRed() * backColor.getRed()) / (255 - foreColor.getRed()));
green = foreColor.getGreen() == 255 ? 255
: (backColor.getGreen() + (foreColor.getGreen() * backColor.getGreen()) / (255 - foreColor.getGreen()));
blue = foreColor.getBlue() == 255 ? 255
: (backColor.getBlue() + (foreColor.getBlue() * backColor.getBlue()) / (255 - foreColor.getBlue()));
}
}
public static class LinearDodgeBlend extends PixelsBlend {
public LinearDodgeBlend() {
this.blendMode = ImagesBlendMode.LINEAR_DODGE;
}
@Override
public void makeRGB() {
red = foreColor.getRed() + backColor.getRed();
green = foreColor.getGreen() + backColor.getGreen();
blue = foreColor.getBlue() + backColor.getBlue();
}
}
public static class DivideBlend extends PixelsBlend {
public DivideBlend() {
this.blendMode = ImagesBlendMode.DIVIDE;
}
@Override
public void makeRGB() {
red = foreColor.getRed() == 0 ? 255 : ((backColor.getRed() * 255) / foreColor.getRed());
green = foreColor.getGreen() == 0 ? 255 : ((backColor.getGreen() * 255) / foreColor.getGreen());
blue = foreColor.getBlue() == 0 ? 255 : ((backColor.getBlue() * 255) / foreColor.getBlue());
}
}
public static class ColorBurnBlend extends PixelsBlend {
public ColorBurnBlend() {
this.blendMode = ImagesBlendMode.COLOR_BURN;
}
@Override
public void makeRGB() {
red = foreColor.getRed() == 0 ? 0
: (backColor.getRed() - (255 - foreColor.getRed()) * 255 / foreColor.getRed());
green = foreColor.getGreen() == 0 ? 0
: (backColor.getGreen() - (255 - foreColor.getGreen()) * 255 / foreColor.getGreen());
blue = foreColor.getBlue() == 0 ? 0
: (backColor.getBlue() - (255 - foreColor.getBlue()) * 255 / foreColor.getBlue());
}
}
public static class LinearBurnBlend extends PixelsBlend {
public LinearBurnBlend() {
this.blendMode = ImagesBlendMode.LINEAR_BURN;
}
@Override
public void makeRGB() {
red = backColor.getRed() == 0 ? 0
: foreColor.getRed() + backColor.getRed() - 255;
green = backColor.getGreen() == 0 ? 0
: foreColor.getGreen() + backColor.getGreen() - 255;
blue = backColor.getBlue() == 0 ? 0
: foreColor.getBlue() + backColor.getBlue() - 255;
}
}
public static class VividLightBlend extends PixelsBlend {
public VividLightBlend() {
this.blendMode = ImagesBlendMode.VIVID_LIGHT;
}
@Override
public void makeRGB() {
if (foreColor.getRed() < 128) {
red = foreColor.getRed() == 0 ? backColor.getRed()
: (backColor.getRed() - (255 - backColor.getRed()) * (255 - 2 * foreColor.getRed()) / (2 * foreColor.getRed()));
} else {
red = foreColor.getRed() == 255 ? backColor.getRed()
: (backColor.getRed() + backColor.getRed() * (2 * foreColor.getRed() - 255) / (2 * (255 - foreColor.getRed())));
}
if (foreColor.getGreen() < 128) {
green = foreColor.getGreen() == 0 ? backColor.getGreen()
: (backColor.getGreen() - (255 - backColor.getGreen()) * (255 - 2 * foreColor.getGreen()) / (2 * foreColor.getGreen()));
} else {
green = foreColor.getGreen() == 255 ? backColor.getGreen()
: (backColor.getGreen() + backColor.getGreen() * (2 * foreColor.getGreen() - 255) / (2 * (255 - foreColor.getGreen())));
}
if (foreColor.getBlue() < 128) {
blue = foreColor.getBlue() == 0 ? backColor.getBlue()
: (backColor.getBlue() - (255 - backColor.getBlue()) * (255 - 2 * foreColor.getBlue()) / (2 * foreColor.getBlue()));
} else {
blue = foreColor.getBlue() == 255 ? backColor.getBlue()
: (backColor.getBlue() + backColor.getBlue() * (2 * foreColor.getBlue() - 255) / (2 * (255 - foreColor.getBlue())));
}
}
}
public static class LinearLightBlend extends PixelsBlend {
public LinearLightBlend() {
this.blendMode = ImagesBlendMode.LINEAR_LIGHT;
}
@Override
public void makeRGB() {
red = 2 * foreColor.getRed() + backColor.getRed() - 255;
green = 2 * foreColor.getGreen() + backColor.getGreen() - 255;
blue = 2 * foreColor.getBlue() + backColor.getBlue() - 255;
}
}
public static class SubtractBlend extends PixelsBlend {
public SubtractBlend() {
this.blendMode = ImagesBlendMode.SUBTRACT;
}
@Override
public void makeRGB() {
red = backColor.getRed() - foreColor.getRed();
green = backColor.getGreen() - foreColor.getGreen();
blue = backColor.getBlue() - foreColor.getBlue();
}
}
public static class DifferenceBlend extends PixelsBlend {
public DifferenceBlend() {
this.blendMode = ImagesBlendMode.DIFFERENCE;
}
@Override
public void makeRGB() {
red = Math.abs(backColor.getRed() - foreColor.getRed());
green = Math.abs(backColor.getGreen() - foreColor.getGreen());
blue = Math.abs(backColor.getBlue() - foreColor.getBlue());
}
}
public static class ExclusionBlend extends PixelsBlend {
public ExclusionBlend() {
this.blendMode = ImagesBlendMode.EXCLUSION;
}
@Override
public void makeRGB() {
red = backColor.getRed() + foreColor.getRed() - backColor.getRed() * foreColor.getRed() / 128;
green = backColor.getGreen() + foreColor.getGreen() - backColor.getGreen() * foreColor.getGreen() / 128;
blue = backColor.getBlue() + foreColor.getBlue() - backColor.getBlue() * foreColor.getBlue() / 128;
}
}
public static class DarkenBlend extends PixelsBlend {
public DarkenBlend() {
this.blendMode = ImagesBlendMode.DARKEN;
}
@Override
public void makeRGB() {
red = Math.min(backColor.getRed(), foreColor.getRed());
green = Math.min(backColor.getGreen(), foreColor.getGreen());
blue = Math.min(backColor.getBlue(), foreColor.getBlue());
}
}
public static class LightenBlend extends PixelsBlend {
public LightenBlend() {
this.blendMode = ImagesBlendMode.LIGHTEN;
}
@Override
public void makeRGB() {
red = Math.max(backColor.getRed(), foreColor.getRed());
green = Math.max(backColor.getGreen(), foreColor.getGreen());
blue = Math.max(backColor.getBlue(), foreColor.getBlue());
}
}
public static class HueBlend extends PixelsBlend {
public HueBlend() {
this.blendMode = ImagesBlendMode.HUE;
}
@Override
public int blend(int forePixel, int backPixel) {
if (forePixel == 0) { // Pass transparency
return backPixel;
}
if (backPixel == 0) { // Pass transparency
return forePixel;
}
float[] hA = ColorConvertTools.pixel2hsb(forePixel);
float[] hB = ColorConvertTools.pixel2hsb(backPixel);
Color hColor = Color.getHSBColor(hA[0], hB[1], hB[2]);
return hColor.getRGB();
}
}
public static class SaturationBlend extends PixelsBlend {
public SaturationBlend() {
this.blendMode = ImagesBlendMode.SATURATION;
}
@Override
public int blend(int forePixel, int backPixel) {
if (forePixel == 0) { // Pass transparency
return backPixel;
}
if (backPixel == 0) { // Pass transparency
return forePixel;
}
float[] sA = ColorConvertTools.pixel2hsb(forePixel);
float[] sB = ColorConvertTools.pixel2hsb(backPixel);
Color sColor = Color.getHSBColor(sB[0], sA[1], sB[2]);
return sColor.getRGB();
}
}
public static class LuminosityBlend extends PixelsBlend {
public LuminosityBlend() {
this.blendMode = ImagesBlendMode.LUMINOSITY;
}
@Override
public int blend(int forePixel, int backPixel) {
if (forePixel == 0) { // Pass transparency
return backPixel;
}
if (backPixel == 0) { // Pass transparency
return forePixel;
}
float[] bA = ColorConvertTools.pixel2hsb(forePixel);
float[] bB = ColorConvertTools.pixel2hsb(backPixel);
Color newColor = Color.getHSBColor(bB[0], bB[1], bA[2]);
return newColor.getRGB();
}
}
public static class ColorBlend extends PixelsBlend {
public ColorBlend() {
this.blendMode = ImagesBlendMode.COLOR;
}
@Override
public int blend(int forePixel, int backPixel) {
if (forePixel == 0) { // Pass transparency
return backPixel;
}
if (backPixel == 0) { // Pass transparency
return forePixel;
}
float[] cA = ColorConvertTools.pixel2hsb(forePixel);
float[] cB = ColorConvertTools.pixel2hsb(backPixel);
Color cColor = Color.getHSBColor(cA[0], cA[1], cB[2]);
return cColor.getRGB();
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsOperation.java | alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsOperation.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.data.IntPoint;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2019-2-13 14:44:03
* @Description Pixel operations here only involve pixel itself. Pixel
* operations which involve other pixels need be defined separately.
* @License Apache License Version 2.0
*/
public abstract class PixelsOperation {
protected BufferedImage srcImage, image;
protected boolean isDithering, skipTransparent, excludeScope,
boolPara1, boolPara2, boolPara3;
protected int intPara1, intPara2, intPara3, scopeColor = 0;
protected float floatPara1, floatPara2;
protected Color colorPara1, colorPara2;
protected ImageScope scope;
protected OperationType operationType;
protected ColorActionType colorActionType;
protected int currentX, currentY;
protected Color[] thisLine, nextLine;
protected int thisLineY;
protected int imageWidth, imageHeight;
protected FxTask task;
public enum OperationType {
Smooth, Denoise, Blur, Sharpen, Clarity, Emboss, EdgeDetect,
Thresholding, Quantization, Gray, BlackOrWhite, Sepia,
ReplaceColor, Invert, Red, Green, Blue, Yellow, Cyan, Magenta, Mosaic, FrostedGlass,
Brightness, Saturation, Hue, Opacity, PreOpacity, RGB, Color, Blend,
ShowScope, SelectPixels, Convolution, Contrast
}
public enum ColorActionType {
Set, Increase, Decrease, Filter, Invert
}
public PixelsOperation() {
excludeScope = false;
skipTransparent = true;
}
public PixelsOperation(BufferedImage image, ImageScope scope, OperationType operationType) {
srcImage = image;
this.image = image;
this.operationType = operationType;
this.scope = scope;
}
public BufferedImage start() {
return operateImage();
}
public Image startFx() {
BufferedImage target = start();
if (target == null || taskInvalid()) {
return null;
}
return SwingFXUtils.toFXImage(target, null);
}
// do not refer this directly
protected BufferedImage operateImage() {
if (image == null || operationType == null) {
return image;
}
try {
imageWidth = image.getWidth();
imageHeight = image.getHeight();
if (operationType != OperationType.BlackOrWhite
&& operationType != OperationType.Quantization) {
isDithering = false;
}
if (scope != null) {
scope = ImageScopeFactory.create(scope);
}
if (scope != null
&& (scope.getShapeType() == ImageScope.ShapeType.Matting4
|| scope.getShapeType() == ImageScope.ShapeType.Matting8)) {
isDithering = false;
return operateMatting();
} else {
return operateScope();
}
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
private BufferedImage operateScope() {
if (image == null) {
return image;
}
try {
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage target = new BufferedImage(imageWidth, imageHeight, imageType);
boolean inScope;
if (isDithering) {
thisLine = new Color[imageWidth];
nextLine = new Color[imageWidth];
thisLineY = 0;
thisLine[0] = new Color(image.getRGB(0, 0), true);
}
Color newColor;
int pixel;
for (int y = 0; y < image.getHeight(); y++) {
if (taskInvalid()) {
return null;
}
for (int x = 0; x < image.getWidth(); x++) {
if (taskInvalid()) {
return null;
}
pixel = image.getRGB(x, y);
Color color = new Color(pixel, true);
if (pixel == 0 && skipTransparent) {
// transparency need write dithering lines while they affect nothing
newColor = skipTransparent(target, x, y);
} else {
inScope = inScope(x, y, color);
if (isDithering && y == thisLineY) {
color = thisLine[x];
}
if (inScope) {
newColor = operatePixel(target, color, x, y);
} else {
newColor = color;
target.setRGB(x, y, color.getRGB());
}
}
if (isDithering) {
dithering(color, newColor, x, y);
}
}
if (isDithering) {
thisLine = nextLine;
thisLineY = y + 1;
nextLine = new Color[imageWidth];
}
}
thisLine = nextLine = null;
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return image;
}
}
// https://en.wikipedia.org/wiki/Flood_fill
// https://www.codeproject.com/Articles/6017/QuickFill-An-Efficient-Flood-Fill-Algorithm
private BufferedImage operateMatting() {
try {
if (image == null || scope == null) {
return image;
}
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage target = new BufferedImage(imageWidth, imageHeight, imageType);
boolean excluded = scope.isColorExcluded();
if (excludeScope) {
excluded = !excluded;
}
if (operationType == OperationType.ShowScope) {
excluded = !excluded;
}
if (excluded) {
for (int y = 0; y < imageHeight; y++) {
for (int x = 0; x < imageWidth; x++) {
if (taskInvalid()) {
return null;
}
operatePixel(target, x, y);
}
}
} else {
target = image.getSubimage(0, 0, imageWidth, imageHeight);
}
if (taskInvalid()) {
return null;
}
List<IntPoint> points = scope.getPoints();
if (points == null || points.isEmpty()) {
return target;
}
boolean[][] visited = new boolean[imageHeight][imageWidth];
Queue<IntPoint> queue = new LinkedList<>();
boolean eightNeighbor = scope.getShapeType() == ImageScope.ShapeType.Matting8;
int x, y;
for (IntPoint point : points) {
if (taskInvalid()) {
return null;
}
x = point.getX();
y = point.getY();
if (x < 0 || x >= imageWidth || y < 0 || y >= imageHeight) {
continue;
}
Color startColor = new Color(image.getRGB(x, y), true);
queue.add(point);
while (!queue.isEmpty()) {
if (taskInvalid()) {
return null;
}
IntPoint p = queue.remove();
x = p.getX();
y = p.getY();
if (x < 0 || x >= imageWidth || y < 0 || y >= imageHeight
|| visited[y][x]) {
continue;
}
visited[y][x] = true;
int pixel = image.getRGB(x, y);
Color color = new Color(pixel, true);
if (pixel == 0 && skipTransparent) {
skipTransparent(target, x, y);
} else if (scope.isMatchColor(startColor, color)) {
if (scope.isMatchColors(color)) {
if (excluded) {
target.setRGB(x, y, pixel);
} else {
operatePixel(target, color, x, y);
}
}
queue.add(new IntPoint(x + 1, y));
queue.add(new IntPoint(x - 1, y));
queue.add(new IntPoint(x, y + 1));
queue.add(new IntPoint(x, y - 1));
if (eightNeighbor) {
queue.add(new IntPoint(x + 1, y + 1));
queue.add(new IntPoint(x + 1, y - 1));
queue.add(new IntPoint(x - 1, y + 1));
queue.add(new IntPoint(x - 1, y - 1));
}
}
}
}
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
protected boolean inScope(int x, int y, Color color) {
try {
boolean inScope = scope == null || scope.inScope(x, y, color);
if (excludeScope) {
inScope = !inScope;
}
return inScope;
} catch (Exception e) {
return false;
}
}
protected Color skipTransparent(BufferedImage target, int x, int y) {
try {
target.setRGB(x, y, 0);
return Colors.TRANSPARENT;
} catch (Exception e) {
return null;
}
}
protected Color operatePixel(BufferedImage target, int x, int y) {
try {
int pixel = image.getRGB(x, y);
Color color = new Color(pixel, true);
if (pixel == 0 && skipTransparent) {
return color;
} else {
return operatePixel(target, color, x, y);
}
} catch (Exception e) {
return null;
}
}
protected Color operatePixel(BufferedImage target, Color color, int x, int y) {
currentX = x;
currentY = y;
Color newColor = operateColor(color);
if (newColor == null) {
newColor = color;
}
target.setRGB(x, y, newColor.getRGB());
return newColor;
}
// https://en.wikipedia.org/wiki/Dither
// https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering
protected void dithering(Color color, Color newColor, int x, int y) {
if (y != thisLineY) {
return;
}
int red_error, green_error, blue_error;
int new_red, new_green, new_blue;
red_error = color.getRed() - newColor.getRed();
green_error = color.getGreen() - newColor.getGreen();
blue_error = color.getBlue() - newColor.getBlue();
if (x + 1 < imageWidth) {
color = new Color(image.getRGB(x + 1, y), true);
new_red = Math.max(Math.min(color.getRed() + red_error * 7 / 16, 255), 0);
new_green = Math.max(Math.min(color.getGreen() + green_error * 7 / 16, 255), 0);
new_blue = Math.max(Math.min(color.getBlue() + blue_error * 7 / 16, 255), 0);
newColor = new Color(new_red, new_green, new_blue, color.getAlpha());
thisLine[x + 1] = newColor;
}
if (x - 1 >= 0 && y + 1 < imageHeight) {
color = new Color(image.getRGB(x - 1, y + 1), true);
new_red = Math.max(Math.min(color.getRed() + red_error * 3 / 16, 255), 0);
new_green = Math.max(Math.min(color.getGreen() + green_error * 3 / 16, 255), 0);
new_blue = Math.max(Math.min(color.getBlue() + blue_error * 3 / 16, 255), 0);
newColor = new Color(new_red, new_green, new_blue, color.getAlpha());
nextLine[x - 1] = newColor;
}
if (y + 1 < imageHeight) {
color = new Color(image.getRGB(x, y + 1), true);
new_red = Math.max(Math.min(color.getRed() + red_error * 5 / 16, 255), 0);
new_green = Math.max(Math.min(color.getGreen() + green_error * 5 / 16, 255), 0);
new_blue = Math.max(Math.min(color.getBlue() + blue_error * 5 / 16, 255), 0);
newColor = new Color(new_red, new_green, new_blue, color.getAlpha());
nextLine[x] = newColor;
}
if (x + 1 < imageWidth && y + 1 < imageHeight) {
color = new Color(image.getRGB(x + 1, y + 1), true);
new_red = Math.max(Math.min(color.getRed() + red_error * 1 / 16, 255), 0);
new_green = Math.max(Math.min(color.getGreen() + green_error * 1 / 16, 255), 0);
new_blue = Math.max(Math.min(color.getBlue() + blue_error * 1 / 16, 255), 0);
newColor = new Color(new_red, new_green, new_blue, color.getAlpha());
nextLine[x + 1] = newColor;
}
}
// SubClass should implement this
protected Color operateColor(Color color) {
return color;
}
public boolean taskInvalid() {
return task != null && !task.isWorking();
}
/*
get/set
*/
public OperationType getOperationType() {
return operationType;
}
public PixelsOperation setOperationType(OperationType operationType) {
this.operationType = operationType;
return this;
}
public BufferedImage getImage() {
return image;
}
public PixelsOperation setImage(BufferedImage image) {
this.image = image;
srcImage = image;
return this;
}
public PixelsOperation setImage(Image image) {
this.image = SwingFXUtils.fromFXImage(image, null);
return this;
}
public boolean isIsDithering() {
return isDithering;
}
public PixelsOperation setIsDithering(boolean isDithering) {
this.isDithering = isDithering;
return this;
}
public ImageScope getScope() {
return scope;
}
public PixelsOperation setScope(ImageScope scope) {
this.scope = scope;
return this;
}
public boolean isBoolPara1() {
return boolPara1;
}
public PixelsOperation setBoolPara1(boolean boolPara1) {
this.boolPara1 = boolPara1;
return this;
}
public boolean isBoolPara2() {
return boolPara2;
}
public PixelsOperation setBoolPara2(boolean boolPara2) {
this.boolPara2 = boolPara2;
return this;
}
public boolean isBoolPara3() {
return boolPara3;
}
public PixelsOperation setBoolPara3(boolean boolPara3) {
this.boolPara3 = boolPara3;
return this;
}
public int getIntPara1() {
return intPara1;
}
public PixelsOperation setIntPara1(int intPara1) {
this.intPara1 = intPara1;
return this;
}
public int getIntPara2() {
return intPara2;
}
public PixelsOperation setIntPara2(int intPara2) {
this.intPara2 = intPara2;
return this;
}
public int getIntPara3() {
return intPara3;
}
public PixelsOperation setIntPara3(int intPara3) {
this.intPara3 = intPara3;
return this;
}
public float getFloatPara1() {
return floatPara1;
}
public PixelsOperation setFloatPara1(float floatPara1) {
this.floatPara1 = floatPara1;
return this;
}
public float getFloatPara2() {
return floatPara2;
}
public PixelsOperation setFloatPara2(float floatPara2) {
this.floatPara2 = floatPara2;
return this;
}
public Color[] getThisLine() {
return thisLine;
}
public PixelsOperation setThisLine(Color[] thisLine) {
this.thisLine = thisLine;
return this;
}
public Color[] getNextLine() {
return nextLine;
}
public PixelsOperation setNextLine(Color[] nextLine) {
this.nextLine = nextLine;
return this;
}
public int getThisLineY() {
return thisLineY;
}
public PixelsOperation setThisLineY(int thisLineY) {
this.thisLineY = thisLineY;
return this;
}
public int getImageWidth() {
return imageWidth;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}
public Color getColorPara1() {
return colorPara1;
}
public PixelsOperation setColorPara1(Color colorPara1) {
this.colorPara1 = colorPara1;
return this;
}
public Color getColorPara2() {
return colorPara2;
}
public PixelsOperation setColorPara2(Color colorPara2) {
this.colorPara2 = colorPara2;
return this;
}
public ColorActionType getColorActionType() {
return colorActionType;
}
public PixelsOperation setColorActionType(ColorActionType colorActionType) {
this.colorActionType = colorActionType;
return this;
}
public int getScopeColor() {
return scopeColor;
}
public PixelsOperation setScopeColor(int scopeColor) {
this.scopeColor = scopeColor;
return this;
}
public boolean isSkipTransparent() {
return skipTransparent;
}
public PixelsOperation setSkipTransparent(boolean skipTransparent) {
this.skipTransparent = skipTransparent;
return this;
}
public boolean isExcludeScope() {
return excludeScope;
}
public PixelsOperation setExcludeScope(boolean excludeScope) {
this.excludeScope = excludeScope;
return this;
}
public FxTask getTask() {
return task;
}
public PixelsOperation setTask(FxTask task) {
this.task = task;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageQuantization.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageQuantization.java | package mara.mybox.image.data;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ColorMatch;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.FloatTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2019-2-13 14:44:03
* @License Apache License Version 2.0
*/
// http://web.cs.wpi.edu/~matt/courses/cs563/talks/color_quant/CQindex.html
public class ImageQuantization extends PixelsOperation {
protected ColorMatch colorMatch;
protected int maxLoop;
public static enum QuantizationAlgorithm {
RGBUniformQuantization, HSBUniformQuantization,
RegionPopularityQuantization,
RegionKMeansClustering,
KMeansClustering
// MedianCutQuantization, ANN
}
protected QuantizationAlgorithm algorithm;
protected int quantizationSize, regionSize, weight1, weight2, weight3, intValue;
protected boolean recordCount, firstColor;
protected Map<Color, Long> counts;
protected List<ColorCount> sortedCounts;
protected long totalCount;
protected Color[][][] palette;
public ImageQuantization() {
operationType = PixelsOperation.OperationType.Quantization;
}
public ImageQuantization buildPalette() {
return this;
}
public void countColor(Color mappedColor) {
if (recordCount) {
if (counts == null) {
counts = new HashMap<>();
}
if (counts.containsKey(mappedColor)) {
counts.put(mappedColor, counts.get(mappedColor) + 1);
} else {
counts.put(mappedColor, Long.valueOf(1));
}
}
}
public static class ColorCount {
public Color color;
public long count;
public ColorCount(Color color, long count) {
this.color = color;
this.count = count;
}
}
public List<ColorCount> sortCounts(FxTask currentTask) {
totalCount = 0;
if (counts == null) {
return null;
}
sortedCounts = new ArrayList<>();
for (Color color : counts.keySet()) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
sortedCounts.add(new ColorCount(color, counts.get(color)));
totalCount += counts.get(color);
}
Collections.sort(sortedCounts, new Comparator<ColorCount>() {
@Override
public int compare(ColorCount v1, ColorCount v2) {
long diff = v2.count - v1.count;
if (diff == 0) {
return 0;
} else if (diff > 0) {
return 1;
} else {
return -1;
}
}
});
return sortedCounts;
}
public StringTable countTable(FxTask currentTask, String name) {
try {
sortedCounts = sortCounts(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (sortedCounts == null || totalCount == 0) {
return null;
}
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(message("ID"), message("PixelsNumber"),
message("Percentage"), message("Color"),
message("Red"), message("Green"), message("Blue"), message("Opacity"),
message("Hue"), message("Brightness"), message("Saturation")
));
String title = message(algorithm.name());
if (name != null) {
title += "_" + name;
}
StringTable table = new StringTable(names, title);
int id = 1;
for (ColorCount count : sortedCounts) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
List<String> row = new ArrayList<>();
javafx.scene.paint.Color color = ColorConvertTools.converColor(count.color);
int red = (int) Math.round(color.getRed() * 255);
int green = (int) Math.round(color.getGreen() * 255);
int blue = (int) Math.round(color.getBlue() * 255);
row.addAll(Arrays.asList((id++) + "", StringTools.format(count.count),
FloatTools.percentage(count.count, totalCount) + "%",
"<DIV style=\"width: 50px; background-color:"
+ FxColorTools.color2rgb(color) + "; \"> </DIV>",
red + " ", green + " ", blue + " ",
(int) Math.round(color.getOpacity() * 100) + "%",
Math.round(color.getHue()) + " ",
Math.round(color.getSaturation() * 100) + "%",
Math.round(color.getBrightness() * 100) + "%"
));
table.add(row);
}
return table;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String resultInfo() {
return null;
}
@Override
public Color operateColor(Color color) {
return color;
}
public ImageRegionKMeans imageRegionKMeans() {
try {
ImageQuantizationFactory.KMeansRegion regionQuantization
= ImageQuantizationFactory.KMeansRegion.create();
regionQuantization.setQuantizationSize(regionSize)
.setRegionSize(regionSize)
.setFirstColor(firstColor)
.setWeight1(weight1).setWeight2(weight2).setWeight3(weight3)
.setRecordCount(true)
.setColorMatch(colorMatch)
.setImage(image).setScope(scope)
.setOperationType(PixelsOperation.OperationType.Quantization)
.setIsDithering(isDithering)
.setTask(task);
regionQuantization.buildPalette().start();
ImageRegionKMeans kmeans = ImageRegionKMeans.create();
kmeans.setK(quantizationSize)
.setMaxIteration(maxLoop)
.setTask(task);
if (kmeans.init(regionQuantization).run()) {
kmeans.makeMap();
return kmeans;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
public ImageKMeans imageKMeans() {
try {
ImageKMeans kmeans = ImageKMeans.create();
kmeans.setK(quantizationSize)
.setMaxIteration(maxLoop)
.setTask(task);
if (kmeans.init(image, colorMatch).run()) {
kmeans.makeMap();
return kmeans;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
public class PopularityRegionValue {
protected long redAccum, greenAccum, blueAccum, pixelsCount;
protected Color regionColor, averageColor;
}
/*
get/set
*/
public QuantizationAlgorithm getAlgorithm() {
return algorithm;
}
public ImageQuantization setAlgorithm(QuantizationAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public int getQuantizationSize() {
return quantizationSize;
}
public ImageQuantization setQuantizationSize(int quantizationSize) {
this.quantizationSize = quantizationSize;
return this;
}
public int getWeight1() {
return weight1;
}
public ImageQuantization setWeight1(int weight1) {
this.weight1 = weight1;
return this;
}
public int getWeight2() {
return weight2;
}
public ImageQuantization setWeight2(int weight2) {
this.weight2 = weight2;
return this;
}
public int getWeight3() {
return weight3;
}
public ImageQuantization setWeight3(int weight3) {
this.weight3 = weight3;
return this;
}
public boolean isRecordCount() {
return recordCount;
}
public ImageQuantization setRecordCount(boolean recordCount) {
this.recordCount = recordCount;
return this;
}
public Map<Color, Long> getCounts() {
return counts;
}
public ImageQuantization setCounts(Map<Color, Long> counts) {
this.counts = counts;
return this;
}
public List<ColorCount> getSortedCounts() {
return sortedCounts;
}
public ImageQuantization setSortedCounts(List<ColorCount> sortedCounts) {
this.sortedCounts = sortedCounts;
return this;
}
public long getTotalCount() {
return totalCount;
}
public ImageQuantization setTotalCount(long totalCount) {
this.totalCount = totalCount;
return this;
}
public int getIntValue() {
return intValue;
}
public ImageQuantization setIntValue(int intValue) {
this.intValue = intValue;
return this;
}
public int getRegionSize() {
return regionSize;
}
public ImageQuantization setRegionSize(int regionSize) {
this.regionSize = regionSize;
return this;
}
public boolean isFirstColor() {
return firstColor;
}
public ImageQuantization setFirstColor(boolean firstColor) {
this.firstColor = firstColor;
return this;
}
public Color[][][] getPalette() {
return palette;
}
public ImageQuantization setPalette(Color[][][] palette) {
this.palette = palette;
return this;
}
public ColorMatch getColorMatch() {
return colorMatch;
}
public ImageQuantization setColorMatch(ColorMatch colorMatch) {
this.colorMatch = colorMatch;
return this;
}
public int getMaxLoop() {
return maxLoop;
}
public ImageQuantization setMaxLoop(int maxLoop) {
this.maxLoop = maxLoop;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageColor.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageColor.java | package mara.mybox.image.data;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @License Apache License Version 2.0
*/
public class ImageColor {
private int index, red, green, blue, alpha = 255;
public ImageColor(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public ImageColor(int red, int green, int blue, int alpha) {
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
public ImageColor(int index, int red, int green, int blue, int alpha) {
this.index = index;
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
@Override
public String toString() {
return Languages.message("Red") + ": " + red
+ Languages.message("Green") + ": " + green
+ Languages.message("Blue") + ": " + blue
+ Languages.message("Alpha") + ": " + alpha;
}
/*
get/set
*/
public int getRed() {
return red;
}
public void setRed(int red) {
this.red = red;
}
public int getGreen() {
return green;
}
public void setGreen(int green) {
this.green = green;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
public int getAlpha() {
return alpha;
}
public void setAlpha(int alpha) {
this.alpha = alpha;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ComponentStatistic.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ComponentStatistic.java | package mara.mybox.image.data;
import mara.mybox.calculation.IntStatistic;
import mara.mybox.image.tools.ColorComponentTools.ColorComponent;
/**
* @Author Mara
* @CreateDate 2019-10-26
* @License Apache License Version 2.0
*/
public class ComponentStatistic {
protected ColorComponent component;
protected IntStatistic statistic;
protected int[] histogram;
public static ComponentStatistic create() {
return new ComponentStatistic();
}
/*
get/set
*/
public ColorComponent getComponent() {
return component;
}
public ComponentStatistic setComponent(ColorComponent component) {
this.component = component;
return this;
}
public IntStatistic getStatistic() {
return statistic;
}
public ComponentStatistic setStatistic(IntStatistic statistic) {
this.statistic = statistic;
return this;
}
public int[] getHistogram() {
return histogram;
}
public ComponentStatistic setHistogram(int[] histogram) {
this.histogram = histogram;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageMosaic.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageMosaic.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ShapeTools;
import java.awt.Color;
import java.awt.image.BufferedImage;
/**
* @Author Mara
* @CreateDate 2019-2-15
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ImageMosaic extends PixelsOperation {
protected MosaicType type;
protected int intensity;
public enum MosaicType {
Mosaic, FrostedGlass
};
public ImageMosaic() {
this.operationType = OperationType.Mosaic;
this.type = MosaicType.Mosaic;
intensity = 20;
}
public static ImageMosaic create() {
return new ImageMosaic();
}
@Override
protected Color operatePixel(BufferedImage target, Color color, int x, int y) {
int newColor = ShapeTools.mosaic(image, imageWidth, imageHeight, x, y, type, intensity);
target.setRGB(x, y, newColor);
return new Color(newColor, true);
}
/*
set
*/
public ImageMosaic setType(MosaicType type) {
this.type = type;
return this;
}
public ImageMosaic setIntensity(int intensity) {
this.intensity = intensity;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageContrast.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageContrast.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ColorConvertTools;
import java.awt.Color;
import java.awt.image.BufferedImage;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2019-2-17
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ImageContrast extends PixelsOperation {
protected ContrastAlgorithm algorithm;
protected long threshold;
protected int offset, percentage;
public static enum ContrastAlgorithm {
GrayHistogramEqualization,
GrayHistogramStretching,
GrayHistogramShifting,
SaturationHistogramEqualization,
SaturationHistogramStretching,
SaturationHistogramShifting,
BrightnessHistogramEqualization,
BrightnessHistogramStretching,
BrightnessHistogramShifting,
SaturationBrightnessHistogramEqualization,
SaturationBrightnessHistogramStretching,
SaturationBrightnessHistogramShifting
}
public ImageContrast() {
this.operationType = OperationType.Contrast;
threshold = 0;
percentage = 0;
offset = 0;
}
@Override
public BufferedImage operateImage() {
if (image == null || operationType != OperationType.Contrast || null == algorithm) {
return image;
}
switch (algorithm) {
case GrayHistogramEqualization:
return grayHistogramEqualization(task, image);
case GrayHistogramStretching:
return grayHistogramStretching(task, image, threshold, percentage);
case GrayHistogramShifting:
return grayHistogramShifting(task, image, offset);
case SaturationHistogramEqualization:
return saturationHistogramEqualization(task, image);
case SaturationHistogramStretching:
return saturationHistogramStretching(task, image, threshold, percentage);
case SaturationHistogramShifting:
return saturationHistogramShifting(task, image, offset);
case BrightnessHistogramEqualization:
return brightnessHistogramEqualization(task, image);
case BrightnessHistogramStretching:
return brightnessHistogramStretching(task, image, threshold, percentage);
case BrightnessHistogramShifting:
return brightnessHistogramShifting(task, image, offset);
case SaturationBrightnessHistogramEqualization:
return saturationBrightnessHistogramEqualization(task, image);
case SaturationBrightnessHistogramStretching:
return saturationBrightnessHistogramStretching(task, image, threshold, percentage);
case SaturationBrightnessHistogramShifting:
return saturationBrightnessHistogramShifting(task, image, offset);
default:
return image;
}
}
// https://en.wikipedia.org/wiki/Histogram_equalization
public static BufferedImage grayHistogramEqualization(FxTask task, BufferedImage image) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] greyHistogram = new long[256];
int pixel, grey;
long count = 0;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
continue;
}
grey = ColorConvertTools.pixel2grayValue(pixel);
greyHistogram[grey]++;
count++;
}
}
if (count == 0) {
return image;
}
float nf = 255.0f / count;
long cumulative = 0;
int[] lookUpTable = new int[256];
for (int i = 0; i < 256; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
cumulative += greyHistogram[i];
lookUpTable[i] = Math.round(cumulative * nf);
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
grey = ColorConvertTools.pixel2grayValue(pixel);
grey = lookUpTable[grey];
target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey));
}
}
}
return target;
}
// https://blog.csdn.net/fang20277/article/details/51801093
public static BufferedImage grayHistogramStretching(FxTask task, BufferedImage image,
long threshold, int percentage) {
if (image == null || threshold < 0 || percentage < 0) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] greyHistogram = new long[256];
int pixel, grey;
long count = 0;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
continue;
}
grey = ColorConvertTools.pixel2grayValue(pixel);
greyHistogram[grey]++;
count++;
}
}
if (count == 0) {
return image;
}
int min = 0, max = 0;
long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100;
for (int i = 0; i < 256; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
v = greyHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
min = i;
break;
}
}
cumulative = 0;
for (int i = 255; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
v = greyHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
max = i;
break;
}
}
if (min == max) {
return null;
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
float scale = 255.0f / (max - min) + 0.5f;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
grey = ColorConvertTools.pixel2grayValue(pixel);
grey = (int) ((grey - min) * scale);
if (grey < 0) {
grey = 0;
} else if (grey > 255) {
grey = 255;
}
target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey));
}
}
}
return target;
}
public static BufferedImage grayHistogramShifting(FxTask task, BufferedImage image, int offset) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int pixel, grey;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
grey = ColorConvertTools.pixel2grayValue(pixel);
grey = Math.max(Math.min(grey + offset, 255), 0);
target.setRGB(x, y, ColorConvertTools.rgb2Pixel(grey, grey, grey));
}
}
}
return target;
}
public static BufferedImage saturationHistogramEqualization(FxTask task, BufferedImage image) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] saturationHistogram = new long[101];
long nonTransparent = 0;
int saturation;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
continue;
}
nonTransparent++;
saturation = Math.round(ColorConvertTools.getSaturation(new Color(p)) * 100);
saturationHistogram[saturation]++;
}
}
if (nonTransparent == 0) {
return image;
}
float nf = 100.0f / nonTransparent;
long cumulative = 0;
int[] lookUpTable = new int[101];
for (int i = 0; i < 101; ++i) {
cumulative += saturationHistogram[i];
lookUpTable[i] = Math.round(cumulative * nf);
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int pixel;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturation = lookUpTable[saturation];
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2]));
}
}
}
return target;
}
public static BufferedImage saturationHistogramStretching(FxTask task, BufferedImage image,
long threshold, int percentage) {
if (image == null || threshold < 0 || percentage < 0) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] saturationHistogram = new long[101];
long nonTransparent = 0;
int saturation, pixel;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
continue;
}
nonTransparent++;
saturation = Math.round(ColorConvertTools.getSaturation(new Color(pixel)) * 100);
saturationHistogram[saturation]++;
}
}
if (nonTransparent == 0) {
return image;
}
int min = 0, max = 0;
long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100;
for (int i = 0; i < 101; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
v = saturationHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
min = i;
break;
}
}
cumulative = 0;
for (int i = 100; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
v = saturationHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
max = i;
break;
}
}
if (min == max) {
return null;
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
float scale = 100.0f / (max - min);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
if (saturation <= min) {
saturation = 0;
} else if (saturation >= max) {
saturation = 100;
} else {
saturation = (int) ((saturation - min) * scale);
}
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2]));
}
}
}
return target;
}
public static BufferedImage saturationHistogramShifting(FxTask task, BufferedImage image, int offset) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int pixel, saturation;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturation = Math.max(Math.min(saturation + offset, 100), 0);
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, hsb[2]));
}
}
}
return target;
}
public static BufferedImage brightnessHistogramEqualization(FxTask task, BufferedImage colorImage) {
if (colorImage == null) {
return null;
}
int width = colorImage.getWidth();
int height = colorImage.getHeight();
long[] brightnessHistogram = new long[101];
long nonTransparent = 0;
int brightness;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = colorImage.getRGB(x, y);
if (p == 0) { // ignore transparent
continue;
}
nonTransparent++;
brightness = Math.round(ColorConvertTools.getBrightness(new Color(p)) * 100);
brightnessHistogram[brightness]++;
}
}
float nf = 100.0f / nonTransparent;
long cumulative = 0;
int[] lookUpTable = new int[101];
for (int i = 0; i < 101; ++i) {
cumulative += brightnessHistogram[i];
lookUpTable[i] = Math.round(cumulative * nf);
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = colorImage.getRGB(x, y);
if (p == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(p));
brightness = Math.round(hsb[2] * 100);
brightness = lookUpTable[brightness];
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f));
}
}
}
return target;
}
public static BufferedImage brightnessHistogramStretching(FxTask task, BufferedImage image,
long threshold, int percentage) {
if (image == null || threshold < 0 || percentage < 0) {
return null;
}
int brightness;
int width = image.getWidth();
int height = image.getHeight();
long[] brightnessHistogram = new long[101];
long nonTransparent = 0;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
int p = image.getRGB(x, y);
if (p == 0) {
continue;
}
nonTransparent++;
brightness = Math.round(ColorConvertTools.getBrightness(new Color(p)) * 100);
brightnessHistogram[brightness]++;
}
}
if (nonTransparent == 0) {
return image;
}
int min = 0, max = 0;
long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100;
for (int i = 0; i < 101; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
v = brightnessHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
min = i;
break;
}
}
cumulative = 0;
for (int i = 100; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
v = brightnessHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
max = i;
break;
}
}
if (min == max) {
return null;
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
float scale = 100.0f / (max - min);
int pixel;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
brightness = Math.round(hsb[2] * 100);
if (brightness <= min) {
brightness = 0;
} else if (brightness >= max) {
brightness = 100;
} else {
brightness = (int) ((brightness - min) * scale);
}
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f));
}
}
}
return target;
}
public static BufferedImage brightnessHistogramShifting(FxTask task, BufferedImage image, int offset) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int pixel, brightness;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
brightness = Math.round(hsb[2] * 100);
brightness = Math.max(Math.min(brightness + offset, 100), 0);
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], hsb[1], brightness / 100.0f));
}
}
}
return target;
}
public static BufferedImage saturationBrightnessHistogramEqualization(FxTask task, BufferedImage image) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] saturationHistogram = new long[101];
long[] brightnessHistogram = new long[101];
long nonTransparent = 0;
int pixel, saturation, brightness;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
continue;
}
nonTransparent++;
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturationHistogram[saturation]++;
brightness = Math.round(hsb[2] * 100);
brightnessHistogram[brightness]++;
}
}
if (nonTransparent == 0) {
return image;
}
float nf = 100.0f / nonTransparent;
long sCumulative = 0, bCumulative = 0;
int[] sLlookUpTable = new int[101], bLlookUpTable = new int[101];
for (int i = 0; i < 101; ++i) {
sCumulative += saturationHistogram[i];
sLlookUpTable[i] = Math.round(sCumulative * nf);
bCumulative += brightnessHistogram[i];
bLlookUpTable[i] = Math.round(bCumulative * nf);
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturation = sLlookUpTable[saturation];
brightness = Math.round(hsb[2] * 100);
brightness = bLlookUpTable[brightness];
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f));
}
}
}
return target;
}
public static BufferedImage saturationBrightnessHistogramStretching(FxTask task, BufferedImage image,
long threshold, int percentage) {
if (image == null || threshold < 0 || percentage < 0) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
long[] saturationHistogram = new long[101];
long[] brightnessHistogram = new long[101];
long nonTransparent = 0;
int pixel, saturation, brightness;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
continue;
}
nonTransparent++;
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturationHistogram[saturation]++;
brightness = Math.round(hsb[2] * 100);
brightnessHistogram[brightness]++;
}
}
if (nonTransparent == 0) {
return image;
}
int sMin = 0, sMax = 0, bMin = 0, bMax = 0;
long v, cumulative = 0, cumulativeThreshold = width * height * percentage / 100;
for (int i = 0; i < 101; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
v = saturationHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
sMin = i;
break;
}
}
cumulative = 0;
for (int i = 100; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
v = saturationHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
sMax = i;
break;
}
}
cumulative = 0;
for (int i = 0; i < 101; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
v = brightnessHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
bMin = i;
break;
}
}
cumulative = 0;
for (int i = 100; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
v = brightnessHistogram[i];
cumulative += v;
if (v > threshold || cumulative > cumulativeThreshold) {
bMax = i;
break;
}
}
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
float sScale = sMin == sMax ? -1 : (100.0f / (sMax - sMin));
float bScale = bMin == bMax ? -1 : (100.0f / (bMax - bMin));
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
if (sScale > 0) {
if (saturation <= sMin) {
saturation = 0;
} else if (saturation >= sMax) {
saturation = 100;
} else {
saturation = (int) ((saturation - sMin) * sScale);
}
}
brightness = Math.round(hsb[2] * 100);
if (bScale > 0) {
if (brightness <= bMin) {
brightness = 0;
} else if (brightness >= bMax) {
brightness = 100;
} else {
brightness = (int) ((brightness - bMin) * bScale);
}
}
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f));
}
}
}
return target;
}
public static BufferedImage saturationBrightnessHistogramShifting(FxTask task, BufferedImage image, int offset) {
if (image == null) {
return null;
}
int width = image.getWidth();
int height = image.getHeight();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int pixel, saturation, brightness;
for (int y = 0; y < height; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < width; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixel = image.getRGB(x, y);
if (pixel == 0) {
target.setRGB(x, y, 0);
} else {
float[] hsb = ColorConvertTools.color2hsb(new Color(pixel));
saturation = Math.round(hsb[1] * 100);
saturation = Math.max(Math.min(saturation + offset, 100), 0);
brightness = Math.round(hsb[2] * 100);
brightness = Math.max(Math.min(brightness + offset, 100), 0);
target.setRGB(x, y, Color.HSBtoRGB(hsb[0], saturation / 100.0f, brightness / 100.0f));
}
}
}
return target;
}
/*
get/set
*/
public ContrastAlgorithm getAlgorithm() {
return algorithm;
}
public ImageContrast setAlgorithm(ContrastAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public long getThreshold() {
return threshold;
}
public ImageContrast setThreshold(long thresholdValue) {
this.threshold = thresholdValue;
return this;
}
public int getPercentage() {
return percentage;
}
public ImageContrast setPercentage(int percentage) {
this.percentage = percentage;
return this;
}
public int getOffset() {
return offset;
}
public ImageContrast setOffset(int offset) {
this.offset = offset;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageConvolution.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageConvolution.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.tools.FloatMatrixTools;
/**
* @Author Mara
* @CreateDate 2018-11-10 19:35:49
* @License Apache License Version 2.0
*/
public class ImageConvolution extends PixelsOperation {
protected ConvolutionKernel kernel;
protected int matrixWidth, matrixHeight, edge_op, color_op, radiusX, radiusY, maxX, maxY;
protected boolean keepOpacity, isEmboss, isInvert;
protected float[][] matrix;
protected int[][] intMatrix;
protected int intScale;
public static enum SmoothAlgorithm {
GaussianBlur, AverageBlur, MotionBlur
}
public static enum SharpenAlgorithm {
UnsharpMasking, EightNeighborLaplace, FourNeighborLaplace
}
public ImageConvolution() {
this.operationType = OperationType.Convolution;
}
public static ImageConvolution create() {
return new ImageConvolution();
}
public ImageConvolution setKernel(ConvolutionKernel kernel) {
this.kernel = kernel;
matrix = kernel.getMatrix();
matrixWidth = matrix[0].length;
matrixHeight = matrix.length;
intMatrix = new int[matrixHeight][matrixWidth];
intScale = 10000; // Run integer calcualation instead of float/double calculation
for (int matrixY = 0; matrixY < matrixHeight; matrixY++) {
for (int matrixX = 0; matrixX < matrixWidth; matrixX++) {
intMatrix[matrixY][matrixX] = Math.round(matrix[matrixY][matrixX] * intScale);
}
}
edge_op = kernel.getEdge();
radiusX = matrixWidth / 2;
radiusY = matrixHeight / 2;
maxX = image.getWidth() - 1;
maxY = image.getHeight() - 1;
isEmboss = (kernel.getType() == ConvolutionKernel.Convolution_Type.EMBOSS);
color_op = kernel.getColor();
keepOpacity = (kernel.getType() != ConvolutionKernel.Convolution_Type.EMBOSS
&& kernel.getType() != ConvolutionKernel.Convolution_Type.EDGE_DETECTION);
isInvert = kernel.isInvert();
return this;
}
@Override
public BufferedImage start() {
if (image == null || kernel == null || kernel.getMatrix() == null) {
return image;
}
return super.start();
}
@Override
protected BufferedImage operateImage() {
if (image == null || operationType == null) {
return image;
}
if (scope == null || scope.isWhole()) {
return applyConvolution(task, image, kernel);
}
BufferedImage target = super.operateImage();
if (kernel.isGrey()) {
target = ImageGray.byteGray(task, target);
} else if (kernel.isBW()) {
target = ImageBinary.byteBinary(task, target);
}
return target;
}
@Override
protected Color operatePixel(BufferedImage target, Color color, int x, int y) {
Color newColor = applyConvolution(x, y);
if (isEmboss) {
int v = 128, red, blue, green;
red = Math.min(Math.max(newColor.getRed() + v, 0), 255);
green = Math.min(Math.max(newColor.getGreen() + v, 0), 255);
blue = Math.min(Math.max(newColor.getBlue() + v, 0), 255);
newColor = new Color(red, green, blue, newColor.getAlpha());
}
target.setRGB(x, y, newColor.getRGB());
return newColor;
}
public Color applyConvolution(int x, int y) {
try {
int red = 0, green = 0, blue = 0, opacity = 0;
int convolveX, convolveY;
matrix:
for (int matrixY = 0; matrixY < matrixHeight; matrixY++) {
if (taskInvalid()) {
return null;
}
for (int matrixX = 0; matrixX < matrixWidth; matrixX++) {
if (taskInvalid()) {
return null;
}
convolveX = x - radiusX + matrixX;
convolveY = y - radiusY + matrixY;
if (convolveX < 0 || convolveX > maxX
|| convolveY < 0 || convolveY > maxY) {
if (edge_op == ConvolutionKernel.Edge_Op.COPY) {
Color color = new Color(image.getRGB(x, y), true);
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
opacity = color.getAlpha();
break matrix;
} else {
/* fill zero */
continue;
}
}
Color color = new Color(image.getRGB(convolveX, convolveY), true);
red += color.getRed() * intMatrix[matrixY][matrixX];
green += color.getGreen() * intMatrix[matrixY][matrixX];
blue += color.getBlue() * intMatrix[matrixY][matrixX];
if (keepOpacity) {
opacity += color.getAlpha() * intMatrix[matrixY][matrixX];
}
}
}
red = Math.min(Math.max(red / intScale, 0), 255);
green = Math.min(Math.max(green / intScale, 0), 255);
blue = Math.min(Math.max(blue / intScale, 0), 255);
if (keepOpacity) {
opacity = Math.min(Math.max(opacity / intScale, 0), 255);
} else {
opacity = 255;
}
Color color;
if (isInvert) {
color = new Color(255 - red, 255 - green, 255 - blue, opacity);
} else {
color = new Color(red, green, blue, opacity);
}
return color;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
static
*/
public static BufferedImage applyConvolution(FxTask task, BufferedImage inSource,
ConvolutionKernel convolutionKernel) {
BufferedImage source;
int type = convolutionKernel.getType();
if (type == ConvolutionKernel.Convolution_Type.EDGE_DETECTION
|| type == ConvolutionKernel.Convolution_Type.EMBOSS) {
source = AlphaTools.removeAlpha(task, inSource);
} else {
source = inSource;
}
if (task != null && !task.isWorking()) {
return null;
}
float[] k = FloatMatrixTools.matrix2Array(task, convolutionKernel.getMatrix());
if (task != null && !task.isWorking()) {
return null;
}
if (k == null) {
return source;
}
int w = convolutionKernel.getWidth();
int h = convolutionKernel.getHeight();
Kernel kernel = new Kernel(w, h, k);
ConvolveOp imageOp;
if (convolutionKernel.getEdge() == ConvolutionKernel.Edge_Op.COPY) {
imageOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
} else {
imageOp = new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL, null);
}
BufferedImage target = applyConvolveOp(source, imageOp);
if (task != null && !task.isWorking()) {
return null;
}
if (type == ConvolutionKernel.Convolution_Type.EMBOSS) {
PixelsOperation pixelsOperation = PixelsOperationFactory.create(target, null,
OperationType.RGB, ColorActionType.Increase);
pixelsOperation.setIntPara1(128).setTask(task);
target = pixelsOperation.start();
if (task != null && !task.isWorking()) {
return null;
}
}
if (convolutionKernel.isInvert()) {
PixelsOperation pixelsOperation = PixelsOperationFactory.create(target, null,
OperationType.RGB, ColorActionType.Invert).setTask(task);
target = pixelsOperation.start();
if (task != null && !task.isWorking()) {
return null;
}
}
if (convolutionKernel.isGrey()) {
target = ImageGray.byteGray(task, target);
} else if (convolutionKernel.isBW()) {
target = ImageBinary.byteBinary(task, target);
}
if (task != null && !task.isWorking()) {
return null;
}
return target;
}
// source should have no alpha
public static BufferedImage applyConvolveOp(BufferedImage source, ConvolveOp imageOp) {
if (source == null || imageOp == null) {
return source;
}
int width = source.getWidth();
int height = source.getHeight();
int imageType = source.getType();
if (imageType == BufferedImage.TYPE_CUSTOM) {
imageType = BufferedImage.TYPE_INT_RGB;
}
BufferedImage target = new BufferedImage(width, height, imageType);
imageOp.filter(source, target);
return target;
}
/*
get/set
*/
@Override
public ImageConvolution setImage(BufferedImage image) {
this.image = image;
return this;
}
@Override
public ImageConvolution setImage(Image image) {
this.image = SwingFXUtils.fromFXImage(image, null);
return this;
}
@Override
public ImageConvolution setScope(ImageScope scope) {
this.scope = scope;
return this;
}
public ConvolutionKernel getKernel() {
return kernel;
}
public int[][] getIntMatrix() {
return intMatrix;
}
public ImageConvolution setIntMatrix(int[][] intMatrix) {
this.intMatrix = intMatrix;
return this;
}
public int getIntScale() {
return intScale;
}
public ImageConvolution setSum(int sum) {
this.intScale = sum;
return this;
}
public int getMatrixWidth() {
return matrixWidth;
}
public ImageConvolution setMatrixWidth(int matrixWidth) {
this.matrixWidth = matrixWidth;
return this;
}
public int getMatrixHeight() {
return matrixHeight;
}
public ImageConvolution setMatrixHeight(int matrixHeight) {
this.matrixHeight = matrixHeight;
return this;
}
public int getEdge_op() {
return edge_op;
}
public ImageConvolution setEdge_op(int edge_op) {
this.edge_op = edge_op;
return this;
}
public int getRadiusX() {
return radiusX;
}
public ImageConvolution setRadiusX(int radiusX) {
this.radiusX = radiusX;
return this;
}
public int getRadiusY() {
return radiusY;
}
public ImageConvolution setRadiusY(int radiusY) {
this.radiusY = radiusY;
return this;
}
public int getMaxX() {
return maxX;
}
public ImageConvolution setMaxX(int maxX) {
this.maxX = maxX;
return this;
}
public int getMaxY() {
return maxY;
}
public ImageConvolution setMaxY(int maxY) {
this.maxY = maxY;
return this;
}
public boolean isKeepOpacity() {
return keepOpacity;
}
public ImageConvolution setKeepOpacity(boolean keepOpacity) {
this.keepOpacity = keepOpacity;
return this;
}
public boolean isIsEmboss() {
return isEmboss;
}
public ImageConvolution setIsEmboss(boolean isEmboss) {
this.isEmboss = isEmboss;
return this;
}
public int getColor() {
return color_op;
}
public ImageConvolution setColor(int color_op) {
this.color_op = color_op;
return this;
}
public boolean isIsInvert() {
return isInvert;
}
public ImageConvolution setIsInvert(boolean isInvert) {
this.isInvert = isInvert;
return this;
}
public float[][] getMatrix() {
return matrix;
}
public ImageConvolution setMatrix(float[][] matrix) {
this.matrix = matrix;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageAttributes.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageAttributes.java | package mara.mybox.image.data;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import mara.mybox.value.FileExtensions;
import org.apache.pdfbox.rendering.ImageType;
/**
* @Author Mara
* @CreateDate 2018-6-18 6:53:00
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ImageAttributes {
public static enum Alpha {
Keep, Remove, PremultipliedAndKeep, PremultipliedAndRemove
}
protected String imageFormat, compressionType, colorSpaceName;
protected ImageType colorType;
protected int density, quality, ratioAdjustion, width;
protected Alpha alpha;
protected ImageBinary imageBinary;
protected boolean embedProfile, keepRatio;
protected int sourceWidth, sourceHeight, targetWidth, targetHeight;
protected ICC_Profile profile;
protected String profileName;
public ImageAttributes() {
init(null, null);
}
public ImageAttributes(String format, ImageType colorSpace, int density) {
init(null, format);
this.colorType = colorSpace;
this.density = density;
this.quality = 100;
imageBinary = null;
}
public ImageAttributes(BufferedImage image, String format) {
init(image, format);
}
public ImageAttributes(String format) {
init(null, format);
}
private void init(BufferedImage image, String format) {
if (format == null || !FileExtensions.SupportedImages.contains(format)) {
format = "png";
}
imageFormat = format.toLowerCase();
switch (imageFormat) {
case "jpg":
case "jpeg":
compressionType = "JPEG";
alpha = Alpha.Remove;
break;
case "gif":
compressionType = "LZW";
break;
case "tif":
case "tiff":
if (image != null && image.getType() == BufferedImage.TYPE_BYTE_BINARY) {
compressionType = "CCITT T.6";
} else {
compressionType = "Deflate";
}
break;
case "bmp":
compressionType = "BI_RGB";
alpha = Alpha.Remove;
break;
}
density = 96;
quality = 100;
}
/*
get/set
*/
public String getImageFormat() {
return imageFormat;
}
public ImageAttributes setImageFormat(String imageFormat) {
this.imageFormat = imageFormat;
return this;
}
public int getDensity() {
return density;
}
public ImageAttributes setDensity(int density) {
this.density = density;
return this;
}
public String getCompressionType() {
return compressionType;
}
public ImageAttributes setCompressionType(String compressionType) {
this.compressionType = compressionType;
return this;
}
public int getTargetWidth() {
return targetWidth;
}
public ImageAttributes setTargetWidth(int targetWidth) {
this.targetWidth = targetWidth;
return this;
}
public int getTargetHeight() {
return targetHeight;
}
public ImageAttributes setTargetHeight(int targetHeight) {
this.targetHeight = targetHeight;
return this;
}
public ImageType getColorType() {
return colorType;
}
public ImageAttributes setColorType(ImageType colorType) {
this.colorType = colorType;
return this;
}
public int getQuality() {
return quality;
}
public ImageAttributes setQuality(int quality) {
this.quality = quality;
return this;
}
public int getRatioAdjustion() {
return ratioAdjustion;
}
public ImageAttributes setRatioAdjustion(int ratioAdjustion) {
this.ratioAdjustion = ratioAdjustion;
return this;
}
public boolean isKeepRatio() {
return keepRatio;
}
public ImageAttributes setKeepRatio(boolean keepRatio) {
this.keepRatio = keepRatio;
return this;
}
public int getSourceWidth() {
return sourceWidth;
}
public ImageAttributes setSourceWidth(int sourceWidth) {
this.sourceWidth = sourceWidth;
return this;
}
public int getSourceHeight() {
return sourceHeight;
}
public ImageAttributes setSourceHeight(int sourceHeight) {
this.sourceHeight = sourceHeight;
return this;
}
public ImageBinary getImageBinary() {
return imageBinary;
}
public ImageAttributes setImageBinary(ImageBinary imageBinary) {
this.imageBinary = imageBinary;
return this;
}
public ICC_Profile getProfile() {
return profile;
}
public ImageAttributes setProfile(ICC_Profile profile) {
this.profile = profile;
return this;
}
public String getProfileName() {
return profileName;
}
public ImageAttributes setProfileName(String profileName) {
this.profileName = profileName;
return this;
}
public String getColorSpaceName() {
return colorSpaceName;
}
public ImageAttributes setColorSpaceName(String colorSpaceName) {
this.colorSpaceName = colorSpaceName;
return this;
}
public Alpha getAlpha() {
return alpha;
}
public ImageAttributes setAlpha(Alpha alpha) {
this.alpha = alpha;
return this;
}
public boolean isEmbedProfile() {
return embedProfile;
}
public ImageAttributes setEmbedProfile(boolean embedProfile) {
this.embedProfile = embedProfile;
return this;
}
public int getWidth() {
return width;
}
public ImageAttributes setWidth(int width) {
this.width = width;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/CropTools.java | alpha/MyBox/src/main/java/mara/mybox/image/data/CropTools.java | package mara.mybox.image.data;
import mara.mybox.image.tools.ScaleTools;
import java.awt.Color;
import java.awt.image.BufferedImage;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.data.DoubleShape;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2018-6-27 18:58:57
* @License Apache License Version 2.0
*/
public class CropTools {
public static BufferedImage cropInside(FxTask task, BufferedImage source, DoubleRectangle rect, Color bgColor) {
try {
if (rect == null || rect.isEmpty()) {
return source;
}
int width = source.getWidth();
int height = source.getHeight();
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage target = new BufferedImage(width, height, imageType);
int bgPixel = bgColor.getRGB();
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
if (DoubleShape.contains(rect, i, j)) {
target.setRGB(i, j, bgPixel);
} else {
target.setRGB(i, j, source.getRGB(i, j));
}
}
}
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return source;
}
}
public static BufferedImage cropOutside(FxTask task, BufferedImage source, DoubleRectangle rect, Color bgColor) {
try {
if (source == null || rect == null || rect.isEmpty()) {
return source;
}
int width = source.getWidth();
int height = source.getHeight();
int x1 = Math.max(0, (int) Math.ceil(rect.getX()));
int y1 = Math.max(0, (int) Math.ceil(rect.getY()));
if (x1 > width || y1 > height) {
return null;
}
int x2 = Math.min(width, (int) Math.floor(rect.getMaxX()));
int y2 = Math.min(height, (int) Math.floor(rect.getMaxY()));
int w = x2 - x1;
int h = y2 - y1;
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage target = new BufferedImage(w, h, imageType);
int bgPixel = bgColor.getRGB();
for (int y = 0; y < h; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < w; x++) {
if (task != null && !task.isWorking()) {
return null;
}
if (rect.contains(x1 + x, y1 + y)) {
target.setRGB(x, y, source.getRGB(x1 + x, y1 + y));
} else {
target.setRGB(x, y, bgPixel);
}
}
}
return target;
} catch (Exception e) {
MyBoxLog.error(e);
return source;
}
}
public static BufferedImage cropOutside(FxTask task, BufferedImage source, DoubleRectangle rect) {
return cropOutside(task, source, rect, Colors.TRANSPARENT);
}
public static BufferedImage cropOutside(FxTask task, BufferedImage source, double x1, double y1, double x2, double y2) {
return cropOutside(task, source, DoubleRectangle.xy12(x1, y1, x2, y2), Colors.TRANSPARENT);
}
public static BufferedImage sample(FxTask task, BufferedImage source, DoubleRectangle rectangle, int xscale, int yscale) {
try {
if (rectangle == null) {
return ScaleTools.scaleImageByScale(source, xscale, yscale);
}
int realXScale = xscale > 0 ? xscale : 1;
int realYScale = yscale > 0 ? yscale : 1;
BufferedImage bufferedImage = cropOutside(task, source, rectangle);
if (bufferedImage == null) {
return null;
}
int width = bufferedImage.getWidth() / realXScale;
int height = bufferedImage.getHeight() / realYScale;
bufferedImage = ScaleTools.scaleImageBySize(bufferedImage, width, height);
return bufferedImage;
} catch (Exception e) {
MyBoxLog.error(e);
return source;
}
}
public static BufferedImage sample(FxTask task, BufferedImage source, DoubleRectangle rectangle, int width) {
try {
if (rectangle == null) {
return ScaleTools.scaleImageWidthKeep(source, width);
}
BufferedImage bufferedImage = cropOutside(task, source, rectangle);
if (bufferedImage == null) {
return null;
}
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width);
return bufferedImage;
} catch (Exception e) {
MyBoxLog.error(e);
return source;
}
}
public static BufferedImage sample(FxTask task, BufferedImage source, int x1, int y1, int x2, int y2, int xscale, int yscale) {
if (x1 >= x2 || y1 >= y2 || x1 < 0 || x2 < 0 || y1 < 0 || y2 < 0) {
return null;
}
return sample(task, source, DoubleRectangle.xy12(x1, y1, x2, y2), xscale, yscale);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageQuantizationFactory.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageQuantizationFactory.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.color.ColorMatch;
import mara.mybox.controller.ControlImageQuantization;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm;
import static mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm.RegionKMeansClustering;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2019-2-13 14:44:03
* @License Apache License Version 2.0
*/
public class ImageQuantizationFactory {
public static ImageQuantization createFX(FxTask task, Image image, ImageScope scope,
ControlImageQuantization quantizationController, boolean recordCount) {
return create(task, image != null ? SwingFXUtils.fromFXImage(image, null) : null,
scope, quantizationController, recordCount);
}
public static ImageQuantization create(FxTask task, BufferedImage image, ImageScope scope,
ControlImageQuantization quantizationController, boolean recordCount) {
return create(task, image, scope, quantizationController.getAlgorithm(),
quantizationController.getQuanColors(),
quantizationController.getRegionSize(),
quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization
? quantizationController.getHsbWeight1() : quantizationController.getRgbWeight1(),
quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization
? quantizationController.getHsbWeight2() : quantizationController.getRgbWeight2(),
quantizationController.getAlgorithm() == QuantizationAlgorithm.HSBUniformQuantization
? quantizationController.getHsbWeight3() : quantizationController.getRgbWeight3(),
recordCount,
quantizationController.getQuanDitherCheck().isSelected(),
quantizationController.getFirstColorCheck().isSelected(),
quantizationController.colorMatch(),
quantizationController.getMaxLoop());
}
public static ImageQuantization create(FxTask task, BufferedImage image, ImageScope scope,
QuantizationAlgorithm algorithm, int quantizationSize,
int regionSize, int weight1, int weight2, int weight3,
boolean recordCount, boolean dithering, boolean firstColor,
ColorMatch colorMatch, int maxLoop) {
try {
ImageQuantization quantization;
switch (algorithm) {
case RGBUniformQuantization:
quantization = RGBUniformQuantization.create();
break;
case HSBUniformQuantization:
quantization = HSBUniformQuantization.create();
break;
case RegionPopularityQuantization:
quantization = RegionPopularityQuantization.create();
break;
case RegionKMeansClustering:
quantization = RegionKMeansClusteringQuantization.create();
break;
case KMeansClustering:
quantization = KMeansClusteringQuantization.create();
break;
// case ANN:
// return new RGBUniform(image, quantizationSize);
default:
quantization = RegionKMeansClusteringQuantization.create();
break;
}
quantization.setAlgorithm(algorithm).
setQuantizationSize(quantizationSize)
.setRegionSize(regionSize)
.setWeight1(weight1).setWeight2(weight2).setWeight3(weight3)
.setRecordCount(recordCount)
.setFirstColor(firstColor)
.setColorMatch(colorMatch)
.setMaxLoop(maxLoop)
.setOperationType(PixelsOperation.OperationType.Quantization)
.setImage(image).setScope(scope).setIsDithering(dithering)
.setTask(task);
return quantization.buildPalette();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static class RGBUniformQuantization extends ImageQuantization {
protected int redMod, redOffset, greenMod, greenOffset, blueMod, blueOffset;
protected int redSize, greenSize, blueSize;
public static RGBUniformQuantization create() {
return new RGBUniformQuantization();
}
@Override
public RGBUniformQuantization buildPalette() {
try {
regionSize = quantizationSize;
algorithm = QuantizationAlgorithm.RGBUniformQuantization;
float redWegiht = weight1 < 1 ? 1 : weight1;
float greenWegiht = weight2 < 1 ? 1 : weight2;
float blueWegiht = weight3 < 1 ? 1 : weight3;
float sum = weight1 + weight2 + weight3;
redWegiht = redWegiht / sum;
greenWegiht = greenWegiht / sum;
blueWegiht = blueWegiht / sum;
float x = (float) Math.cbrt(quantizationSize / (redWegiht * greenWegiht * blueWegiht));
float redValue = redWegiht * x;
redMod = (int) (256 / redValue);
redSize = (int) (256 / redMod) + 1;
float greenValue = greenWegiht * x;
greenMod = (int) (256 / greenValue);
greenSize = (int) (256 / greenMod) + 1;
float blueValue = blueWegiht * x;
blueMod = (int) (256 / blueValue);
blueSize = (int) (256 / blueMod) + 1;
// MyBoxLog.console("quantizationSize:" + quantizationSize + " x:" + x);
// MyBoxLog.console("redMod:" + redMod + " greenMod:" + greenMod + " blueMod:" + blueMod);
// MyBoxLog.console("redSize:" + redSize + " greenSize:" + greenSize + " blueSize:" + blueSize);
if (redSize <= 0 || greenSize <= 0 || blueSize <= 0
|| redMod <= 0 || greenMod <= 0 || blueMod <= 0) {
MyBoxLog.error(message("InvalidParameters"));
return this;
}
if (firstColor) {
palette = new Color[redSize][greenSize][blueSize];
} else {
redOffset = redMod / 2;
greenOffset = greenMod / 2;
blueOffset = blueMod / 2;
}
if (recordCount) {
counts = new HashMap<>();
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return this;
}
@Override
public String resultInfo() {
return message(algorithm.name()) + "\n"
+ message("ColorsRegionSize") + ": " + redSize * greenSize * blueSize + "\n"
+ "redMod: " + redMod + " greenMod: " + greenMod + " blueMod: " + blueMod + "\n"
+ "redSize: " + redSize + " greenSize: " + greenSize + " blueSize: " + blueSize;
}
@Override
public Color operateColor(Color color) {
try {
if (color.getRGB() == 0) {
return color;
}
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
Color mappedColor;
if (firstColor) {
int indexRed = red / redMod;
int indexGreen = green / greenMod;
int indexBlue = blue / blueMod;
if (palette[indexRed][indexGreen][indexBlue] == null) {
palette[indexRed][indexGreen][indexBlue] = color;
mappedColor = color;
} else {
mappedColor = palette[indexRed][indexGreen][indexBlue];
}
} else {
red = red - (red % redMod) + redOffset;
red = Math.min(Math.max(red, 0), 255);
green = green - (green % greenMod) + greenOffset;
green = Math.min(Math.max(green, 0), 255);
blue = blue - (blue % blueMod) + blueOffset;
blue = Math.min(Math.max(blue, 0), 255);
mappedColor = new Color(red, green, blue);
}
countColor(mappedColor);
return mappedColor;
} catch (Exception e) {
// MyBoxLog.error(e);
return color;
}
}
}
public static class HSBUniformQuantization extends ImageQuantization {
protected int hueMod, saturationMod, brightnessMod,
hueOffset, saturationOffset, brightnessOffset;
protected int hueSize, saturationSize, brightnessSize;
public static HSBUniformQuantization create() throws Exception {
return new HSBUniformQuantization();
}
@Override
public HSBUniformQuantization buildPalette() {
try {
regionSize = quantizationSize;
algorithm = QuantizationAlgorithm.HSBUniformQuantization;
float hueWegiht = weight1 < 1 ? 1 : weight1;
float saturationWegiht = weight2 < 1 ? 1 : weight2;
float brightnessWegiht = weight3 < 1 ? 1 : weight3;
float sum = hueWegiht + saturationWegiht + brightnessWegiht;
hueWegiht = hueWegiht / sum;
saturationWegiht = saturationWegiht / sum;
brightnessWegiht = brightnessWegiht / sum;
float x = (float) Math.cbrt(quantizationSize / (hueWegiht * saturationWegiht * brightnessWegiht));
float hueValue = hueWegiht * x;
hueMod = (int) (360 / hueValue);
hueSize = (int) (360 / hueMod) + 1;
float saturationValue = saturationWegiht * x;
saturationMod = (int) (100 / saturationValue);
saturationSize = (int) (100 / saturationMod) + 1;
float brightnessValue = brightnessWegiht * x;
brightnessMod = (int) (100 / brightnessValue);
brightnessSize = (int) (100 / brightnessMod) + 1;
// MyBoxLog.console("regionSize:" + regionSize + " x:" + x);
// MyBoxLog.console("hueMod:" + hueMod + " saturationMod:" + saturationMod + " brightnessMod:" + brightnessMod);
// MyBoxLog.console("hueSize:" + hueSize + " saturationSize:" + saturationSize + " brightnessSize:" + brightnessSize);
if (hueSize <= 0 || saturationSize <= 0 || saturationSize <= 0
|| hueMod <= 0 || saturationMod <= 0 || brightnessMod <= 0) {
MyBoxLog.error(message("InvalidParameters"));
return this;
}
if (firstColor) {
palette = new Color[hueSize][saturationSize][brightnessSize];
} else {
hueOffset = hueMod / 2;
saturationOffset = saturationMod / 2;
brightnessOffset = brightnessMod / 2;
}
if (recordCount) {
counts = new HashMap<>();
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return this;
}
@Override
public String resultInfo() {
return message(algorithm.name()) + "\n"
+ message("ColorsRegionSize") + ": " + hueSize * saturationSize * brightnessSize + "\n"
+ "hueMod: " + hueMod + " saturationMod: " + saturationMod + " brightnessMod: " + brightnessMod + "\n"
+ "hueSize: " + hueSize + " saturationSize: " + saturationSize + " brightnessSize: " + brightnessSize;
}
@Override
public Color operateColor(Color color) {
try {
if (color.getRGB() == 0) {
return color;
}
Color mappedColor;
float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
float h, s, b;
int hue = (int) (hsb[0] * 360);
int saturation = (int) (hsb[1] * 100);
int brightness = (int) (hsb[2] * 100);
if (firstColor) {
int indexHue = hue / hueMod;
int indexSaturation = saturation / saturationMod;
int indexBrightness = brightness / brightnessMod;
if (palette[indexHue][indexSaturation][indexBrightness] == null) {
palette[indexHue][indexSaturation][indexBrightness] = color;
mappedColor = color;
} else {
mappedColor = palette[indexHue][indexSaturation][indexBrightness];
}
} else {
hue = hue - (hue % hueMod) + hueOffset;
h = Math.min(Math.max(hue / 360.0f, 0.0f), 1.0f);
saturation = saturation - (saturation % saturationMod) + saturationOffset;
s = Math.min(Math.max(saturation / 100.0f, 0.0f), 1.0f);
brightness = brightness - (brightness % brightnessMod) + brightnessOffset;
b = Math.min(Math.max(brightness / 100.0f, 0.0f), 1.0f);
mappedColor = Color.getHSBColor(h, s, b);
}
countColor(mappedColor);
return mappedColor;
} catch (Exception e) {
// MyBoxLog.error(e);
return color;
}
}
}
public static class RegionQuantization extends ImageQuantization {
protected RGBUniformQuantization rgbPalette;
protected boolean large;
@Override
public RegionQuantization buildPalette() {
try {
large = image.getWidth() * image.getHeight() > regionSize;
if (large) {
rgbPalette = RGBUniformQuantization.create();
rgbPalette.setQuantizationSize(regionSize)
.setFirstColor(firstColor)
.setRecordCount(recordCount)
.setWeight1(weight1).setWeight2(weight2).setWeight3(weight3)
.setIsDithering(isDithering)
.setTask(task);
rgbPalette.buildPalette();
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return this;
}
@Override
public String resultInfo() {
return rgbPalette.resultInfo();
}
@Override
public Color operateColor(Color color) {
if (color.getRGB() == 0) {
return color;
}
Color regionColor = map(color);
handleRegionColor(color, regionColor);
return regionColor;
}
public Color map(Color color) {
if (color.getRGB() == 0) {
return color;
}
Color regionColor;
if (rgbPalette != null) {
regionColor = rgbPalette.operateColor(color);
} else {
regionColor = new Color(color.getRGB(), false);
}
return regionColor;
}
public void handleRegionColor(Color color, Color regionColor) {
}
}
public static class PopularityRegion extends RegionQuantization {
protected Map<Color, PopularityRegionValue> regionsMap;
public static PopularityRegion create() {
return new PopularityRegion();
}
@Override
public RegionQuantization buildPalette() {
super.buildPalette();
regionsMap = new HashMap<>();
return this;
}
@Override
public void handleRegionColor(Color color, Color regionColor) {
PopularityRegionValue value = regionsMap.get(regionColor);
if (value == null) {
value = new PopularityRegionValue();
value.regionColor = regionColor;
value.redAccum = color.getRed();
value.greenAccum = color.getGreen();
value.blueAccum = color.getBlue();
value.pixelsCount = 1;
regionsMap.put(regionColor, value);
} else {
value.redAccum += color.getRed();
value.greenAccum += color.getGreen();
value.blueAccum += color.getBlue();
value.pixelsCount += 1;
}
}
public List<PopularityRegionValue> getRegionValues(int quantizationSize) {
List<PopularityRegionValue> values = new ArrayList<>();
values.addAll(regionsMap.values());
for (PopularityRegionValue region : values) {
region.averageColor = new Color(
Math.min(255, (int) (region.redAccum / region.pixelsCount)),
Math.min(255, (int) (region.greenAccum / region.pixelsCount)),
Math.min(255, (int) (region.blueAccum / region.pixelsCount)));
}
Collections.sort(values, new Comparator<PopularityRegionValue>() {
@Override
public int compare(PopularityRegionValue r1, PopularityRegionValue r2) {
long diff = r2.pixelsCount - r1.pixelsCount;
if (diff == 0) {
return 0;
} else if (diff > 0) {
return 1;
} else {
return -1;
}
}
});
if (quantizationSize < values.size()) {
values = values.subList(0, quantizationSize);
}
regionsMap.clear();
return values;
}
}
public static class RegionPopularityQuantization extends ImageQuantization {
protected PopularityRegion regionQuantization;
protected List<PopularityRegionValue> regionValues;
public static RegionPopularityQuantization create() {
return new RegionPopularityQuantization();
}
@Override
public RegionPopularityQuantization buildPalette() {
try {
algorithm = QuantizationAlgorithm.RegionPopularityQuantization;
colorMatch = new ColorMatch();
regionQuantization = PopularityRegion.create();
regionQuantization.setQuantizationSize(regionSize)
.setRegionSize(regionSize)
.setFirstColor(firstColor)
.setWeight1(weight1).setWeight2(weight2).setWeight3(weight3)
.setRecordCount(false)
.setImage(image).setScope(scope)
.setOperationType(PixelsOperation.OperationType.Quantization)
.setIsDithering(isDithering)
.setTask(task);
regionQuantization.buildPalette().start();
regionValues = regionQuantization.getRegionValues(quantizationSize);
if (recordCount) {
counts = new HashMap<>();
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return this;
}
@Override
public String resultInfo() {
if (regionValues == null) {
return null;
}
return message(algorithm.name()) + "\n"
+ message("ColorsNumber") + ": " + regionValues.size() + "\n-----\n"
+ regionQuantization.resultInfo();
}
@Override
public Color operateColor(Color color) {
if (color.getRGB() == 0) {
return color;
}
Color mappedColor = null;
Color regionColor = regionQuantization.map(color);
for (int i = 0; i < regionValues.size(); ++i) {
PopularityRegionValue region = regionValues.get(i);
if (region.regionColor.equals(regionColor)) {
mappedColor = region.averageColor;
break;
}
}
if (mappedColor == null) {
double minDistance = Integer.MAX_VALUE;
PopularityRegionValue nearestRegion = regionValues.get(0);
for (int i = 0; i < regionValues.size(); ++i) {
PopularityRegionValue region = regionValues.get(i);
double distance = colorMatch.distance(region.averageColor, color);
if (distance < minDistance) {
minDistance = distance;
nearestRegion = region;
}
}
mappedColor = nearestRegion.averageColor;
}
countColor(mappedColor);
return mappedColor;
}
}
public static class KMeansRegion extends RegionQuantization {
protected List<Color> regionColors;
public static KMeansRegion create() {
return new KMeansRegion();
}
@Override
public RegionQuantization buildPalette() {
super.buildPalette();
regionColors = new ArrayList<>();
return this;
}
@Override
public void handleRegionColor(Color color, Color regionColor) {
if (!regionColors.contains(regionColor)) {
regionColors.add(regionColor);
}
}
}
public static class RegionKMeansClusteringQuantization extends ImageQuantization {
protected ImageRegionKMeans kmeans;
public static RegionKMeansClusteringQuantization create() throws Exception {
return new RegionKMeansClusteringQuantization();
}
@Override
public RegionKMeansClusteringQuantization buildPalette() {
algorithm = QuantizationAlgorithm.RegionKMeansClustering;
kmeans = imageRegionKMeans();
if (recordCount) {
counts = new HashMap<>();
}
return this;
}
@Override
public String resultInfo() {
if (kmeans == null) {
return null;
}
return message(algorithm.name()) + "\n"
+ message("ColorsNumber") + ": " + kmeans.centerSize() + "\n"
+ message("ActualLoop") + ": " + kmeans.getLoopCount() + "\n-----\n"
+ kmeans.regionQuantization.resultInfo();
}
@Override
public Color operateColor(Color color) {
if (color.getRGB() == 0) {
return color;
}
Color mappedColor = kmeans.map(color);
countColor(mappedColor);
return mappedColor;
}
/*
get/set
*/
public ImageRegionKMeans getKmeans() {
return kmeans;
}
public void setKmeans(ImageRegionKMeans kmeans) {
this.kmeans = kmeans;
}
}
public static class KMeansClusteringQuantization extends ImageQuantization {
protected ImageKMeans kmeans;
public static KMeansClusteringQuantization create() throws Exception {
return new KMeansClusteringQuantization();
}
@Override
public KMeansClusteringQuantization buildPalette() {
algorithm = QuantizationAlgorithm.KMeansClustering;
kmeans = imageKMeans();
if (recordCount) {
counts = new HashMap<>();
}
return this;
}
@Override
public String resultInfo() {
if (kmeans == null) {
return null;
}
return message(algorithm.name()) + "\n"
+ message("ColorsNumber") + ": " + kmeans.centerSize() + "\n"
+ message("ActualLoop") + ": " + kmeans.getLoopCount();
}
@Override
public Color operateColor(Color color) {
if (color.getRGB() == 0) {
return color;
}
Color mappedColor = kmeans.map(color);
countColor(mappedColor);
return mappedColor;
}
/*
get/set
*/
public ImageKMeans getKmeans() {
return kmeans;
}
public void setKmeans(ImageKMeans kmeans) {
this.kmeans = kmeans;
}
}
// https://www.researchgate.net/publication/220502178_On_spatial_quantization_of_color_images
public static class Spatialquantization {
}
// https://www.codeproject.com/Tips/1046574/OctTree-Based-Nearest-Color-Search
public class ColorFinder {
// Declare a root node to contain all of the source colors.
private Node rootNode;
public ColorFinder(Color[] colors) {
// Create the root node.
rootNode = new Node(0, colors);
// Add all source colors to it.
for (int i = 0; i < colors.length; ++i) {
rootNode.AddColor(i);
}
}
public int GetNearestColorIndex(Color color) {
return rootNode.GetNearestColorIndex(color)[0];
}
private class Node {
private int level;
private Color[] colors;
private final Node[] children = new Node[8];
private int colorIndex = -1;
// Cached distance calculations.
private final int[][] Distance = new int[256][256];
// Cached bit masks.
private final int[] Mask = {128, 64, 32, 16, 8, 4, 2, 1};
public Node() {
// precalculate every possible distance
for (int i = 0; i < 256; ++i) {
for (int j = 0; j < 256; ++j) {
Distance[i][j] = ((i - j) * (i - j));
}
}
}
public Node(int level, Color[] colors) {
this.level = level;
this.colors = colors;
}
public void AddColor(int colorIndex) {
if (level == 7) {
// LEAF MODE.
// The deepest level contains the averageColor mappedValue and no children.
this.colorIndex = colorIndex;
} else {
// BRANCH MODE.
// Get the oct mappedValue for the specified source averageColor at this level.
int index = colorIndex(colors[colorIndex], level);
// If the necessary child node doesn't exist, root it.
if (children[index] == null) {
children[index] = new Node((level + 1), colors);
}
// Pass the averageColor along to the proper child node.
children[index].AddColor(colorIndex);
}
}
public int colorIndex(Color color, int level) {
// Take 1 bit from each averageColor channel
// to return a 3-bit value ranging from 0 to 7.
// Level 0 uses the highest bit, level 1 uses the second-highest bit, etc.
int shift = (7 - level);
return (((color.getRed() & Mask[level]) >> shift)
| ((color.getGreen() & Mask[level]) << 1 >> shift)
| ((color.getBlue() & Mask[level]) << 2 >> shift));
}
public int distance(int b1, int b2) {
return Distance[b1][b2];
}
public int distance(Color c1, Color c2) {
return distance(c1.getRed(), c2.getRed())
+ distance(c1.getGreen(), c2.getGreen())
+ distance(c1.getBlue(), c2.getBlue());
}
public int[] GetNearestColorIndex(Color color) {
int[] ret = new int[2];
ret[0] = -1;
ret[1] = Integer.MAX_VALUE;
if (level == 7) { // LEAF MODE.
ret[0] = colorIndex;
ret[1] = distance(color, colors[colorIndex]);
} else { // BRANCH MODE.
int index = colorIndex(color, level);
if (children[index] == null) {
int minDistance = Integer.MAX_VALUE;
int minIndex = -1;
for (Node child : children) {
if (child != null) {
int[] v = child.GetNearestColorIndex(color);
if (v[1] < minDistance) {
minIndex = v[0];
minDistance = v[1];
}
}
}
ret[0] = minIndex;
ret[1] = minDistance;
} else { // DIRECT CHILD EXISTS.
ret = children[index].GetNearestColorIndex(color);
}
}
return ret;
}
}
}
public static class Octree {
private OctreeNode rootNode;
public Octree(BufferedImage image, int colorsNumber) {
rootNode = new OctreeNode();
rootNode.afterSetParam();
for (int i = 0; i < image.getWidth(); ++i) {
for (int j = 0; j < image.getHeight(); ++j) {
int colorValue = image.getRGB(i, j);
if (colorValue == 0) { // transparency is not involved
continue;
}
rootNode.addColor(colorValue, colorsNumber);
}
}
}
public static class OctreeNode {
protected int level = 0;
protected OctreeNode parent;
protected OctreeNode[] children = new OctreeNode[8];
protected boolean isLeaf = false;
protected int redAccum = 0;
protected int greenAccum = 0;
protected int blueAccum = 0;
protected int piexlsCount = 0;
protected Map<Integer, List<OctreeNode>> levelMapping;
public void addColor(int colorValue, int number) {
if (level != 0 || this.parent != null) {
throw new UnsupportedOperationException();
}
int speed = 7 + 1 - number;
int r = colorValue >> 16 & 0xFF;
int g = colorValue >> 8 & 0xFF;
int b = colorValue & 0xFF;
OctreeNode proNode = this;
for (int i = 7; i >= speed; --i) {
int item = ((r >> i & 1) << 2) + ((g >> i & 1) << 1) + (b >> i & 1);
OctreeNode child = proNode.getChild(item);
if (child == null) {
child = new OctreeNode();
child.setLevel(8 - i);
child.setParent(proNode);
child.afterSetParam();
this.levelMapping.get(child.getLevel()).add(child);
proNode.setChild(item, child);
}
if (i == speed) {
child.setIsLeaf(true);
}
if (child.isIsLeaf()) {
child.setPixel(r, g, b);
break;
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/ImageColorSpace.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageColorSpace.java | package mara.mybox.image.data;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageReaderSpi;
import com.github.jaiimageio.impl.plugins.pcx.PCXImageWriterSpi;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageReaderSpi;
import com.github.jaiimageio.impl.plugins.pnm.PNMImageWriterSpi;
import com.github.jaiimageio.impl.plugins.raw.RawImageReaderSpi;
import com.github.jaiimageio.impl.plugins.raw.RawImageWriterSpi;
import com.github.jaiimageio.impl.plugins.tiff.TIFFImageReaderSpi;
import com.github.jaiimageio.impl.plugins.tiff.TIFFImageWriterSpi;
import com.luciad.imageio.webp.WebPImageReaderSpi;
import com.luciad.imageio.webp.WebPImageWriterSpi;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.spi.IIORegistry;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.image.file.ImageFileWriters;
import static mara.mybox.image.file.ImageJpgFile.getJpegCompressionTypes;
import mara.mybox.value.Languages;
import org.apache.pdfbox.rendering.ImageType;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @License Apache License Version 2.0
*/
public class ImageColorSpace {
public static List<String> RGBColorSpaces = new ArrayList<>() {
{
addAll(Arrays.asList(
"sRGB", "Linear sRGB", "Apple RGB", "Adobe RGB", "Color Match RGB", "ECI RGB"
));
}
};
public static List<String> CMYKColorSpaces = new ArrayList<>() {
{
addAll(Arrays.asList(
"ECI CMYK", "Adobe CMYK - CoatedFOGRA27", "Adobe CMYK - CoatedFOGRA39",
"Adobe CMYK - JapanColor2001Coated", "Adobe CMYK_JapanColor2001Uncoated",
"Adobe CMYK - JapanColor2002Newspaper", "Adobe CMYK - JapanWebCoated",
"Adobe CMYK - USSheetfedCoated", "Adobe CMYK - USSheetfedUncoated",
"Adobe CMYK - USWebCoatedSWOP", "Adobe CMYK - USWebUncoated",
"Adobe CMYK - UncoatedFOGRA29", "Adobe CMYK - WebCoatedFOGRA28"
));
}
};
public static List<String> OtherColorSpaces = new ArrayList<>() {
{
addAll(Arrays.asList(
"Gray", "BlackOrWhite"
));
}
};
public static void registrySupportedImageFormats() {
IIORegistry registry = IIORegistry.getDefaultInstance();
// tiff of ECI CMYK can not be opened by reader in jdk
registry.registerServiceProvider(new TIFFImageWriterSpi());
registry.registerServiceProvider(new TIFFImageReaderSpi());
// registry.registerServiceProvider(new BMPImageWriterSpi());
// registry.registerServiceProvider(new BMPImageReaderSpi());
// registry.registerServiceProvider(new GIFImageWriterSpi());
// registry.registerServiceProvider(new WBMPImageWriterSpi());
// registry.registerServiceProvider(new WBMPImageReaderSpi());
registry.registerServiceProvider(new RawImageWriterSpi());
registry.registerServiceProvider(new RawImageReaderSpi());
registry.registerServiceProvider(new PCXImageWriterSpi());
registry.registerServiceProvider(new PCXImageReaderSpi());
registry.registerServiceProvider(new PNMImageWriterSpi());
registry.registerServiceProvider(new PNMImageReaderSpi());
// registry.registerServiceProvider(new J2KImageWriterSpi());
// registry.registerServiceProvider(new J2KImageReaderSpi());
// String readFormats[] = ImageIO.getReaderFormatNames();
// String writeFormats[] = ImageIO.getWriterFormatNames();
// MyBoxLog.console("Readers:" + Arrays.asList(readFormats));
// MyBoxLog.console("Writers:" + Arrays.asList(writeFormats));
//Readers:[JPG, JPEG 2000, tiff, bmp, PCX, gif, WBMP, PNG, RAW, JPEG, PNM, tif, TIFF, wbmp, jpeg, jpg, JPEG2000, BMP, pcx, GIF, png, raw, pnm, TIF, jpeg2000, jpeg 2000]
//Writers:[JPEG 2000, JPG, tiff, bmp, PCX, gif, WBMP, PNG, RAW, JPEG, PNM, tif, TIFF, wbmp, jpeg, jpg, JPEG2000, BMP, pcx, GIF, png, raw, pnm, TIF, jpeg2000, jpeg 2000]
registry.registerServiceProvider(new WebPImageWriterSpi());
registry.registerServiceProvider(new WebPImageReaderSpi());
}
public static String[] getCompressionTypes(String imageFormat, String colorSpace, boolean hasAlpha) {
if (imageFormat == null || colorSpace == null) {
return null;
}
String[] compressionTypes;
switch (imageFormat) {
case "jpg":
case "jpeg":
compressionTypes = getJpegCompressionTypes();
break;
case "gif":
compressionTypes = new String[]{"LZW"};
break;
case "tif":
case "tiff": // Summarized based on API of class "com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam" and debugging
if (Languages.message("BlackOrWhite").equals(colorSpace)) {
compressionTypes = new String[]{"CCITT T.6", "CCITT RLE",
"CCITT T.4", "ZLib", "Deflate", "LZW", "PackBits"};
} else {
if (hasAlpha || ImageColorSpace.CMYKColorSpaces.contains(colorSpace)) {
compressionTypes = new String[]{"LZW", "ZLib", "Deflate",
"PackBits"};
} else {
compressionTypes = new String[]{"LZW", "ZLib", "Deflate",
"JPEG", "PackBits"};
}
}
// compressionTypes = ImageTools.getTiffCompressionTypes();
break;
case "bmp": // Summarized based on API of class "com.github.jaiimageio.plugins.bmp.BMPImageWriteParam" and debugging
if (Languages.message("Gray").equals(colorSpace)) {
compressionTypes = new String[]{"BI_RGB", "BI_RLE8",
"BI_BITFIELDS"};
} else if (Languages.message("BlackOrWhite").equals(colorSpace)) {
compressionTypes = new String[]{"BI_RGB", "BI_BITFIELDS"};
} else {
compressionTypes = new String[]{"BI_RGB", "BI_BITFIELDS"};
}
break;
default:
compressionTypes = getCompressionTypes(imageFormat);
}
return compressionTypes;
}
public static String[] getCompressionTypes(String imageFormat, ImageType imageColor) {
if (imageFormat == null || imageColor == null) {
return null;
}
String[] compressionTypes = null;
switch (imageFormat) {
case "jpg":
case "jpeg":
compressionTypes = getJpegCompressionTypes();
break;
case "gif":
String[] giftypes = {"LZW"};
return giftypes;
case "tif":
case "tiff": // Summarized based on API of class "com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam" and debugging
switch (imageColor) {
case BINARY: {
String[] types = {"CCITT T.6", "CCITT RLE", "CCITT T.4",
"ZLib", "Deflate", "LZW", "PackBits"};
return types;
}
case GRAY: {
String[] types = {"LZW", "ZLib", "Deflate", "JPEG",
"PackBits"};
return types;
}
case RGB: {
String[] types = {"LZW", "ZLib", "Deflate", "JPEG",
"PackBits"};
return types;
}
case ARGB: {
String[] types = {"LZW", "ZLib", "Deflate", "PackBits"};
return types;
}
default:
break;
}
// compressionTypes = ImageTools.getTiffCompressionTypes();
break;
case "bmp": // Summarized based on API of class "com.github.jaiimageio.plugins.bmp.BMPImageWriteParam" and debugging
switch (imageColor) {
case BINARY: {
String[] types = {"BI_RGB", "BI_BITFIELDS"};
return types;
}
case GRAY: {
String[] types = {"BI_RGB", "BI_RLE8", "BI_BITFIELDS"};
return types;
}
case RGB: {
String[] types = {"BI_RGB", "BI_BITFIELDS"};
return types;
}
case ARGB: {
return null;
}
default:
// compressionTypes = getCompressionTypes(imageFormat);
}
break;
default:
compressionTypes = getCompressionTypes(imageFormat);
}
return compressionTypes;
}
public static String[] getCompressionTypes(String imageFormat) {
try {
ImageWriter writer = ImageFileWriters.getWriter(imageFormat);
ImageWriteParam param = writer.getDefaultWriteParam();
return param.getCompressionTypes();
} catch (Exception e) {
return null;
}
}
public static boolean canImageCompressed(String imageFormat) {
return getCompressionTypes(imageFormat) != null;
}
public static String imageType(int type) {
switch (type) {
case BufferedImage.TYPE_3BYTE_BGR:
return "3BYTE_BGR";
case BufferedImage.TYPE_4BYTE_ABGR:
return "4BYTE_ABGR";
case BufferedImage.TYPE_4BYTE_ABGR_PRE:
return "4BYTE_ABGR_PRE";
case BufferedImage.TYPE_BYTE_BINARY:
return "BYTE_BINARY";
case BufferedImage.TYPE_BYTE_GRAY:
return "BYTE_GRAY";
case BufferedImage.TYPE_BYTE_INDEXED:
return "BYTE_INDEXED";
case BufferedImage.TYPE_CUSTOM:
return "CUSTOM";
case BufferedImage.TYPE_INT_ARGB:
return "INT_ARGB";
case BufferedImage.TYPE_INT_ARGB_PRE:
return "INT_ARGB_PRE";
case BufferedImage.TYPE_INT_BGR:
return "INT_BGR";
case BufferedImage.TYPE_INT_RGB:
return "INT_RGB";
case BufferedImage.TYPE_USHORT_555_RGB:
return "USHORT_555_RGB";
case BufferedImage.TYPE_USHORT_565_RGB:
return "USHORT_565_RGB";
}
return type + "";
}
public static ColorSpace srgbColorSpace() {
return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_sRGB);
}
public static ColorSpace grayColorSpace() {
return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_GRAY);
}
public static ColorSpace linearSRGBColorSpace() {
return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_LINEAR_RGB);
}
public static ColorSpace ciexyzColorSpace() {
return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_CIEXYZ);
}
public static ColorSpace pyccColorSpace() {
return ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_PYCC);
}
public static ColorSpace appleRGBColorSpace() {
return new ICC_ColorSpace(appleRGBProfile());
}
public static ColorSpace adobeRGBColorSpace() {
return new ICC_ColorSpace(adobeRGBProfile());
}
public static ColorSpace colorMatchRGBColorSpace() {
return new ICC_ColorSpace(colorMatchRGBProfile());
}
public static ColorSpace eciRGBColorSpace() {
return new ICC_ColorSpace(eciRGBProfile());
}
public static ICC_ColorSpace eciCmykColorSpace() {
try {
return new ICC_ColorSpace(eciCmykProfile());
} catch (Exception ex) {
return null;
}
}
//
public static ICC_ColorSpace internalColorSpace(String profileName) {
try {
return new ICC_ColorSpace(internalProfile(profileName));
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static ICC_ColorSpace colorSpace(String profileName) {
try {
return new ICC_ColorSpace(iccProfile(profileName));
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static ICC_ColorSpace adobeCmykColorSpace() {
try {
return new ICC_ColorSpace(adobeCmykProfile());
} catch (Exception ex) {
return null;
}
}
// https://stackoverflow.com/questions/8118712/java-cmyk-to-rgb-with-profile-output-is-too-dark/12132556#12132556
public static ICC_Profile internalProfileByName(String name) {
try {
switch (name) {
case "sRGB":
return sRGBProfile();
case "Linear sRGB":
return linearRGBProfile();
case "Apple RGB":
return appleRGBProfile();
case "Adobe RGB":
return adobeRGBProfile();
case "Color Match RGB":
return colorMatchRGBProfile();
case "ECI RGB":
return eciRGBProfile();
case "ECI CMYK":
return eciCmykProfile();
case "Adobe CMYK - CoatedFOGRA27":
return internalProfile("AdobeCMYK_CoatedFOGRA27.icc");
case "Adobe CMYK - CoatedFOGRA39":
return internalProfile("AdobeCMYK_CoatedFOGRA39.icc");
case "Adobe CMYK - JapanColor2001Coated":
return internalProfile("AdobeCMYK_JapanColor2001Coated.icc");
case "Adobe CMYK - JapanColor2001Uncoated":
return internalProfile("AdobeCMYK_JapanColor2001Uncoated.icc");
case "Adobe CMYK - JapanColor2002Newspaper":
return internalProfile("AdobeCMYK_JapanColor2002Newspaper.icc");
case "Adobe CMYK - JapanWebCoated":
return internalProfile("AdobeCMYK_JapanWebCoated.icc");
case "Adobe CMYK - USSheetfedCoated":
return internalProfile("AdobeCMYK_USSheetfedCoated.icc");
case "Adobe CMYK - USSheetfedUncoated":
return internalProfile("AdobeCMYK_USSheetfedUncoated.icc");
case "Adobe CMYK - USWebCoatedSWOP":
return internalProfile("AdobeCMYK_USWebCoatedSWOP.icc");
case "Adobe CMYK - USWebUncoated":
return internalProfile("AdobeCMYK_USWebUncoated.icc");
case "Adobe CMYK - UncoatedFOGRA29":
return internalProfile("AdobeCMYK_UncoatedFOGRA29.icc");
case "Adobe CMYK - WebCoatedFOGRA28":
return internalProfile("AdobeCMYK_WebCoatedFOGRA28.icc");
case "Gray":
return grayProfile();
default:
if (Languages.message("Gray").equals(name)) {
return grayProfile();
}
return null;
}
} catch (Exception e) {
return null;
}
}
public static ICC_Profile iccProfile(String file) {
try {
ICC_Profile profile = ICC_Profile.getInstance(file);
return iccProfile(profile);
} catch (Exception ex) {
return null;
}
}
public static ICC_Profile internalProfile(String filename) {
try {
File file = FxFileTools.getInternalFile("/data/ICC/" + filename, "ICC", filename);
ICC_Profile profile = ICC_Profile.getInstance(file.getAbsolutePath());
return iccProfile(profile);
} catch (Exception ex) {
return null;
}
}
public static ICC_Profile iccProfile(ICC_Profile profile) {
try {
if (profile.getProfileClass() != ICC_Profile.CLASS_DISPLAY) {
byte[] profileData = profile.getData(); // Need to clone entire profile, due to a JDK 7 bug
if (profileData[ICC_Profile.icHdrRenderingIntent] == ICC_Profile.icPerceptual) {
intToBigEndian(ICC_Profile.icSigDisplayClass, profileData, ICC_Profile.icHdrDeviceClass); // Header is first
profile = ICC_Profile.getInstance(profileData);
}
}
return profile;
} catch (Exception ex) {
return null;
}
}
static void intToBigEndian(int value, byte[] array, int index) {
array[index] = (byte) (value >> 24);
array[index + 1] = (byte) (value >> 16);
array[index + 2] = (byte) (value >> 8);
array[index + 3] = (byte) (value);
}
public static ICC_Profile sRGBProfile() {
return ICC_Profile.getInstance(ICC_ColorSpace.CS_sRGB);
}
public static ICC_Profile grayProfile() {
return ICC_Profile.getInstance(ICC_ColorSpace.CS_GRAY);
}
public static ICC_Profile linearRGBProfile() {
return ICC_Profile.getInstance(ICC_ColorSpace.CS_LINEAR_RGB);
}
public static ICC_Profile xyzProfile() {
return ICC_Profile.getInstance(ICC_ColorSpace.CS_CIEXYZ);
}
public static ICC_Profile pyccProfile() {
return ICC_Profile.getInstance(ICC_ColorSpace.CS_PYCC);
}
public static ICC_Profile eciRGBProfile() {
return internalProfile("ECI_RGB_v2_ICCv4.icc");
}
public static ICC_Profile appleRGBProfile() {
return internalProfile("Adobe_AppleRGB.icc");
}
public static ICC_Profile adobeRGBProfile() {
return internalProfile("AdobeRGB_1998.icc");
}
public static ICC_Profile colorMatchRGBProfile() {
return internalProfile("Adobe_ColorMatchRGB.icc");
}
public static ICC_Profile eciCmykProfile() {
return internalProfile("ECI_CMYK.icc");
}
public static ICC_Profile adobeCmykProfile() {
return internalProfile("AdobeCMYK_UncoatedFOGRA29.icc");
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsOperationFactory.java | alpha/MyBox/src/main/java/mara/mybox/image/data/PixelsOperationFactory.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.PixelsOperation.ColorActionType;
import mara.mybox.image.data.PixelsOperation.OperationType;
import static mara.mybox.image.data.PixelsOperation.OperationType.Blend;
import static mara.mybox.image.data.PixelsOperation.OperationType.Color;
import mara.mybox.image.tools.ColorBlendTools;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2019-2-13 14:44:03
* @License Apache License Version 2.0
*/
public class PixelsOperationFactory {
public static PixelsOperation createFX(Image image, ImageScope scope, OperationType operationType) {
return create(image != null ? SwingFXUtils.fromFXImage(image, null) : null,
scope, operationType);
}
public static PixelsOperation create(BufferedImage image, ImageScope scope, OperationType operationType) {
return create(image, scope, operationType, null);
}
public static PixelsOperation create(BufferedImage image, ImageScope scope,
OperationType operationType, ColorActionType colorActionType) {
switch (operationType) {
case ShowScope:
return new ShowScope(image, scope);
case SelectPixels:
return new SelectPixels(image, scope);
case ReplaceColor:
return new ReplaceColor(image, scope);
case Color:
return new ColorSet(image, scope);
case Blend:
return new BlendColor(image, scope);
case Sepia:
return new Sepia(image, scope);
case Thresholding:
return new Thresholding(image, scope);
case Opacity:
switch (colorActionType) {
case Increase:
return new IncreaseOpacity(image, scope);
case Decrease:
return new DecreaseOpacity(image, scope);
case Set:
default:
return new SetOpacity(image, scope);
}
case PreOpacity:
switch (colorActionType) {
case Increase:
return new IncreasePreOpacity(image, scope);
case Decrease:
return new DecreasePreOpacity(image, scope);
case Set:
default:
return new SetPreOpacity(image, scope);
}
case Brightness:
switch (colorActionType) {
case Increase:
return new IncreaseBrightness(image, scope);
case Decrease:
return new DecreaseBrightness(image, scope);
case Set:
default:
return new SetBrightness(image, scope);
}
case Saturation:
switch (colorActionType) {
case Increase:
return new IncreaseSaturation(image, scope);
case Decrease:
return new DecreaseSaturation(image, scope);
case Set:
default:
return new SetSaturation(image, scope);
}
case Hue:
switch (colorActionType) {
case Increase:
return new IncreaseHue(image, scope);
case Decrease:
return new DecreaseHue(image, scope);
case Set:
default:
return new SetHue(image, scope);
}
case Red:
switch (colorActionType) {
case Increase:
return new IncreaseRed(image, scope);
case Decrease:
return new DecreaseRed(image, scope);
case Filter:
return new FilterRed(image, scope);
case Invert:
return new InvertRed(image, scope);
case Set:
default:
return new SetRed(image, scope);
}
case Green:
switch (colorActionType) {
case Increase:
return new IncreaseGreen(image, scope);
case Decrease:
return new DecreaseGreen(image, scope);
case Filter:
return new FilterGreen(image, scope);
case Invert:
return new InvertGreen(image, scope);
case Set:
default:
return new SetGreen(image, scope);
}
case Blue:
switch (colorActionType) {
case Increase:
return new IncreaseBlue(image, scope);
case Decrease:
return new DecreaseBlue(image, scope);
case Filter:
return new FilterBlue(image, scope);
case Invert:
return new InvertBlue(image, scope);
case Set:
default:
return new SetBlue(image, scope);
}
case Yellow:
switch (colorActionType) {
case Increase:
return new IncreaseYellow(image, scope);
case Decrease:
return new DecreaseYellow(image, scope);
case Filter:
return new FilterYellow(image, scope);
case Invert:
return new InvertYellow(image, scope);
case Set:
default:
return new SetYellow(image, scope);
}
case Cyan:
switch (colorActionType) {
case Increase:
return new IncreaseCyan(image, scope);
case Decrease:
return new DecreaseCyan(image, scope);
case Filter:
return new FilterCyan(image, scope);
case Invert:
return new InvertCyan(image, scope);
case Set:
default:
return new SetCyan(image, scope);
}
case Magenta:
switch (colorActionType) {
case Increase:
return new IncreaseMagenta(image, scope);
case Decrease:
return new DecreaseMagenta(image, scope);
case Filter:
return new FilterMagenta(image, scope);
case Invert:
return new InvertMagenta(image, scope);
case Set:
default:
return new SetMagenta(image, scope);
}
case RGB:
switch (colorActionType) {
case Increase:
return new IncreaseRGB(image, scope);
case Decrease:
return new DecreaseRGB(image, scope);
case Invert:
return new InvertRGB(image, scope);
// case Set:
// default:
// return new SetRGB(image, scope);
}
default:
return null;
}
}
public static PixelsOperation createFX(Image image, ImageScope scope,
OperationType operationType, ColorActionType colorActionType) {
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
return create(bufferedImage, scope, operationType, colorActionType);
}
public static BufferedImage replaceColor(FxTask task, BufferedImage image,
Color oldColor, Color newColor, int distance) {
PixelsOperation pixelsOperation = replaceColorOperation(task, image, oldColor, newColor, distance);
if (pixelsOperation == null) {
return image;
}
return pixelsOperation.start();
}
public static PixelsOperation replaceColorOperation(FxTask task, BufferedImage image,
Color oldColor, Color newColor, double threshold) {
if (oldColor == null || threshold < 0) {
return null;
}
try {
ImageScope scope = new ImageScope();
scope.setShapeType(ImageScope.ShapeType.Whole);
scope.addColor(oldColor);
scope.setColorThreshold(threshold);
PixelsOperation pixelsOperation = PixelsOperationFactory.create(image,
scope, OperationType.ReplaceColor, ColorActionType.Set)
.setColorPara1(oldColor)
.setColorPara2(newColor)
.setTask(task);
return pixelsOperation;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
subclass
*/
public static class ShowScope extends PixelsOperation {
private final float maskOpacity;
private final Color maskColor;
public ShowScope(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.ShowScope;
this.image = image;
this.scope = scope;
maskOpacity = scope.getMaskOpacity();
maskColor = scope.getMaskColor();
}
@Override
protected boolean inScope(int x, int y, Color color) {
return !super.inScope(x, y, color);
}
@Override
protected Color skipTransparent(BufferedImage target, int x, int y) {
try {
Color color = ColorBlendTools.blendColor(Colors.TRANSPARENT, maskOpacity, maskColor, true);
target.setRGB(x, y, color.getRGB());
return color;
} catch (Exception e) {
return null;
}
}
@Override
protected Color operateColor(Color color) {
return ColorBlendTools.blendColor(color, maskOpacity, maskColor, true);
}
}
public static class SelectPixels extends PixelsOperation {
public SelectPixels(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.SelectPixels;
this.image = image;
this.scope = scope;
}
@Override
protected Color skipTransparent(BufferedImage target, int x, int y) {
try {
target.setRGB(x, y, colorPara1.getRGB());
return colorPara1;
} catch (Exception e) {
return null;
}
}
@Override
protected boolean inScope(int x, int y, Color color) {
return !super.inScope(x, y, color);
}
@Override
protected Color operateColor(Color color) {
return colorPara1;
}
}
public static class Sepia extends PixelsOperation {
public Sepia(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Sepia;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return ColorConvertTools.pixel2Sepia(color, intPara1);
}
}
public static class Thresholding extends PixelsOperation {
public Thresholding(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Thresholding;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return ColorConvertTools.thresholdingColor(color, intPara1, intPara2, intPara3);
}
}
public static class ReplaceColor extends PixelsOperation {
private float paraHue, paraSaturation, paraBrightness,
colorHue, colorSaturation, colorBrightness;
private boolean directReplace;
public ReplaceColor(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.ReplaceColor;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
boolPara1 = boolPara2 = boolPara3 = true;
directReplace = false;
}
@Override
public BufferedImage start() {
directReplace = (boolPara1 && boolPara2 && boolPara3)
|| (!boolPara1 && !boolPara2 && !boolPara3);
if (!directReplace) {
float[] hsb = ColorConvertTools.color2hsb(colorPara2);
paraHue = hsb[0];
paraSaturation = hsb[1];
paraBrightness = hsb[2];
}
return super.start();
}
@Override
protected Color operateColor(Color color) {
if (directReplace) {
return colorPara2;
}
float[] hsb = ColorConvertTools.color2hsb(color);
colorHue = boolPara1 ? paraHue : hsb[0];
colorSaturation = boolPara2 ? paraSaturation : hsb[1];
colorBrightness = boolPara3 ? paraBrightness : hsb[2];
return ColorConvertTools.hsb2rgb(colorHue, colorSaturation, colorBrightness);
}
}
public static class ColorSet extends PixelsOperation {
private float paraHue, paraSaturation, paraBrightness,
colorHue, colorSaturation, colorBrightness;
private boolean directReplace;
public ColorSet(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Color;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
boolPara1 = boolPara2 = boolPara3 = true;
directReplace = false;
}
@Override
public BufferedImage start() {
directReplace = (boolPara1 && boolPara2 && boolPara3)
|| (!boolPara1 && !boolPara2 && !boolPara3);
if (!directReplace) {
float[] hsb = ColorConvertTools.color2hsb(colorPara1);
paraHue = hsb[0];
paraSaturation = hsb[1];
paraBrightness = hsb[2];
}
return super.start();
}
@Override
protected Color operateColor(Color color) {
if (directReplace) {
return colorPara1;
}
float[] hsb = ColorConvertTools.color2hsb(color);
colorHue = boolPara1 ? paraHue : hsb[0];
colorSaturation = boolPara2 ? paraSaturation : hsb[1];
colorBrightness = boolPara3 ? paraBrightness : hsb[2];
return ColorConvertTools.hsb2rgb(colorHue, colorSaturation, colorBrightness);
}
}
public static class BlendColor extends PixelsOperation {
protected PixelsBlend blender;
public BlendColor(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blend;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
public BlendColor setBlender(PixelsBlend blender) {
this.blender = blender;
return this;
}
@Override
protected Color operateColor(Color color) {
if (blender == null) {
return color;
}
return blender.blend(colorPara1, color);
}
}
public static class SetOpacity extends PixelsOperation {
public SetOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(intPara1, 0), 255));
}
}
public static class IncreaseOpacity extends PixelsOperation {
public IncreaseOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(color.getAlpha() + intPara1, 0), 255));
}
}
public static class DecreaseOpacity extends PixelsOperation {
public DecreaseOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(color.getAlpha() - intPara1, 0), 255));
}
}
public static class SetPreOpacity extends PixelsOperation {
protected Color bkColor;
public SetPreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class IncreasePreOpacity extends PixelsOperation {
protected Color bkColor;
public IncreasePreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(color.getAlpha() + intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class DecreasePreOpacity extends PixelsOperation {
protected Color bkColor;
public DecreasePreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(color.getAlpha() - intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class SetBrightness extends PixelsOperation {
public SetBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class IncreaseBrightness extends PixelsOperation {
public IncreaseBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[2] * (1.0f + floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class DecreaseBrightness extends PixelsOperation {
public DecreaseBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[2] * (1.0f - floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class SetSaturation extends PixelsOperation {
public SetSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class IncreaseSaturation extends PixelsOperation {
public IncreaseSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[1] * (1.0f + floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class DecreaseSaturation extends PixelsOperation {
public DecreaseSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[1] * (1.0f - floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class SetHue extends PixelsOperation {
public SetHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class IncreaseHue extends PixelsOperation {
public IncreaseHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[0] + floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class DecreaseHue extends PixelsOperation {
public DecreaseHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[0] - floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class SetRed extends PixelsOperation {
public SetRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class IncreaseRed extends PixelsOperation {
public IncreaseRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(color.getRed() + intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class DecreaseRed extends PixelsOperation {
public DecreaseRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(color.getRed() - intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class FilterRed extends PixelsOperation {
public FilterRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Filter;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), 0, 0, color.getAlpha());
}
}
public static class InvertRed extends PixelsOperation {
public InvertRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Invert;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(255 - color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class SetGreen extends PixelsOperation {
public SetGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class IncreaseGreen extends PixelsOperation {
public IncreaseGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(color.getGreen() + intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class DecreaseGreen extends PixelsOperation {
public DecreaseGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(color.getGreen() - intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class FilterGreen extends PixelsOperation {
public FilterGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Filter;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(0, color.getGreen(), 0, color.getAlpha());
}
}
public static class InvertGreen extends PixelsOperation {
public InvertGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Invert;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), 255 - color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class SetBlue extends PixelsOperation {
public SetBlue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blue;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(),
Math.min(Math.max(intPara1, 0), 255), color.getAlpha());
}
}
public static class IncreaseBlue extends PixelsOperation {
public IncreaseBlue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blue;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(),
Math.min(Math.max(color.getBlue() + intPara1, 0), 255), color.getAlpha());
| 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/image/data/ImageScope.java | alpha/MyBox/src/main/java/mara/mybox/image/data/ImageScope.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
import mara.mybox.color.ColorMatch;
import mara.mybox.color.ColorMatch.MatchAlgorithm;
import mara.mybox.data.DoubleCircle;
import mara.mybox.data.DoubleEllipse;
import mara.mybox.data.DoublePolygon;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.data.IntPoint;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.tools.ImageScopeTools;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2018-8-1 16:22:41
* @License Apache License Version 2.0
*/
public class ImageScope {
public static String ValueSeparator = ",";
protected String background, name, shapeData, colorData, outlineName;
protected ShapeType shapeType;
protected List<Color> colors;
protected List<IntPoint> points;
protected DoubleRectangle rectangle;
protected DoubleCircle circle;
protected DoubleEllipse ellipse;
protected DoublePolygon polygon;
protected ColorMatch colorMatch;
protected boolean shapeExcluded, colorExcluded;
protected Image image, clip;
protected Color maskColor;
protected float maskOpacity;
protected BufferedImage outlineSource, outline;
public static enum ShapeType {
Whole, Matting4, Matting8, Rectangle, Circle, Ellipse, Polygon, Outline
}
public ImageScope() {
init();
}
public final void init() {
shapeType = ShapeType.Whole;
colorMatch = new ColorMatch();
maskColor = Colors.TRANSPARENT;
maskOpacity = 0.5f;
shapeExcluded = false;
resetParameters();
}
public final void resetParameters() {
rectangle = null;
circle = null;
ellipse = null;
polygon = null;
shapeData = null;
colorData = null;
outlineName = null;
outlineSource = null;
outline = null;
points = new ArrayList<>();
clearColors();
}
public ImageScope cloneValues() {
return ImageScopeTools.cloneAll(this);
}
public boolean isWhole() {
return (shapeType == null || shapeType == ShapeType.Whole)
&& (colors == null || colors.isEmpty());
}
public void decode(FxTask task) {
if (colorData != null) {
ImageScopeTools.decodeColorData(this);
}
if (shapeData != null) {
ImageScopeTools.decodeShapeData(this);
}
if (outlineName != null) {
decodeOutline(task);
}
}
public BufferedImage decodeOutline(FxTask task) {
outlineSource = null;
outline = null;
try {
if (outlineName.startsWith("img/") || outlineName.startsWith("buttons/")) {
outlineSource = SwingFXUtils.fromFXImage(new Image(outlineName), null);
} else {
File file = new File(outlineName);
if (file.exists()) {
outlineSource = ImageIO.read(file);
}
}
} catch (Exception e) {
}
return outlineSource;
}
public void encode(FxTask task) {
ImageScopeTools.encodeColorData(this);
ImageScopeTools.encodeShapeData(this);
ImageScopeTools.encodeOutline(task, this);
}
public void addPoint(IntPoint point) {
if (point == null) {
return;
}
if (points == null) {
points = new ArrayList<>();
}
if (!points.contains(point)) {
points.add(point);
}
}
public void addPoint(int x, int y) {
if (x < 0 || y < 0) {
return;
}
IntPoint point = new IntPoint(x, y);
addPoint(point);
}
public void setPoint(int index, int x, int y) {
if (x < 0 || y < 0 || points == null || index < 0 || index >= points.size()) {
return;
}
IntPoint point = new IntPoint(x, y);
points.set(index, point);
}
public void deletePoint(int index) {
if (points == null || index < 0 || index >= points.size()) {
return;
}
points.remove(index);
}
public void clearPoints() {
points = new ArrayList<>();
}
/*
color match
*/
protected boolean isMatchColor(Color color1, Color color2) {
boolean match = colorMatch.isMatch(color1, color2);
return colorExcluded ? !match : match;
}
public boolean isMatchColors(Color color) {
return colorMatch.isMatchColors(colors, color, colorExcluded);
}
public boolean addColor(Color color) {
if (color == null) {
return false;
}
if (colors == null) {
colors = new ArrayList<>();
}
if (!colors.contains(color)) {
colors.add(color);
return true;
} else {
return false;
}
}
public void clearColors() {
colors = null;
}
/**
*
* @param x the x of the pixel
* @param y the y of the pixel
* @param color the color of the pixel
* @return whether in image scope
*/
public boolean inScope(int x, int y, Color color) {
return inShape(x, y) && isMatchColors(color);
}
public boolean inShape(int x, int y) {
return true;
}
/*
Static methods
*/
public static ImageScope create() {
return new ImageScope();
}
public static boolean valid(ImageScope data) {
return data != null
&& data.getColorMatch() != null
&& data.getShapeType() != null;
}
public static ShapeType shapeType(String type) {
try {
return ShapeType.valueOf(type);
} catch (Exception e) {
return ShapeType.Whole;
}
}
public static MatchAlgorithm matchAlgorithm(String a) {
try {
return MatchAlgorithm.valueOf(a);
} catch (Exception e) {
return ColorMatch.DefaultAlgorithm;
}
}
/*
customized get/set
*/
public ShapeType getShapeType() {
if (shapeType == null) {
shapeType = ShapeType.Whole;
}
return shapeType;
}
public ImageScope setShapeType(ShapeType shapeType) {
this.shapeType = shapeType != null ? shapeType : ShapeType.Whole;
return this;
}
public ImageScope setShapeType(String shapeType) {
this.shapeType = shapeType(shapeType);
return this;
}
public double getColorThreshold() {
return colorMatch.getThreshold();
}
public void setColorThreshold(double threshold) {
colorMatch.setThreshold(threshold);
}
public MatchAlgorithm getColorAlgorithm() {
return colorMatch.getAlgorithm();
}
public void setColorAlgorithm(MatchAlgorithm algorithm) {
colorMatch.setAlgorithm(algorithm);
}
public void setColorAlgorithm(String algorithm) {
colorMatch.setAlgorithm(matchAlgorithm(algorithm));
}
public boolean setColorWeights(String weights) {
return colorMatch.setColorWeights(weights);
}
public String getColorWeights() {
return colorMatch.getColorWeights();
}
/*
get/set
*/
public DoubleRectangle getRectangle() {
return rectangle;
}
public ImageScope setRectangle(DoubleRectangle rectangle) {
this.rectangle = rectangle;
return this;
}
public DoubleCircle getCircle() {
return circle;
}
public void setCircle(DoubleCircle circle) {
this.circle = circle;
}
public Image getImage() {
return image;
}
public ImageScope setImage(Image image) {
this.image = image;
return this;
}
public ColorMatch getColorMatch() {
return colorMatch;
}
public List<Color> getColors() {
return colors;
}
public ImageScope setColors(List<Color> colors) {
this.colors = colors;
return this;
}
public boolean isColorExcluded() {
return colorExcluded;
}
public ImageScope setColorExcluded(boolean colorExcluded) {
this.colorExcluded = colorExcluded;
return this;
}
public float getMaskOpacity() {
return maskOpacity;
}
public ImageScope setMaskOpacity(float maskOpacity) {
this.maskOpacity = maskOpacity;
return this;
}
public Color getMaskColor() {
return maskColor;
}
public ImageScope setMaskColor(Color maskColor) {
this.maskColor = maskColor;
return this;
}
public String getBackground() {
return background;
}
public boolean isShapeExcluded() {
return shapeExcluded;
}
public ImageScope setShapeExcluded(boolean shapeExcluded) {
this.shapeExcluded = shapeExcluded;
return this;
}
public List<IntPoint> getPoints() {
return points;
}
public void setPoints(List<IntPoint> points) {
this.points = points;
}
public DoubleEllipse getEllipse() {
return ellipse;
}
public void setEllipse(DoubleEllipse ellipse) {
this.ellipse = ellipse;
}
public DoublePolygon getPolygon() {
return polygon;
}
public void setPolygon(DoublePolygon polygon) {
this.polygon = polygon;
}
public void setBackground(String background) {
this.background = background;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BufferedImage getOutline() {
return outline;
}
public ImageScope setOutline(BufferedImage outline) {
this.outline = outline;
return this;
}
public BufferedImage getOutlineSource() {
return outlineSource;
}
public ImageScope setOutlineSource(BufferedImage outlineSource) {
this.outlineSource = outlineSource;
return this;
}
public Image getClip() {
return clip;
}
public void setClip(Image clip) {
this.clip = clip;
}
public String getShapeData() {
return shapeData;
}
public void setShapeData(String shapeData) {
this.shapeData = shapeData;
}
public String getColorData() {
return colorData;
}
public void setColorData(String colorData) {
this.colorData = colorData;
}
public String getOutlineName() {
return outlineName;
}
public void setOutlineName(String outlineName) {
this.outlineName = outlineName;
}
}
| 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/dev/Test.java | alpha/MyBox/src/main/java/mara/mybox/dev/Test.java | package mara.mybox.dev;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import javafx.geometry.Bounds;
/**
* @Author Mara
* @CreateDate 2023-8-7
* @License Apache License Version 2.0
*/
public class Test {
/* https://github.com/Mararsh/MyBox/issues/1816
Following are results of checking these values in Java20:
javafx.scene.shape.Rectangle: Rectangle[x=0.0, y=0.0, width=5.0, height=6.0, fill=0x000000ff]
default isPickOnBounds: false
rect.contains (rect.getX(), rect.getY()): true rect.contains (rect.getWidth(), rect.getHeight()):false
rect.getBoundsInLocal():
bind.getMinX: 0.0 bind.getMinY: 0.0 bind.getMaxX: 5.0 bind.getMaxY: 6.0 bind.getMaxX: 5.0 bind.getWidth: 5.0 bind.getHeight: 6.0
bind.contains (bind.getMinX(), bind.getMinY()): true bind.contains (bind.getMaxX(), bind.getMaxY()):true bind.contains (bind.getWidth(), bind.getHeight()):true
---------------------
javafx.scene.shape.Rectangle: Rectangle[x=0.0, y=0.0, width=5.0, height=6.0, fill=0x000000ff]
isPickOnBounds: true
rect.contains (rect.getX(), rect.getY()): true rect.contains (rect.getWidth(), rect.getHeight()):true
rect.getBoundsInLocal():
bind.getMinX: 0.0 bind.getMinY: 0.0 bind.getMaxX: 5.0 bind.getMaxY: 6.0 bind.getMaxX: 5.0 bind.getWidth: 5.0 bind.getHeight: 6.0
bind.contains (bind.getMinX(), bind.getMinY()): true bind.contains (bind.getMaxX(), bind.getMaxY()):true bind.contains (bind.getWidth(), bind.getHeight()):true
---------------------
java.awt.geom.Rectangle2D.Double: java.awt.geom.Rectangle2D$Double[x=0.0,y=0.0,w=5.0,h=6.0]
rect2d.getMinX: 0.0 rect2d.getMinY: 0.0 rect2d.getMaxX: 5.0 rect2d.getMaxY: 6.0 rect2d.getMaxX: 5.0 rect2d.getWidth: 5.0 rect2d.getHeight: 6.0
rect2d.contains (rect.getX(), rect2d.getY()): true rect2d.contains (rect.getWidth(), rect2d.getHeight()):false
rect2d.getBounds():
bind2d.getMinX: 0.0 bind2d.getMinY: 0.0 bind2d.getMaxX: 5.0 bind2d.getMaxY: 6.0 bind2d.getMaxX: 5.0 bind2d.getWidth: 5.0 bind2d.getHeight: 6.0
bind2d.contains (bind2d.getMinX(), bind2d.getMinY()): true bind2d.contains (bind2d.getMaxX(), bind2d.getMaxY()):false bind2d.contains (bind2d.getWidth(), bind2d.getHeight()):false
*/
public static void rectangleBounds() {
javafx.scene.shape.Rectangle rect = new javafx.scene.shape.Rectangle(0, 0, 5, 6);
MyBoxLog.console("javafx.scene.shape.Rectangle: " + rect.toString());
MyBoxLog.console("default isPickOnBounds: " + rect.isPickOnBounds());
MyBoxLog.console("rect.contains (rect.getX(), rect.getY()): " + rect.contains(rect.getX(), rect.getY())
+ " rect.contains (rect.getWidth(), rect.getHeight()):" + rect.contains(rect.getWidth(), rect.getHeight()));
Bounds bind = rect.getBoundsInLocal();
MyBoxLog.console("rect.getBoundsInLocal(): ");
MyBoxLog.console("bind.getMinX: " + bind.getMinX()
+ " bind.getMinY: " + bind.getMinY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getMaxY: " + bind.getMaxY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getWidth: " + bind.getWidth()
+ " bind.getHeight: " + bind.getHeight());
MyBoxLog.console("bind.contains (bind.getMinX(), bind.getMinY()): " + bind.contains(bind.getMinX(), bind.getMinY())
+ " bind.contains (bind.getMaxX(), bind.getMaxY()):" + bind.contains(bind.getMaxX(), bind.getMaxY())
+ " bind.contains (bind.getWidth(), bind.getHeight()):" + bind.contains(bind.getWidth(), bind.getHeight()));
MyBoxLog.console("---------------------");
rect.setPickOnBounds(!rect.isPickOnBounds());
MyBoxLog.console("javafx.scene.shape.Rectangle: " + rect.toString());
MyBoxLog.console("isPickOnBounds: " + rect.isPickOnBounds());
MyBoxLog.console("rect.contains (rect.getX(), rect.getY()): " + rect.contains(rect.getX(), rect.getY())
+ " rect.contains (rect.getWidth(), rect.getHeight()):" + rect.contains(rect.getWidth(), rect.getHeight()));
bind = rect.getBoundsInLocal();
MyBoxLog.console("rect.getBoundsInLocal(): ");
MyBoxLog.console("bind.getMinX: " + bind.getMinX()
+ " bind.getMinY: " + bind.getMinY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getMaxY: " + bind.getMaxY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getWidth: " + bind.getWidth()
+ " bind.getHeight: " + bind.getHeight());
MyBoxLog.console("bind.contains (bind.getMinX(), bind.getMinY()): " + bind.contains(bind.getMinX(), bind.getMinY())
+ " bind.contains (bind.getMaxX(), bind.getMaxY()):" + bind.contains(bind.getMaxX(), bind.getMaxY())
+ " bind.contains (bind.getWidth(), bind.getHeight()):" + bind.contains(bind.getWidth(), bind.getHeight()));
MyBoxLog.console("---------------------");
Rectangle2D.Double rect2d = new Rectangle2D.Double(0, 0, 5, 6);
MyBoxLog.console("java.awt.geom.Rectangle2D.Double: " + rect2d.toString());
MyBoxLog.console("rect2d.getMinX: " + rect2d.getMinX()
+ " rect2d.getMinY: " + rect2d.getMinY()
+ " rect2d.getMaxX: " + rect2d.getMaxX()
+ " rect2d.getMaxY: " + rect2d.getMaxY()
+ " rect2d.getMaxX: " + rect2d.getMaxX()
+ " rect2d.getWidth: " + rect2d.getWidth()
+ " rect2d.getHeight: " + rect2d.getHeight());
MyBoxLog.console("rect2d.contains (rect.getX(), rect2d.getY()): " + rect2d.contains(rect2d.getX(), rect2d.getY())
+ " rect2d.contains (rect.getWidth(), rect2d.getHeight()):" + rect2d.contains(rect2d.getWidth(), rect2d.getHeight()));
Rectangle bind2d = rect2d.getBounds();
MyBoxLog.console("rect2d.getBounds(): ");
MyBoxLog.console("bind2d.getMinX: " + bind2d.getMinX()
+ " bind2d.getMinY: " + bind2d.getMinY()
+ " bind2d.getMaxX: " + bind2d.getMaxX()
+ " bind2d.getMaxY: " + bind2d.getMaxY()
+ " bind2d.getMaxX: " + bind2d.getMaxX()
+ " bind2d.getWidth: " + bind2d.getWidth()
+ " bind2d.getHeight: " + bind2d.getHeight());
MyBoxLog.console("bind2d.contains (bind2d.getMinX(), bind2d.getMinY()): " + bind2d.contains(bind2d.getMinX(), bind2d.getMinY())
+ " bind2d.contains (bind2d.getMaxX(), bind2d.getMaxY()):" + bind2d.contains(bind2d.getMaxX(), bind2d.getMaxY())
+ " bind2d.contains (bind2d.getWidth(), bind2d.getHeight()):" + bind2d.contains(bind2d.getWidth(), bind2d.getHeight()));
}
}
| 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/dev/MyBoxLog.java | alpha/MyBox/src/main/java/mara/mybox/dev/MyBoxLog.java | package mara.mybox.dev;
import java.util.Date;
import javafx.application.Platform;
import mara.mybox.controller.MyBoxLogViewerController;
import mara.mybox.db.data.BaseData;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.table.TableMyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-11-24
* @License Apache License Version 2.0
*/
public class MyBoxLog extends BaseData {
protected long mblid, count;
protected Date time;
protected LogType logType;
protected String fileName, className, methodName, log, comments, callers, typeName;
protected int line;
public static MyBoxLog LastMyBoxLog;
public static long LastRecordTime;
public static int MinInterval = 1; // ms
public static enum LogType {
Console, Error, Debug, Info, Macro
}
public MyBoxLog() {
mblid = -1;
time = new Date();
logType = LogType.Console;
}
@Override
public boolean valid() {
return valid(this);
}
@Override
public boolean setValue(String column, Object value) {
return setValue(this, column, value);
}
@Override
public Object getValue(String column) {
return getValue(this, column);
}
public boolean equalTo(MyBoxLog myMyboxLog) {
return myMyboxLog != null && logType == myMyboxLog.getLogType()
&& log != null && log.equals(myMyboxLog.getLog())
&& fileName != null && fileName.equals(myMyboxLog.getFileName())
&& className != null && className.equals(myMyboxLog.getClassName())
&& methodName != null && methodName.equals(myMyboxLog.getMethodName())
&& callers != null && callers.equals(myMyboxLog.getCallers())
&& line == myMyboxLog.getLine();
}
/*
static methods;
*/
public static MyBoxLog create() {
return new MyBoxLog();
}
public static boolean setValue(MyBoxLog data, String column, Object value) {
if (data == null || column == null) {
return false;
}
try {
switch (column) {
case "mblid":
data.setMblid(value == null ? -1 : (long) value);
return true;
case "time":
data.setTime(value == null ? null : (Date) value);
return true;
case "log_type":
data.setLogType(logType((short) value));
return true;
case "file_name":
data.setFileName(value == null ? null : (String) value);
return true;
case "class_name":
data.setClassName(value == null ? null : (String) value);
return true;
case "method_name":
data.setMethodName(value == null ? null : (String) value);
return true;
case "line":
data.setLine((int) value);
return true;
case "log":
data.setLog(value == null ? null : (String) value);
return true;
case "comments":
data.setComments(value == null ? null : (String) value);
return true;
case "callers":
data.setCallers(value == null ? null : (String) value);
return true;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return false;
}
public static Object getValue(MyBoxLog data, String column) {
if (data == null || column == null) {
return null;
}
switch (column) {
case "mblid":
return data.getMblid();
case "time":
return data.getTime();
case "log_type":
return logType(data.getLogType());
case "file_name":
return data.getFileName();
case "class_name":
return data.getClassName();
case "method_name":
return data.getMethodName();
case "line":
return data.getLine();
case "log":
return data.getLog();
case "comments":
return data.getComments();
case "callers":
return data.getCallers();
}
return null;
}
public static boolean valid(MyBoxLog data) {
return data != null
&& data.getTime() != null && data.getLog() != null && data.getLogType() != null;
}
public static String displayColumn(MyBoxLog data, ColumnDefinition column, Object value) {
if (data == null || column == null || value == null) {
return null;
}
if ("log_type".equals(column.getColumnName())) {
return Languages.message(data.getLogType().name());
}
return column.formatValue(value);
}
public static short logType(LogType logType) {
if (logType == null) {
return (short) LogType.Info.ordinal();
}
return (short) logType.ordinal();
}
public static LogType logType(short logType) {
try {
return LogType.values()[logType];
} catch (Exception e) {
return LogType.Info;
}
}
public static MyBoxLog console(Object log) {
return log(LogType.Console, log, null);
}
public static MyBoxLog console(Object log, String comments) {
return log(LogType.Console, log, comments);
}
public static MyBoxLog debug(Object log) {
return log(LogType.Debug, log, null);
}
public static MyBoxLog debug(Object log, String comments) {
return log(LogType.Debug, log, comments);
}
public static MyBoxLog error(Object log) {
return log(LogType.Error, log, null);
}
public static MyBoxLog error(Object log, String comments) {
return log(LogType.Error, log, comments);
}
public static MyBoxLog info(Object log) {
return log(LogType.Info, log, null);
}
public static MyBoxLog info(Object log, String comments) {
return log(LogType.Info, log, comments);
}
public static boolean isFlooding() {
return new Date().getTime() - LastRecordTime < MinInterval;
}
private static MyBoxLog log(LogType type, Object log, String comments) {
try {
if (type == null) {
return null;
}
// if (isFlooding()) {
// return null;
// }
String logString = log == null ? "null" : log.toString();
if (logString.contains("java.sql.SQLException: No suitable driver found")
|| logString.contains("java.sql.SQLNonTransientConnectionException")) {
if (AppVariables.ignoreDbUnavailable) {
return null;
}
AppVariables.ignoreDbUnavailable = true; // Record only once
}
StackTraceElement[] stacks = new Throwable().getStackTrace();
if (stacks.length <= 2) {
return null;
}
StackTraceElement stack = stacks[2];
boolean isMylog = stack.getClassName().contains("MyBoxLog");
String callers = null;
for (int i = 3; i < stacks.length; ++i) {
StackTraceElement s = stacks[i];
if (s.getClassName().startsWith("mara.mybox")) {
if (callers != null) {
callers += "\n";
} else {
callers = "";
}
callers += s.getFileName() + " " + s.getClassName()
+ " " + s.getMethodName() + " " + s.getLineNumber();
if (s.getClassName().contains("MyBoxLog")) {
isMylog = true;
}
}
}
MyBoxLog myboxLog = MyBoxLog.create()
.setLogType(type)
.setLog(logString)
.setComments(comments)
.setFileName(stack.getFileName())
.setClassName(stack.getClassName())
.setMethodName(stack.getMethodName())
.setLine(stack.getLineNumber())
.setCallers(callers);
String logText = println(myboxLog,
type == LogType.Error
|| (AppVariables.detailedDebugLogs && type == LogType.Debug));
System.out.print(logText);
if (LastMyBoxLog != null && LastMyBoxLog.equalTo(myboxLog)) {
return myboxLog;
}
if (logString.contains("java.sql.SQLNonTransientConnectionException")) {
type = LogType.Debug;
}
if (AppVariables.popErrorLogs && type == LogType.Error) {
Platform.runLater(() -> {
MyBoxLogViewerController controller = MyBoxLogViewerController.oneOpen();
if (controller != null) {
controller.addLog(myboxLog);
}
});
}
boolean notSave = isMylog || type == LogType.Console
|| (type == LogType.Debug && !AppVariables.saveDebugLogs);
if (!notSave) {
new TableMyBoxLog().writeData(myboxLog);
}
if (type == LogType.Error && AppVariables.autoTestingController != null) {
AppVariables.autoTestingController.errorHappened();
}
LastMyBoxLog = myboxLog;
LastRecordTime = new Date().getTime();
return myboxLog;
} catch (Exception e) {
return null;
}
}
public static String print(MyBoxLog log, boolean printCallers) {
return print(log, " ", printCallers);
}
public static String println(MyBoxLog log, boolean printCallers) {
return println(log, " ", printCallers);
}
public static String println(MyBoxLog log, String separator, boolean printCallers) {
return print(log, separator, printCallers) + "\n";
}
public static String print(MyBoxLog log, String separator, boolean printCallers) {
if (log == null) {
return "";
}
String s = DateTools.datetimeToString(log.getTime())
+ (log.getLogType() != null && log.getLogType() != LogType.Console ? separator + log.getLogType() : "")
+ (log.getFileName() != null ? separator + log.getFileName() : "")
+ (log.getClassName() != null ? separator + log.getClassName() : "")
+ (log.getMethodName() != null ? separator + log.getMethodName() : "")
+ (log.getLine() >= 0 ? separator + log.getLine() : "")
+ (log.getLog() != null ? separator + log.getLog() : "null")
+ (log.getComments() != null ? separator + log.getComments() : "");
if (printCallers && log.getCallers() != null && !log.getCallers().isBlank()) {
String[] array = log.getCallers().split("\n");
for (String a : array) {
s += "\n\t\t\t\t" + a;
}
}
return s;
}
/*
set/get
*/
public Date getTime() {
return time;
}
public MyBoxLog setTime(Date time) {
this.time = time;
return this;
}
public String getLog() {
return log;
}
public MyBoxLog setLog(String log) {
this.log = log;
return this;
}
public LogType getLogType() {
return logType;
}
public MyBoxLog setLogType(LogType logType) {
this.logType = logType;
return this;
}
public String getClassName() {
return className;
}
public MyBoxLog setClassName(String className) {
this.className = className;
return this;
}
public String getMethodName() {
return methodName;
}
public MyBoxLog setMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public long getMblid() {
return mblid;
}
public MyBoxLog setMblid(long mblid) {
this.mblid = mblid;
return this;
}
public String getComments() {
return comments;
}
public MyBoxLog setComments(String comments) {
this.comments = comments;
return this;
}
public int getLine() {
return line;
}
public MyBoxLog setLine(int line) {
this.line = line;
return this;
}
public String getFileName() {
return fileName;
}
public MyBoxLog setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public String getCallers() {
return callers;
}
public MyBoxLog setCallers(String callers) {
this.callers = callers;
return this;
}
public String getTypeName() {
if (logType != null) {
typeName = Languages.message(logType.name());
}
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
| 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/dev/BaseMacro.java | alpha/MyBox/src/main/java/mara/mybox/dev/BaseMacro.java | package mara.mybox.dev;
import java.io.File;
import java.util.LinkedHashMap;
import mara.mybox.controller.BaseTaskController;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class BaseMacro {
public static final String ParameterPrefix = "MacroPara_";
protected String script;
protected LinkedHashMap<String, String> arguments; // values defined in macro
protected LinkedHashMap<String, Object> parameters; // values referred when run
protected BaseTaskController controller;
protected boolean defaultOpenResult, ok;
protected FxTask<Void> task;
/*
build macro
*/
public BaseMacro() {
init();
}
public BaseMacro(boolean openResult) {
init();
this.defaultOpenResult = openResult;
}
public final void init() {
script = null;
arguments = null;
reset();
}
public void reset() {
parameters = null;
controller = null;
task = null;
ok = false;
defaultOpenResult = false;
}
public void copyTo(BaseMacro macro) {
if (macro == null) {
return;
}
macro.setScript(script);
macro.setArguments(arguments);
macro.setParameters(parameters);
macro.setController(controller);
macro.setTask(task);
macro.setOk(ok);
macro.setDefaultOpenResult(defaultOpenResult);
}
public void copyFrom(BaseMacro macro) {
if (macro == null) {
return;
}
script = macro.getScript();
arguments = macro.getArguments();
parameters = macro.getParameters();
controller = macro.getController();
task = macro.getTask();
ok = macro.isOk();
defaultOpenResult = macro.isDefaultOpenResult();
}
public void info() {
if (arguments == null) {
return;
}
MyBoxLog.console(arguments);
}
public BaseMacro make(String inScript) {
try {
parseString(inScript);
String func = pickFunction();
if (func == null) {
return null;
}
func = func.toLowerCase();
switch (func) {
case "image":
ImageMacro imageMacro = new ImageMacro();
imageMacro.copyFrom(this);
return imageMacro;
case "pdf":
PdfMacro pdfMacro = new PdfMacro();
pdfMacro.copyFrom(this);
return pdfMacro;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
// helped with deepseek
public boolean parseString(String inScript) {
try {
script = inScript;
if (script == null || script.isBlank()) {
return false;
}
boolean inDoubleQuotes = false;
boolean inSingleQuotes = false;
StringBuilder currentToken = new StringBuilder();
for (int i = 0; i < script.length(); i++) {
char c = script.charAt(i);
if (c == '"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
currentToken.append(c);
continue;
} else if (c == '\'' && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
currentToken.append(c);
continue;
}
if (c == ' ' && !inDoubleQuotes && !inSingleQuotes) {
if (currentToken.length() > 0) {
processToken(currentToken.toString());
currentToken.setLength(0);
}
continue;
}
currentToken.append(c);
}
if (currentToken.length() > 0) {
processToken(currentToken.toString());
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
private void processToken(String token) {
if (token.contains("=")) {
int equalsIndex = token.indexOf('=');
String key = token.substring(0, equalsIndex);
String value = token.substring(equalsIndex + 1);
value = removeQuotes(value);
writeArgument(key, value);
} else {
String value = removeQuotes(token);
writeArgument(ParameterPrefix + (arguments != null ? arguments.size() + 1 : 1), value);
}
}
private static String removeQuotes(String str) {
if ((str.startsWith("\"") && str.endsWith("\""))
|| (str.startsWith("'") && str.endsWith("'"))) {
return str.substring(1, str.length() - 1);
}
return str;
}
public boolean parseArray(String[] args) {
try {
if (args == null) {
return false;
}
for (String arg : args) {
processToken(arg);
if (script == null) {
script = arg;
} else {
script += " " + arg;
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
/*
arguments: values defined in macro
*/
// key is case-insensitive
public void writeArgument(String key, String value) {
if (key == null) {
return;
}
if (arguments == null) {
arguments = new LinkedHashMap<>();
}
arguments.put(key.toLowerCase(), value);
}
// key is case-insensitive
public String readArgument(String key) {
if (key == null || arguments == null) {
return null;
}
return arguments.get(key.toLowerCase());
}
public int readIntArgument(String key) {
try {
return Integer.parseInt(readArgument(key));
} catch (Exception e) {
return AppValues.InvalidInteger;
}
}
public short readShortArgument(String key) {
try {
return Short.parseShort(readArgument(key));
} catch (Exception e) {
return AppValues.InvalidShort;
}
}
public boolean readBooleanArgument(String key) {
try {
return StringTools.isTrue(readArgument(key));
} catch (Exception e) {
return false;
}
}
/*
parameters: values referred when run
*/
// key is case-insensitive
public void writeParameter(String key, Object value) {
if (key == null) {
return;
}
if (parameters == null) {
parameters = new LinkedHashMap<>();
}
if (value != null) {
parameters.put(key.toLowerCase(), value);
} else {
parameters.remove(key);
}
}
// key is case-insensitive
public Object readParameter(String key) {
if (key == null || parameters == null) {
return null;
}
return parameters.get(key.toLowerCase());
}
public String pickFunction() {
try {
String func = readArgument(ParameterPrefix + "1");
writeParameter("function", func);
return func;
} catch (Exception e) {
return null;
}
}
public String pickOperation() {
try {
String op = defaultOperation();
String v = readArgument(ParameterPrefix + "2");
if (v != null) {
op = v;
}
writeParameter("operation", op);
return op;
} catch (Exception e) {
return null;
}
}
public File pickInputFile() {
try {
File file = defaultInputFile();
String v = readArgument("inputFile");
if (v != null) {
File fv = new File(v);
if (fv.exists()) {
file = fv;
}
}
writeParameter("inputFile", file);
return file;
} catch (Exception e) {
return null;
}
}
public File pickOutputFile() {
try {
File file = defaultOutputFile();
String v = readArgument("outputFile");
if (v != null) {
file = new File(v);
}
writeParameter("outputFile", file);
return file;
} catch (Exception e) {
return null;
}
}
public boolean pickOpenResult() {
try {
boolean bv = defaultOpenResult;
String v = readArgument("openResult");
if (v != null) {
bv = StringTools.isTrue(v);
}
writeParameter("openResult", bv);
return bv;
} catch (Exception e) {
return false;
}
}
public String defaultOperation() {
return null;
}
public File defaultInputFile() {
return null;
}
public File defaultOutputFile() {
return null;
}
public String getFunction() {
try {
return (String) readParameter("function");
} catch (Exception e) {
return null;
}
}
public String getOperation() {
try {
return (String) readParameter("operation");
} catch (Exception e) {
return null;
}
}
public File getInputFile() {
try {
return (File) readParameter("inputFile");
} catch (Exception e) {
return null;
}
}
public File getOutputFile() {
try {
return (File) readParameter("outputFile");
} catch (Exception e) {
return null;
}
}
public boolean isOpenResult() {
try {
return (boolean) readParameter("openResult");
} catch (Exception e) {
}
return defaultOpenResult;
}
/*
run
*/
public boolean checkParameters() {
try {
parameters = null;
String function = pickFunction();
if (function == null) {
displayError(message("Invalid" + ": function"));
return false;
}
String operation = pickOperation();
if (operation == null) {
displayError(message("Invalid" + ": operation"));
return false;
}
pickInputFile();
pickOutputFile();
if (!checkMoreParameters()) {
return false;
}
pickOpenResult();
String command = "";
for (String key : parameters.keySet()) {
if ("inputFile".equalsIgnoreCase(key) || "outputFile".equalsIgnoreCase(key)) {
continue;
}
Object v = readParameter(key);
if (v == null) {
continue;
}
String s = v.toString();
if (s.contains(" ")) {
s = "\"" + s + "\"";
}
if (!command.isBlank()) {
command += " ";
}
command += key + "=" + s;
}
File inputFile = getInputFile();
if (inputFile != null) {
command += " inputFile=\"" + inputFile.getAbsolutePath() + "\"";
}
File outputFile = getOutputFile();
if (outputFile != null) {
command += " outputFile=\"" + outputFile.getAbsolutePath() + "\"";
}
displayInfo(message("Parameters") + ": " + command);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkMoreParameters() {
return true;
}
public boolean run() {
return false;
}
public void displayResult() {
displayEnd();
if (isOpenResult()) {
openResult();
}
}
public void displayEnd() {
try {
if (ok) {
displayInfo(message("Completed"));
} else {
displayInfo(message("Failed"));
}
File outputFile = getOutputFile();
if (outputFile != null && outputFile.exists()) {
displayInfo(message("FileGenerated") + ": " + outputFile);
}
} catch (Exception e) {
displayError(e.toString());
}
}
public void openResult() {
}
public void displayError(String info) {
display(info, true);
}
public void displayInfo(String info) {
display(info, false);
}
public void display(String info, boolean isError) {
if (controller != null) {
controller.showLogs(info);
} else if (task != null) {
task.setInfo(info);
} else if (isError) {
MyBoxLog.error(info);
} else {
MyBoxLog.console(info);
}
}
/*
static
*/
public static BaseMacro create() {
return new BaseMacro();
}
public static BaseMacro create(String inScript, boolean openResult) {
BaseMacro macro = new BaseMacro(openResult);
return macro.make(inScript);
}
public static BaseMacro create(String[] args) {
BaseMacro macro = new BaseMacro();
macro.parseArray(args);
return macro.make(macro.getScript());
}
/*
get/set
*/
public LinkedHashMap<String, String> getArguments() {
return arguments;
}
public BaseMacro setArguments(LinkedHashMap<String, String> arguments) {
this.arguments = arguments;
return this;
}
public LinkedHashMap<String, Object> getParameters() {
return parameters;
}
public BaseMacro setParameters(LinkedHashMap<String, Object> parameters) {
this.parameters = parameters;
return this;
}
public String getScript() {
return script;
}
public BaseMacro setScript(String script) {
this.script = script;
return this;
}
public boolean isDefaultOpenResult() {
return defaultOpenResult;
}
public BaseMacro setDefaultOpenResult(boolean defaultOpenResult) {
this.defaultOpenResult = defaultOpenResult;
return this;
}
public BaseTaskController getController() {
return controller;
}
public BaseMacro setController(BaseTaskController controller) {
this.controller = controller;
return this;
}
public boolean isOk() {
return ok;
}
public BaseMacro setOk(boolean ok) {
this.ok = ok;
return this;
}
public FxTask<Void> getTask() {
return task;
}
public BaseMacro setTask(FxTask<Void> 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/dev/PdfMacro.java | alpha/MyBox/src/main/java/mara/mybox/dev/PdfMacro.java | package mara.mybox.dev;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class PdfMacro extends BaseMacro {
@Override
public boolean run() {
try {
} catch (Exception e) {
MyBoxLog.error(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/dev/DevTools.java | alpha/MyBox/src/main/java/mara/mybox/dev/DevTools.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mara.mybox.dev;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mara.mybox.db.table.TableStringValues;
/**
*
* @author mara
*/
public class DevTools {
public static List<Integer> installedVersion(Connection conn) {
List<Integer> versions = new ArrayList<>();
try {
List<String> installed = TableStringValues.read(conn, "InstalledVersions");
for (String v : installed) {
versions.add(myboxVersion(v));
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return versions;
}
public static int lastVersion(Connection conn) {
try {
List<Integer> versions = installedVersion(conn);
if (!versions.isEmpty()) {
Collections.sort(versions);
return versions.get(versions.size() - 1);
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return 0;
}
public static int myboxVersion(String string) {
try {
String[] vs = string.split("\\.");
switch (vs.length) {
case 1:
return Integer.parseInt(vs[0]) * 1000000;
case 2:
return Integer.parseInt(vs[0]) * 1000000 + Integer.parseInt(vs[1]) * 1000;
case 3:
return Integer.parseInt(vs[0]) * 1000000 + Integer.parseInt(vs[1]) * 1000 + Integer.parseInt(vs[2]);
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return 0;
}
public static String myboxVersion(int i) {
try {
int v1 = i / 1000000;
int ii = i % 1000000;
int v2 = ii / 1000;
int v3 = ii % 1000;
if (v3 == 0) {
return v1 + "." + v2;
} else {
return v1 + "." + v2 + "." + v3;
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return i + "";
}
public static String getFileName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getFileName();
}
public static String getMethodName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getMethodName();
}
public static String getClassName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getClassName();
}
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getLineNumber();
}
}
| 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/dev/TestCase.java | alpha/MyBox/src/main/java/mara/mybox/dev/TestCase.java | package mara.mybox.dev;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.value.AppValues;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-5
* @License Apache License Version 2.0
*/
public class TestCase {
protected int id;
protected String object, version, fxml;
protected Operation operation;
protected Type type;
protected Stage stage;
protected Status Status;
protected BaseController controller;
public static enum Type {
Function, UserInterface, Bundary, Data, API, IO, Exception, Performance, Robustness,
Usability, Compatibility, Security, Document
}
public static enum Operation {
Handle, OpenInterface, ClickButton, OpenFile, Edit
}
public static enum Stage {
Alpha, Unit, Integration, Verification, Beta
}
public static enum Status {
NotTested, Testing, Success, Fail
}
public TestCase() {
init();
}
public TestCase(int id, String object, String fxml) {
init();
this.id = id;
this.object = object;
this.fxml = fxml;
}
private void init() {
type = Type.UserInterface;
operation = Operation.OpenInterface;
version = AppValues.AppVersion;
stage = Stage.Alpha;
Status = Status.NotTested;
}
/*
static
*/
public static List<TestCase> testCases() {
List<TestCase> cases = new ArrayList<>();
try {
int index = 1;
cases.add(new TestCase(index++, message("TextTree"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("HtmlTree"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("PdfView"), Fxmls.PdfViewFxml));
cases.add(new TestCase(index++, message("PdfConvertImagesBatch"), Fxmls.PdfConvertImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfImagesConvertBatch"), Fxmls.PdfImagesConvertBatchFxml));
cases.add(new TestCase(index++, message("PdfCompressImagesBatch"), Fxmls.PdfCompressImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfConvertHtmlsBatch"), Fxmls.PdfConvertHtmlsBatchFxml));
cases.add(new TestCase(index++, message("PdfExtractImagesBatch"), Fxmls.PdfExtractImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfExtractTextsBatch"), Fxmls.PdfExtractTextsBatchFxml));
cases.add(new TestCase(index++, message("PdfOCRBatch"), Fxmls.PdfOCRBatchFxml));
cases.add(new TestCase(index++, message("PdfSplitBatch"), Fxmls.PdfSplitBatchFxml));
cases.add(new TestCase(index++, message("MergePdf"), Fxmls.PdfMergeFxml));
cases.add(new TestCase(index++, message("PDFAttributes"), Fxmls.PdfAttributesFxml));
cases.add(new TestCase(index++, message("PDFAttributesBatch"), Fxmls.PdfAttributesBatchFxml));
cases.add(new TestCase(index++, message("MarkdownEditer"), Fxmls.MarkdownEditorFxml));
cases.add(new TestCase(index++, message("MarkdownToHtml"), Fxmls.MarkdownToHtmlFxml));
cases.add(new TestCase(index++, message("MarkdownToText"), Fxmls.MarkdownToTextFxml));
cases.add(new TestCase(index++, message("MarkdownToPdf"), Fxmls.MarkdownToPdfFxml));
cases.add(new TestCase(index++, message("HtmlEditor"), Fxmls.HtmlEditorFxml));
cases.add(new TestCase(index++, message("WebFind"), Fxmls.HtmlFindFxml));
cases.add(new TestCase(index++, message("WebElements"), Fxmls.HtmlElementsFxml));
cases.add(new TestCase(index++, message("HtmlSnap"), Fxmls.HtmlSnapFxml));
cases.add(new TestCase(index++, message("HtmlExtractTables"), Fxmls.HtmlExtractTablesFxml));
cases.add(new TestCase(index++, message("HtmlToMarkdown"), Fxmls.HtmlToMarkdownFxml));
cases.add(new TestCase(index++, message("HtmlToText"), Fxmls.HtmlToTextFxml));
cases.add(new TestCase(index++, message("HtmlToPdf"), Fxmls.HtmlToPdfFxml));
cases.add(new TestCase(index++, message("HtmlSetCharset"), Fxmls.HtmlSetCharsetFxml));
cases.add(new TestCase(index++, message("HtmlSetStyle"), Fxmls.HtmlSetStyleFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsHtml"), Fxmls.HtmlMergeAsHtmlFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsMarkdown"), Fxmls.HtmlMergeAsMarkdownFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsPDF"), Fxmls.HtmlMergeAsPDFFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsText"), Fxmls.HtmlMergeAsTextFxml));
cases.add(new TestCase(index++, message("HtmlFrameset"), Fxmls.HtmlFramesetFxml));
cases.add(new TestCase(index++, message("TextEditer"), Fxmls.TextEditorFxml));
cases.add(new TestCase(index++, message("TextConvertSplit"), Fxmls.TextFilesConvertFxml));
cases.add(new TestCase(index++, message("TextFilesMerge"), Fxmls.TextFilesMergeFxml));
cases.add(new TestCase(index++, message("TextReplaceBatch"), Fxmls.TextReplaceBatchFxml));
cases.add(new TestCase(index++, message("TextFilterBatch"), Fxmls.TextFilterBatchFxml));
cases.add(new TestCase(index++, message("TextToHtml"), Fxmls.TextToHtmlFxml));
cases.add(new TestCase(index++, message("TextToPdf"), Fxmls.TextToPdfFxml));
cases.add(new TestCase(index++, message("WordView"), Fxmls.WordViewFxml));
cases.add(new TestCase(index++, message("WordToHtml"), Fxmls.WordToHtmlFxml));
cases.add(new TestCase(index++, message("WordToPdf"), Fxmls.WordToPdfFxml));
cases.add(new TestCase(index++, message("PptView"), Fxmls.PptViewFxml));
cases.add(new TestCase(index++, message("PptToImages"), Fxmls.PptToImagesFxml));
cases.add(new TestCase(index++, message("PptToPdf"), Fxmls.PptToPdfFxml));
cases.add(new TestCase(index++, message("PptExtract"), Fxmls.PptExtractFxml));
cases.add(new TestCase(index++, message("PptSplit"), Fxmls.PptSplitFxml));
cases.add(new TestCase(index++, message("PptxMerge"), Fxmls.PptxMergeFxml));
cases.add(new TestCase(index++, message("ExtractTextsFromMS"), Fxmls.ExtractTextsFromMSFxml));
cases.add(new TestCase(index++, message("BytesEditer"), Fxmls.BytesEditorFxml));
cases.add(new TestCase(index++, message("TextInMyBoxClipboard"), Fxmls.TextInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("TextInSystemClipboard"), Fxmls.TextInSystemClipboardFxml));
cases.add(new TestCase(index++, message("ImagesBrowser"), Fxmls.ImagesBrowserFxml));
cases.add(new TestCase(index++, message("ImageAnalyse"), Fxmls.ImageAnalyseFxml));
cases.add(new TestCase(index++, message("ImagesPlay"), Fxmls.ImagesPlayFxml));
cases.add(new TestCase(index++, message("ImageEditor"), Fxmls.ImageEditorFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Size"), Fxmls.ImageSizeBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Crop"), Fxmls.ImageCropBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Paste"), Fxmls.ImagePasteBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("AdjustColor"), Fxmls.ImageAdjustColorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("ReplaceColor"), Fxmls.ImageReplaceColorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("ReduceColors"), Fxmls.ImageReduceColorsBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("EdgeDetection"), Fxmls.ImageEdgeBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Sharpen"), Fxmls.ImageSharpenBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Smooth"), Fxmls.ImageSmoothBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Text"), Fxmls.ImageTextBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Round"), Fxmls.ImageRoundBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Shadow"), Fxmls.ImageShadowBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Mirror"), Fxmls.ImageMirrorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Shear"), Fxmls.ImageShearBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Rotate"), Fxmls.ImageRotateBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Margins"), Fxmls.ImageMarginsBatchFxml));
cases.add(new TestCase(index++, message("ImagesSplice"), Fxmls.ImagesSpliceFxml));
cases.add(new TestCase(index++, message("ImageAlphaAdd"), Fxmls.ImageAlphaAddBatchFxml));
cases.add(new TestCase(index++, message("ImageSplit"), Fxmls.ImageSplitFxml));
cases.add(new TestCase(index++, message("ImageSample"), Fxmls.ImageSampleFxml));
cases.add(new TestCase(index++, message("ImageAlphaExtract"), Fxmls.ImageAlphaExtractBatchFxml));
cases.add(new TestCase(index++, message("ImageConverterBatch"), Fxmls.ImageConverterBatchFxml));
cases.add(new TestCase(index++, message("ImageOCR"), Fxmls.ImageOCRFxml));
cases.add(new TestCase(index++, message("ImageOCRBatch"), Fxmls.ImageOCRBatchFxml));
cases.add(new TestCase(index++, message("ManageColors"), Fxmls.ColorsManageFxml));
cases.add(new TestCase(index++, message("QueryColor"), Fxmls.ColorQueryFxml));
cases.add(new TestCase(index++, message("ImageScope"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DrawChromaticityDiagram"), Fxmls.ChromaticityDiagramFxml));
cases.add(new TestCase(index++, message("IccProfileEditor"), Fxmls.IccProfileEditorFxml));
cases.add(new TestCase(index++, message("RGBColorSpaces"), Fxmls.RGBColorSpacesFxml));
cases.add(new TestCase(index++, message("LinearRGB2XYZMatrix"), Fxmls.RGB2XYZConversionMatrixFxml));
cases.add(new TestCase(index++, message("LinearRGB2RGBMatrix"), Fxmls.RGB2RGBConversionMatrixFxml));
cases.add(new TestCase(index++, message("Illuminants"), Fxmls.IlluminantsFxml));
cases.add(new TestCase(index++, message("ChromaticAdaptationMatrix"), Fxmls.ChromaticAdaptationMatrixFxml));
cases.add(new TestCase(index++, message("ImagesInMyBoxClipboard"), Fxmls.ImageInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("ImagesInSystemClipboard"), Fxmls.ImageInSystemClipboardFxml));
cases.add(new TestCase(index++, message("ConvolutionKernelManager"), Fxmls.ConvolutionKernelManagerFxml));
cases.add(new TestCase(index++, message("PixelsCalculator"), Fxmls.PixelsCalculatorFxml));
cases.add(new TestCase(index++, message("ImageBase64"), Fxmls.ImageBase64Fxml));
cases.add(new TestCase(index++, message("DataManufacture"), Fxmls.Data2DManufactureFxml));
cases.add(new TestCase(index++, message("ManageData"), Fxmls.Data2DManageFxml));
cases.add(new TestCase(index++, message("CsvConvert"), Fxmls.DataFileCSVConvertFxml));
cases.add(new TestCase(index++, message("CsvMerge"), Fxmls.DataFileCSVMergeFxml));
cases.add(new TestCase(index++, message("ExcelConvert"), Fxmls.DataFileExcelConvertFxml));
cases.add(new TestCase(index++, message("ExcelMerge"), Fxmls.DataFileExcelMergeFxml));
cases.add(new TestCase(index++, message("TextDataConvert"), Fxmls.DataFileTextConvertFxml));
cases.add(new TestCase(index++, message("TextDataMerge"), Fxmls.DataFileTextMergeFxml));
cases.add(new TestCase(index++, message("DataInSystemClipboard"), Fxmls.DataInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("DataInMyBoxClipboard"), Fxmls.DataInSystemClipboardFxml));
cases.add(new TestCase(index++, message("MatricesManage"), Fxmls.MatricesManageFxml));
cases.add(new TestCase(index++, message("MatrixUnaryCalculation"), Fxmls.MatrixUnaryCalculationFxml));
cases.add(new TestCase(index++, message("MatricesBinaryCalculation"), Fxmls.MatricesBinaryCalculationFxml));
cases.add(new TestCase(index++, message("DatabaseTable"), Fxmls.DataTablesFxml));
cases.add(new TestCase(index++, message("RowExpression"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DataColumn"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DatabaseSQL"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("MathFunction"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JShell"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JEXL"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JavaScript"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("GeographyCode"), Fxmls.GeographyCodeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("ConvertCoordinate"), Fxmls.ConvertCoordinateFxml));
cases.add(new TestCase(index++, message("BarcodeCreator"), Fxmls.BarcodeCreatorFxml));
cases.add(new TestCase(index++, message("BarcodeDecoder"), Fxmls.BarcodeDecoderFxml));
cases.add(new TestCase(index++, message("MessageDigest"), Fxmls.MessageDigestFxml));
cases.add(new TestCase(index++, message("Base64Conversion"), Fxmls.Base64Fxml));
cases.add(new TestCase(index++, message("TTC2TTF"), Fxmls.FileTTC2TTFFxml));
cases.add(new TestCase(index++, message("FilesArrangement"), Fxmls.FilesArrangementFxml));
cases.add(new TestCase(index++, message("DirectorySynchronize"), Fxmls.DirectorySynchronizeFxml));
cases.add(new TestCase(index++, message("FileCut"), Fxmls.FileCutFxml));
cases.add(new TestCase(index++, message("FilesMerge"), Fxmls.FilesMergeFxml));
cases.add(new TestCase(index++, message("FilesFind"), Fxmls.FilesFindFxml));
cases.add(new TestCase(index++, message("FilesRedundancy"), Fxmls.FilesRedundancyFxml));
cases.add(new TestCase(index++, message("FilesCompare"), Fxmls.FilesCompareFxml));
cases.add(new TestCase(index++, message("FilesRename"), Fxmls.FilesRenameFxml));
cases.add(new TestCase(index++, message("FilesCopy"), Fxmls.FilesCopyFxml));
cases.add(new TestCase(index++, message("FilesMove"), Fxmls.FilesMoveFxml));
cases.add(new TestCase(index++, message("DeleteJavaIOTemporaryPathFiles"), Fxmls.FilesDeleteJavaTempFxml));
cases.add(new TestCase(index++, message("DeleteEmptyDirectories"), Fxmls.FilesDeleteEmptyDirFxml));
cases.add(new TestCase(index++, message("FilesDelete"), Fxmls.FilesDeleteFxml));
cases.add(new TestCase(index++, message("DeleteNestedDirectories"), Fxmls.FilesDeleteNestedDirFxml));
cases.add(new TestCase(index++, message("FileDecompressUnarchive"), Fxmls.FileDecompressUnarchiveFxml));
cases.add(new TestCase(index++, message("FilesDecompressUnarchiveBatch"), Fxmls.FilesDecompressUnarchiveBatchFxml));
cases.add(new TestCase(index++, message("FilesArchiveCompress"), Fxmls.FilesArchiveCompressFxml));
cases.add(new TestCase(index++, message("FilesCompressBatch"), Fxmls.FilesCompressBatchFxml));
cases.add(new TestCase(index++, message("MediaPlayer"), Fxmls.MediaPlayerFxml));
cases.add(new TestCase(index++, message("ManageMediaLists"), Fxmls.MediaListFxml));
cases.add(new TestCase(index++, message("FFmpegScreenRecorder"), Fxmls.FFmpegScreenRecorderFxml));
cases.add(new TestCase(index++, message("FFmpegConvertMediaStreams"), Fxmls.FFmpegConvertMediaStreamsFxml));
cases.add(new TestCase(index++, message("FFmpegConvertMediaFiles"), Fxmls.FFmpegConvertMediaFilesFxml));
cases.add(new TestCase(index++, message("FFmpegMergeImagesInformation"), Fxmls.FFmpegMergeImagesFxml));
cases.add(new TestCase(index++, message("FFmpegMergeImagesFiles"), Fxmls.FFmpegMergeImageFilesFxml));
cases.add(new TestCase(index++, message("FFmpegProbeMediaInformation"), Fxmls.FFmpegProbeMediaInformationFxml));
cases.add(new TestCase(index++, message("FFmpegInformation"), Fxmls.FFmpegInformationFxml));
cases.add(new TestCase(index++, message("AlarmClock"), Fxmls.AlarmClockFxml));
cases.add(new TestCase(index++, message("GameElimniation"), Fxmls.GameElimniationFxml));
cases.add(new TestCase(index++, message("GameMine"), Fxmls.GameMineFxml));
cases.add(new TestCase(index++, message("WebBrowser"), Fxmls.WebBrowserFxml));
cases.add(new TestCase(index++, message("WebFavorite"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("WebHistories"), Fxmls.WebHistoriesFxml));
cases.add(new TestCase(index++, message("QueryNetworkAddress"), Fxmls.NetworkQueryAddressFxml));
cases.add(new TestCase(index++, message("QueryDNSBatch"), Fxmls.NetworkQueryDNSBatchFxml));
cases.add(new TestCase(index++, message("ConvertUrl"), Fxmls.NetworkConvertUrlFxml));
cases.add(new TestCase(index++, message("DownloadHtmls"), Fxmls.DownloadFirstLevelLinksFxml));
cases.add(new TestCase(index++, message("SecurityCertificates"), Fxmls.SecurityCertificatesFxml));
cases.add(new TestCase(index++, message("Settings"), Fxmls.SettingsFxml));
cases.add(new TestCase(index++, message("MyBoxProperties"), Fxmls.MyBoxPropertiesFxml));
cases.add(new TestCase(index++, message("MyBoxLogs"), Fxmls.MyBoxLogsFxml));
cases.add(new TestCase(index++, message("MacroCommands"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("RunSystemCommand"), Fxmls.RunSystemCommandFxml));
cases.add(new TestCase(index++, message("ManageLanguages"), Fxmls.MyBoxLanguagesFxml));
cases.add(new TestCase(index++, message("MakeIcons"), Fxmls.MyBoxIconsFxml));
cases.add(new TestCase(index++, message("AutoTesting"), Fxmls.AutoTestingCasesFxml));
cases.add(new TestCase(index++, message("MessageAuthor"), Fxmls.MessageAuthorFxml));
cases.add(new TestCase(index++, message("Shortcuts"), Fxmls.ShortcutsFxml));
cases.add(new TestCase(index++, message("FunctionsList"), Fxmls.FunctionsListFxml));
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return cases;
}
/*
get/set
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Operation getOperation() {
return operation;
}
public String getOperationName() {
return message(operation.name());
}
public void setOperation(Operation operation) {
this.operation = operation;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Type getType() {
return type;
}
public String getTypeName() {
return message(type.name());
}
public TestCase setType(Type type) {
this.type = type;
return this;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public Status getStatus() {
return Status;
}
public String getStatusName() {
return message(Status.name());
}
public void setStatus(Status Status) {
this.Status = Status;
}
public BaseController getController() {
return controller;
}
public void setController(BaseController controller) {
this.controller = controller;
}
public String getFxml() {
return fxml;
}
public void setFxml(String fxml) {
this.fxml = fxml;
}
}
| 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/dev/ImageMacro.java | alpha/MyBox/src/main/java/mara/mybox/dev/ImageMacro.java | package mara.mybox.dev;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javax.imageio.ImageIO;
import mara.mybox.color.ColorMatch;
import mara.mybox.color.ColorMatch.MatchAlgorithm;
import mara.mybox.controller.ImageEditorController;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.image.data.ImageConvolution;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.StringTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class ImageMacro extends BaseMacro {
protected BufferedImage sourceImage;
protected BufferedImage resultImage;
protected PixelsOperation pixelsOperation;
protected ImageConvolution convolution;
protected ConvolutionKernel kernel;
@Override
public void reset() {
super.reset();
sourceImage = null;
resultImage = null;
pixelsOperation = null;
}
@Override
public String defaultOperation() {
return "edit";
}
@Override
public File defaultInputFile() {
return FxFileTools.getInternalFile("/img/MyBox.png", "image", "MyBox.png");
}
@Override
public File defaultOutputFile() {
return FileTmpTools.tmpFile("macro", "jpg");
}
/*
parameters
*/
@Override
public boolean checkMoreParameters() {
try {
File inputFile = getInputFile();
if (inputFile == null || !inputFile.exists()) {
displayError(message("Invalid" + ": inputFile") + (inputFile != null ? ("\n" + inputFile.getAbsolutePath()) : ""));
return false;
}
String operation = getOperation();
switch (operation.toLowerCase()) {
case "edit":
ok = checkEdit();
break;
case "replace":
ok = checkReplace();
break;
case "sharp":
ok = checkSharp();
break;
}
if (!ok) {
return false;
}
sourceImage = ImageIO.read(inputFile);
return sourceImage != null;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkEdit() {
try {
File inputFile = getInputFile();
writeParameter("outputFile", inputFile);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkReplace() {
try {
ImageScope scope = new ImageScope();
ColorMatch colorMatch = scope.getColorMatch();
pixelsOperation = PixelsOperationFactory.create(sourceImage, scope,
PixelsOperation.OperationType.ReplaceColor,
PixelsOperation.ColorActionType.Set);
Color color;
try {
color = FxColorTools.cssToAwt(readArgument("color"));
writeParameter("color", color);
List<java.awt.Color> colors = new ArrayList();
colors.add(color);
scope.setColors(colors);
pixelsOperation.setColorPara1(color);
} catch (Exception e) {
displayError(message("Invalid" + ": color"));
return false;
}
try {
Color newColor = FxColorTools.cssToAwt(readArgument("newColor"));
writeParameter("newColor", newColor);
pixelsOperation.setColorPara2(newColor);
} catch (Exception e) {
displayError(message("Invalid" + ": newColor"));
return false;
}
boolean invert = false, trans = false;
String invertv = readArgument("invert");
if (invertv != null) {
invert = StringTools.isTrue(invertv);
}
writeParameter("invert", invert);
scope.setColorExcluded(invert);
String transv = readArgument("trans");
if (transv != null) {
trans = StringTools.isTrue(transv);
}
writeParameter("trans", trans);
pixelsOperation.setSkipTransparent(color.getRGB() != 0 && !trans);
MatchAlgorithm a = null;
String aname = readArgument("algorithm");
if (aname == null) {
a = ColorMatch.DefaultAlgorithm;
} else {
for (MatchAlgorithm ma : MatchAlgorithm.values()) {
if (Languages.matchIgnoreCase(ma.name(), aname)) {
a = ma;
break;
}
}
}
if (a == null) {
displayError(message("Invalid" + ": algorithm"));
return false;
}
writeParameter("algorithm", a);
colorMatch.setAlgorithm(a);
double threshold = ColorMatch.suggestedThreshold(a);
try {
String v = readArgument("threshold");
if (v != null) {
threshold = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": threshold"));
return false;
}
writeParameter("threshold", threshold);
colorMatch.setThreshold(threshold);
if (ColorMatch.supportWeights(a)) {
double hueWeight = 1d, brightnessWeight = 1d, saturationWeight = 1d;
try {
String v = readArgument("hueWeight");
if (v != null) {
hueWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": hueWeight"));
return false;
}
writeParameter("hueWeight", hueWeight);
colorMatch.setHueWeight(hueWeight);
try {
String v = readArgument("brightnessWeight");
if (v != null) {
brightnessWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": brightnessWeight"));
return false;
}
writeParameter("brightnessWeight", brightnessWeight);
colorMatch.setBrightnessWeight(brightnessWeight);
try {
String v = readArgument("saturationWeight");
if (v != null) {
saturationWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": saturationWeight"));
return false;
}
writeParameter("saturationWeight", saturationWeight);
colorMatch.setSaturationWeight(saturationWeight);
}
boolean hue = true, brightness = false, saturation = false;
String huev = readArgument("hue");
if (huev != null) {
hue = StringTools.isTrue(huev);
}
writeParameter("hue", hue);
String brightnessv = readArgument("brightness");
if (brightnessv != null) {
brightness = StringTools.isTrue(brightnessv);
}
writeParameter("brightness", brightness);
String saturationv = readArgument("saturation");
if (saturationv != null) {
saturation = StringTools.isTrue(saturationv);
}
writeParameter("saturation", saturation);
pixelsOperation.setBoolPara1(hue)
.setBoolPara2(brightness)
.setBoolPara3(saturation);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkSharp() {
try {
String a = readArgument("algorithm");
if (a == null || "mask".equalsIgnoreCase(a)) {
short intensity = 2;
String v = readArgument("intensity");
if (v != null) {
try {
intensity = Short.parseShort(v);
} catch (Exception e) {
displayError(message("Invalid" + ": intensity"));
return false;
}
}
a = "mask";
writeParameter("intensity", intensity);
kernel = ConvolutionKernel.makeUnsharpMasking(intensity);
} else if ("eight".equalsIgnoreCase(a)) {
a = "eight";
kernel = ConvolutionKernel.MakeSharpenEightNeighborLaplace();
} else if ("four".equalsIgnoreCase(a)) {
a = "four";
kernel = ConvolutionKernel.MakeSharpenFourNeighborLaplace();
} else {
displayError(message("Invalid" + ": algorithm"));
return false;
}
writeParameter("algorithm", a);
String edge = readArgument("edge");
if (edge == null || "copy".equalsIgnoreCase(edge)) {
edge = "copy";
kernel.setEdge(ConvolutionKernel.Edge_Op.COPY);
} else if ("zero".equalsIgnoreCase(edge)) {
edge = "zero";
kernel.setEdge(ConvolutionKernel.Edge_Op.FILL_ZERO);
} else {
displayError(message("Invalid" + ": edge"));
return false;
}
writeParameter("edge", edge);
String color = readArgument("color");
if (color == null || "keep".equalsIgnoreCase(color)) {
color = "keep";
kernel.setColor(ConvolutionKernel.Color.Keep);
} else if ("grey".equalsIgnoreCase(color) || "gray".equalsIgnoreCase(color)) {
color = "grey";
kernel.setColor(ConvolutionKernel.Color.Grey);
} else if ("bw".equalsIgnoreCase(color) || "blackwhite".equalsIgnoreCase(color)) {
color = "blackwhite";
kernel.setColor(ConvolutionKernel.Color.BlackWhite);
} else {
displayError(message("Invalid" + ": color=" + color));
return false;
}
writeParameter("color", color);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
/*
run
*/
@Override
public boolean run() {
try {
ok = false;
resultImage = null;
String operation = getOperation();
switch (operation.toLowerCase()) {
case "edit":
ok = true;
break;
case "replace":
ok = runReplace();
break;
case "sharp":
ok = runSharp();
break;
}
File outputFile = getOutputFile();
if (resultImage != null && outputFile != null) {
ImageFileWriters.writeImageFile(task, resultImage, outputFile);
}
} catch (Exception e) {
displayError(e.toString());
}
return ok;
}
public boolean runReplace() {
try {
pixelsOperation.setImage(sourceImage).setTask(task);
resultImage = pixelsOperation.start();
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean runSharp() {
try {
convolution = ImageConvolution.create();
convolution.setImage(sourceImage).setKernel(kernel).setTask(task);
resultImage = convolution.start();
return resultImage != null;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
@Override
public void openResult() {
try {
File outputFile = getOutputFile();
if (outputFile != null && outputFile.exists()) {
ImageEditorController.openFile(outputFile);
} else if (resultImage != null) {
displayInfo(message("ImageGenerated"));
ImageEditorController.openImage(SwingFXUtils.toFXImage(resultImage, null));
}
} catch (Exception e) {
displayError(e.toString());
}
}
}
| 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/fxml/SquareRootCoordinate.java | alpha/MyBox/src/main/java/mara/mybox/fxml/SquareRootCoordinate.java | package mara.mybox.fxml;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2020-05-16
* @License Apache License Version 2.0
*/
public class SquareRootCoordinate extends StringConverter<Number> {
@Override
public String toString(Number value) {
double d = value.doubleValue();
return StringTools.format(d * d);
}
@Override
public Number fromString(String string) {
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/fxml/AlarmClockTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/AlarmClockTask.java | package mara.mybox.fxml;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import mara.mybox.controller.AlarmClockRunController;
import mara.mybox.db.data.AlarmClock;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Fxmls;
/**
* @Author Mara
* @CreateDate 2018-7-16
* @License Apache License Version 2.0
*/
public class AlarmClockTask extends TimerTask {
protected AlarmClock alarm;
protected TimeUnit timeUnit = TimeUnit.SECONDS;
protected long delay, period;
public AlarmClockTask(AlarmClock alarmClock) {
this.alarm = alarmClock;
// AlarmClock.calculateNextTime(alarmClock);
// delay = alarmClock.getNextTime() - new Date().getTime();
// period = AlarmClock.period(alarmClock);
}
@Override
public void run() {
try {
// MyBoxLog.debug("call");
if (!canTriggerAlarm(alarm)) {
MyBoxLog.debug("Can not tigger alarm due to not satisfied");
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
AlarmClockRunController controller = (AlarmClockRunController) WindowTools.openStage(Fxmls.AlarmClockRunFxml);
controller.runAlarm(alarm);
if (AppVariables.AlarmClockController != null
&& AppVariables.AlarmClockController.getAlertClockTableController() != null) {
AppVariables.AlarmClockController.getAlertClockTableController().refreshAction();
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
});
// if (alarm.getAlarmType() == NotRepeat) {
// ScheduledFuture future = ScheduledTasks.get(alarm.getKey());
// if (future != null) {
// future.cancel(true);
// ScheduledTasks.remove(alarm.getKey());
// }
// alarm.setIsActive(false);
// AlarmClock.writeAlarmClock(alarm);
// } else {
// alarm.setLastTime(new Date().getTime());
// alarm.setNextTime(-1);
// AlarmClock.calculateNextTime(alarm);
// AlarmClock.writeAlarmClock(alarm);
// }
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static boolean canTriggerAlarm(AlarmClock alarm) {
long now = new Date().getTime();
switch (alarm.getAlarmType()) {
case NotRepeat:
case EveryDay:
case EverySomeDays:
case EverySomeHours:
case EverySomeMinutes:
case EverySomeSeconds:
return true;
case Weekend:
return DateTools.isWeekend(now);
case WorkingDays:
return !DateTools.isWeekend(now);
default:
return false;
}
}
/*
get/set
*/
public AlarmClock getAlarm() {
return alarm;
}
public void setAlarm(AlarmClock alarm) {
this.alarm = alarm;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public long getPeriod() {
return period;
}
public void setPeriod(long period) {
this.period = period;
}
}
| 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/fxml/WebViewTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/WebViewTools.java | package mara.mybox.fxml;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ScrollBar;
import javafx.scene.shape.Rectangle;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.StringTools;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* @Author Mara
* @CreateDate 2021-7-29
* @License Apache License Version 2.0
*/
public class WebViewTools {
public static String userAgent() {
return new WebView().getEngine().getUserAgent();
}
public static String getHtml(WebView webView) {
if (webView == null) {
return "";
}
return getHtml(webView.getEngine());
}
public static String getHtml(WebEngine engine) {
try {
if (engine == null) {
return "";
}
Object c = engine.executeScript("document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static void selectAll(WebEngine webEngine) {
try {
String js = "window.getSelection().removeAllRanges(); "
+ "var selection = window.getSelection();\n"
+ "var range = document.createRange();\n"
+ "range.selectNode(document.documentElement);\n"
+ "selection.addRange(range);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectNone(WebEngine webEngine) {
try {
String js = "window.getSelection().removeAllRanges(); ";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectNode(WebEngine webEngine, String id) {
try {
String js = "window.getSelection().removeAllRanges(); "
+ "var selection = window.getSelection();\n"
+ "var range = document.createRange();\n"
+ "range.selectNode(document.getElementById('" + id + "'));\n"
+ "selection.addRange(range);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectElement(WebView webView, Element element) {
try {
if (webView == null || element == null) {
return;
}
String id = element.getAttribute("id");
String newid = DateTools.nowFileString();
element.setAttribute("id", newid);
selectNode(webView.getEngine(), newid);
if (id != null) {
element.setAttribute("id", id);
} else {
element.removeAttribute("id");
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static String selectedText(WebEngine webEngine) {
try {
Object ret = webEngine.executeScript("window.getSelection().toString();");
if (ret == null) {
return null;
}
return ((String) ret);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String selectedHtml(WebEngine webEngine) {
try {
String js = " var selectionObj = window.getSelection();\n"
+ " var rangeObj = selectionObj.getRangeAt(0);\n"
+ " var docFragment = rangeObj.cloneContents();\n"
+ " var div = document.createElement(\"div\");\n"
+ " div.appendChild(docFragment);\n"
+ " div.innerHTML;";
Object ret = webEngine.executeScript(js);
if (ret == null) {
return null;
}
return ((String) ret);
} catch (Exception e) {
// MyBoxLog.debug(e);
return null;
}
}
// https://blog.csdn.net/weixin_29251337/article/details/117888001
public static void addStyle(WebEngine webEngine, String style, String styleid) {
try {
if (webEngine == null || styleid == null || styleid.isBlank()
|| style == null || style.isBlank()) {
return;
}
removeNode(webEngine, styleid);
String js = "var node = document.createElement(\"style\");\n"
+ "node.id = \"" + styleid + "\";\n"
+ "node.type = \"text/css\";\n"
+ "node.innerHTML = \"" + StringTools.replaceLineBreak(style) + "\";\n"
+ "document.body.appendChild(node);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void removeNode(WebEngine webEngine, String id) {
try {
if (webEngine == null || id == null || id.isBlank()) {
return;
}
String js = "var node = document.getElementById(\"" + id + "\");\n"
+ "if ( node != null ) node.parentNode.removeChild(node);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static HTMLEditor editor(WebView webView) {
if (webView == null) {
return null;
}
Parent p = webView.getParent();
while (p != null) {
if (p instanceof HTMLEditor) {
return (HTMLEditor) p;
}
p = p.getParent();
}
return null;
}
public static WebView webview(Parent node) {
if (node == null) {
return null;
}
for (Node child : node.getChildrenUnmodifiable()) {
if (child instanceof WebView) {
return (WebView) child;
}
if (child instanceof Parent) {
WebView w = webview((Parent) child);
if (w != null) {
return w;
}
}
}
return null;
}
public static String getFrame(WebEngine engine, int index) {
try {
if (engine == null || index < 0) {
return "";
}
Object c = engine.executeScript("window.frames[" + index + "].document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static String getFrame(WebEngine engine, String frameName) {
try {
if (engine == null || frameName == null) {
return "";
}
Object c = engine.executeScript("window.frames." + frameName + ".document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static Document getFrameDocument(WebEngine engine, String frameName) {
try {
if (engine == null) {
return null;
}
Object c = engine.executeScript("window.frames." + frameName + ".document");
if (c == null) {
return null;
}
return (Document) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static int frameIndex(WebEngine webEngine, String frameName) {
try {
if (frameName == null) {
return -1;
}
Object c = webEngine.executeScript("function checkFrameIndex(frameName) { "
+ " for (i=0; i<window.frames.length; i++) { "
+ " if ( window.frames[i].name == frameName ) return i ;"
+ " };"
+ " return -1; "
+ "};"
+ "checkFrameIndex(\"" + frameName + "\");");
if (c == null) {
return -1;
}
return ((int) c);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return -1;
}
}
public static Map<String, String> readCookie(WebEngine webEngine) {
try {
String s = (String) webEngine.executeScript("document.cookie;");
String[] vs = s.split(";");
Map<String, String> m = new HashMap<>();
for (String v : vs) {
String[] vv = v.split("=");
if (vv.length < 2) {
continue;
}
m.put(vv[0].trim(), vv[1].trim());
}
return m;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
// https://stackoverflow.com/questions/31264847/how-to-set-remember-scrollbar-thumb-position-in-javafx-8-webview?r=SearchResults
public static ScrollBar getVScrollBar(WebView webView) {
try {
Set<Node> scrolls = webView.lookupAll(".scroll-bar");
for (Node scrollNode : scrolls) {
if (ScrollBar.class.isInstance(scrollNode)) {
ScrollBar scroll = (ScrollBar) scrollNode;
if (scroll.getOrientation() == Orientation.VERTICAL) {
return scroll;
}
}
}
} catch (Exception e) {
}
return null;
}
// https://bbs.csdn.net/topics/310020841
public static int px(WebEngine webEngine, String s) {
try {
String js = "function stringPX(s){"
+ " var span = document.createElement(\"span\");\n"
+ " span.innerHTML = s;\n"
+ " document.body.appendChild(span);\n"
+ " var width = span.offsetWidth;\n"
+ " document.body.removeChild(span); "
+ " return width; "
+ "}"
+ "stringPX(\"" + s + "\");";
Object c = webEngine.executeScript(js);
if (c == null) {
return -1;
}
return ((int) c);
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public static Rectangle tagRect(WebEngine webEngine, String tag, int index) {
try {
Rectangle rect = new Rectangle();
String js = "var rect = document.getElementsByTagName('" + tag + "')[" + index + "].getBoundingClientRect();"
+ "rect.x + ' ' + rect.y + ' ' + rect.width + ' ' + rect.height ";
Object c = webEngine.executeScript(js);
if (c == null) {
return null;
}
String[] values = ((String) c).split("\\s+");
rect.setX(Double.parseDouble(values[0]));
rect.setY(Double.parseDouble(values[1]));
rect.setWidth(Double.parseDouble(values[2]));
rect.setHeight(Double.parseDouble(values[3]));
return rect;
} 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/fxml/FxSingletonTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/FxSingletonTask.java | package mara.mybox.fxml;
import mara.mybox.controller.BaseController;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxSingletonTask<Void> extends FxTask<Void> {
public FxSingletonTask(BaseController controller) {
this.controller = controller;
}
@Override
protected void taskQuit() {
if (controller != null && controller.getTask() == self) {
controller.setTask(null);
}
super.taskQuit();
}
}
| 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/fxml/ValidationTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ValidationTools.java | package mara.mybox.fxml;
import java.io.File;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-5
* @License Apache License Version 2.0
*/
public class ValidationTools {
public static void setEditorStyle(final ComboBox box, final String style) {
box.getEditor().setStyle(style);
// Platform.runLater(new Runnable() {
// @Override
// public void run() {
// box.getEditor().setStyle(style);
// }
// });
}
public static void setEditorNormal(final ComboBox box) {
setEditorStyle(box, null);
}
public static void setEditorBadStyle(final ComboBox box) {
setEditorStyle(box, UserConfig.badStyle());
}
public static void setEditorWarnStyle(final ComboBox box) {
setEditorStyle(box, UserConfig.warnStyle());
}
public static int positiveValue(final TextField input) {
return positiveValue(input, Integer.MAX_VALUE);
}
public static int positiveValue(final TextField input, final int max) {
try {
int v = Integer.parseInt(input.getText());
if (v > 0 && v <= max) {
input.setStyle(null);
return v;
} else {
input.setStyle(UserConfig.badStyle());
return -1;
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
return -1;
}
}
public static void setNonnegativeValidation(final TextField input) {
setNonnegativeValidation(input, Integer.MAX_VALUE);
}
public static void setNonnegativeValidation(final TextField input, final int max) {
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
int v = Integer.parseInt(newValue);
if (v >= 0 && v <= max) {
input.setStyle(null);
} else {
input.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
}
});
}
public static void setFloatValidation(final TextField input) {
input.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
try {
float v = Float.parseFloat(newValue);
input.setStyle(null);
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
});
}
public static void setPositiveValidation(final TextField input) {
setPositiveValidation(input, Integer.MAX_VALUE);
}
public static void setPositiveValidation(final TextField input, final int max) {
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
int v = Integer.parseInt(newValue);
if (v > 0 && v <= max) {
input.setStyle(null);
} else {
input.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
}
});
}
public static void setFileValidation(final TextField input, String key) {
if (input == null) {
return;
}
input.setStyle(UserConfig.badStyle());
input.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
String v = input.getText();
if (v == null || v.isEmpty()) {
input.setStyle(UserConfig.badStyle());
return;
}
final File file = new File(newValue);
if (!file.exists() || !file.isFile()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(null);
UserConfig.setString(key, file.getParent());
});
}
public static void setPathValidation(final TextField input) {
if (input == null) {
return;
}
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final File file = new File(newValue);
if (!file.isDirectory()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(null);
}
});
}
public static void setPathExistedValidation(final TextField input) {
if (input == null) {
return;
}
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final File file = new File(newValue);
if (!file.exists() || !file.isDirectory()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(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/fxml/TextClipboardTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/TextClipboardTools.java | package mara.mybox.fxml;
import java.io.File;
import java.sql.Connection;
import javafx.application.Platform;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.TextInMyBoxClipboardController;
import mara.mybox.controller.TextInSystemClipboardController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.table.TableTextClipboard;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.TextClipboardMonitor.DefaultInterval;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.AppVariables.TextClipMonitor;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class TextClipboardTools {
/*
monitor
*/
public static void stopTextClipboardMonitor() {
if (TextClipMonitor != null) {
TextClipMonitor.stop();
TextClipMonitor = null;
}
}
public static void startTextClipboardMonitor() {
startTextClipboardMonitor(getMonitorInterval());
}
public static void startTextClipboardMonitor(int interval) {
if (TextClipMonitor != null) {
TextClipMonitor.cancel();
TextClipMonitor = null;
}
TextClipMonitor = new TextClipboardMonitor().start(interval);
}
public static int getMonitorInterval() {
int v = UserConfig.getInt("TextClipboardMonitorInterval", DefaultInterval);
if (v <= 0) {
v = DefaultInterval;
}
return v;
}
public static int setMonitorInterval(int v) {
if (v <= 0) {
v = DefaultInterval;
}
UserConfig.setInt("TextClipboardMonitorInterval", v);
return v;
}
public static boolean isMonitoring() {
return TextClipMonitor != null;
}
public static boolean isCopy() {
return UserConfig.getBoolean("CopyTextInSystemClipboard", false);
}
public static boolean isMonitoringCopy() {
return isMonitoring() && isCopy();
}
public static void setCopy(boolean value) {
UserConfig.setBoolean("CopyTextInSystemClipboard", value);
}
public static boolean isStartWhenBoot() {
return UserConfig.getBoolean("StartTextClipboardMonitorWhenBoot", false);
}
public static void setStartWhenBoot(boolean value) {
UserConfig.setBoolean("StartTextClipboardMonitorWhenBoot", value);
}
/*
System Clipboard
*/
public static boolean systemClipboardHasString() {
return Clipboard.getSystemClipboard().hasString();
}
public static String getSystemClipboardString() {
return Clipboard.getSystemClipboard().getString();
}
public static boolean stringToSystemClipboard(String string) {
try {
if (string == null || string.isBlank()) {
return false;
}
ClipboardContent cc = new ClipboardContent();
cc.putString(string);
Clipboard.getSystemClipboard().setContent(cc);
TextInSystemClipboardController.updateSystemClipboardStatus();
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static void copyToSystemClipboard(BaseController controller, TextInputControl textInput) {
if (controller == null || textInput == null) {
return;
}
String text = textInput.getSelectedText();
if (text == null || text.isEmpty()) {
text = textInput.getText();
}
copyToSystemClipboard(controller, text);
}
public static void copyToSystemClipboard(BaseController controller, String text) {
Platform.runLater(new Runnable() {
@Override
public void run() {
if (text == null || text.isEmpty()) {
if (controller != null) {
controller.popError(message("NoData"));
}
return;
}
if (stringToSystemClipboard(text)) {
if (controller == null) {
return;
}
int len = text.length();
String info = "\n" + message("CharactersNumber") + ":" + len
+ "\n----------------------\n"
+ (len > 100 ? text.substring(0, 100) + "\n......" : text);
if (TextClipboardTools.isMonitoringCopy()) {
controller.popInformation(message("CopiedInClipBoards") + info);
} else {
controller.popInformation(message("CopiedInSystemClipBoard") + info);
}
} else {
if (controller != null) {
controller.popFailed();
}
}
}
});
}
public static void copyFileToSystemClipboard(BaseController controller, File file) {
Platform.runLater(new Runnable() {
@Override
public void run() {
if (file == null || !file.exists()) {
controller.popError(message("NoData"));
return;
}
copyToSystemClipboard(controller, TextFileTools.readTexts(null, file));
}
});
}
/*
MyBox Clipboard
*/
public static void copyToMyBoxClipboard(BaseController controller, TextInputControl textInput) {
if (controller == null || textInput == null) {
return;
}
String text = textInput.getSelectedText();
if (text == null || text.isEmpty()) {
text = textInput.getText();
}
copyToMyBoxClipboard(controller, text);
}
public static void copyToMyBoxClipboard(BaseController controller, String text) {
if (controller == null) {
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
if (text == null || text.isEmpty()) {
controller.popError(message("NoData"));
return;
}
if (stringToMyBoxClipboard(text)) {
String info = text.length() > 200 ? text.substring(0, 200) + "\n......" : text;
controller.popInformation(message("CopiedInMyBoxClipBoard") + "\n----------------------\n" + info);
} else {
controller.popFailed();
}
}
});
}
public static boolean stringToMyBoxClipboard(String string) {
if (string == null || string.isBlank()) {
return false;
}
return stringToMyBoxClipboard(null, null, string);
}
public static boolean stringToMyBoxClipboard(TableTextClipboard inTable, Connection inConn, String string) {
try {
if (string == null || string.isBlank()) {
return false;
}
new Thread() {
@Override
public void run() {
try {
TableTextClipboard table = inTable;
if (table == null) {
table = new TableTextClipboard();
}
Connection conn = inConn;
if (conn == null || conn.isClosed()) {
conn = DerbyBase.getConnection();
}
table.save(conn, string);
conn.commit();
TextInMyBoxClipboardController.updateMyBoxClipboard();
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
}.start();
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/FxBackgroundTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/FxBackgroundTask.java | package mara.mybox.fxml;
import mara.mybox.controller.BaseController;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxBackgroundTask<Void> extends FxTask<Void> {
public FxBackgroundTask(BaseController controller) {
this.controller = controller;
}
@Override
protected void taskQuit() {
if (controller != null && controller.getBackgroundTask() == self) {
controller.setBackgroundTask(null);
}
super.taskQuit();
}
}
| 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/fxml/ImageClipboardTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ImageClipboardTools.java | package mara.mybox.fxml;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ImageInMyBoxClipboardController;
import mara.mybox.db.data.ImageClipboard;
import static mara.mybox.fxml.ImageClipboardMonitor.DefaultInterval;
import static mara.mybox.value.AppVariables.ImageClipMonitor;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-2
* @License Apache License Version 2.0
*/
public class ImageClipboardTools {
/*
monitor
*/
public static void stopImageClipboardMonitor() {
if (ImageClipMonitor != null) {
ImageClipMonitor.stop();
ImageClipMonitor = null;
}
}
public static void startImageClipboardMonitor(int interval, ImageAttributes attributes, String filePrefix) {
if (ImageClipMonitor != null) {
ImageClipMonitor.stop();
ImageClipMonitor = null;
}
ImageClipMonitor = new ImageClipboardMonitor().start(interval, attributes, filePrefix);
}
public static int getMonitorInterval() {
int v = UserConfig.getInt("ImageClipboardMonitorInterval", DefaultInterval);
if (v <= 0) {
v = DefaultInterval;
}
return v;
}
public static int setMonitorInterval(int v) {
if (v <= 0) {
v = DefaultInterval;
}
UserConfig.setInt("ImageClipboardMonitorInterval", v);
return v;
}
public static boolean isMonitoring() {
return ImageClipMonitor != null;
}
public static int getWidth() {
return UserConfig.getInt("ImageClipboardMonitorWidth", -1);
}
public static int setWidth(int v) {
UserConfig.setInt("ImageClipboardMonitorWidth", v);
return v;
}
public static boolean isCopy() {
return UserConfig.getBoolean("CopyImageInSystemClipboard", false);
}
public static boolean isMonitoringCopy() {
return isMonitoring() && isCopy();
}
public static void setCopy(boolean value) {
UserConfig.setBoolean("CopyImageInSystemClipboard", value);
}
public static boolean isSave() {
return UserConfig.getBoolean("SaveImageInSystemClipboard", false);
}
public static void setSave(boolean value) {
UserConfig.setBoolean("SaveImageInSystemClipboard", value);
}
/*
Image in System Clipboard
*/
public static void copyToSystemClipboard(BaseController controller, Image image) {
if (controller == null || image == null) {
return;
}
ClipboardContent cc = new ClipboardContent();
cc.putImage(image);
Clipboard.getSystemClipboard().setContent(cc);
if (isMonitoringCopy()) {
controller.popInformation(message("CopiedInClipBoards"));
ImageInMyBoxClipboardController.updateClipboards();
} else {
controller.popInformation(message("CopiedInSystemClipBoard"));
}
}
public static Image fetchImageInClipboard(boolean clear) {
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasImage()) {
return null;
}
Image image = clipboard.getImage();
if (clear) {
clipboard.clear();
}
return image;
}
/*
Image in MyBox Clipboard
*/
public static void copyToMyBoxClipboard(BaseController controller, Image image, ImageClipboard.ImageSource source) {
if (controller == null || image == null) {
return;
}
if (ImageClipboard.add(null, image, source) != null) {
controller.popInformation(message("CopiedInMyBoxClipBoard"));
} else {
controller.popFailed();
}
}
}
| 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/fxml/FxFileTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/FxFileTools.java | package mara.mybox.fxml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javafx.stage.FileChooser;
import mara.mybox.controller.BaseController_Files;
import mara.mybox.db.data.VisitHistoryTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class FxFileTools {
public static File getInternalFile(String resourceFile, String subPath, String userFile) {
return getInternalFile(resourceFile, subPath, userFile, false);
}
// Solution from https://stackoverflow.com/questions/941754/how-to-get-a-path-to-a-resource-in-a-java-jar-file
public static File getInternalFile(String resourceFile, String subPath, String userFile, boolean deleteExisted) {
if (resourceFile == null || userFile == null) {
return null;
}
try {
File path = new File(AppVariables.MyboxDataPath + File.separator + subPath + File.separator);
if (!path.exists()) {
path.mkdirs();
}
File file = new File(AppVariables.MyboxDataPath + File.separator + subPath + File.separator + userFile);
if (file.exists() && !deleteExisted) {
return file;
}
File tmpFile = getInternalFile(resourceFile);
if (tmpFile == null) {
return null;
}
if (file.exists()) {
file.delete();
}
mara.mybox.tools.FileTools.override(tmpFile, file);
return file;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static File getInternalFile(String resourceFile) {
if (resourceFile == null) {
return null;
}
File file = FileTmpTools.getTempFile();
try (final InputStream input = FxFileTools.class.getResourceAsStream(resourceFile);
final OutputStream out = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) > 0) {
out.write(bytes, 0, read);
}
file.deleteOnExit();
return file;
} catch (Exception e) {
// MyBoxLog.error(e.toString());
return null;
}
}
public static File selectFile(BaseController_Files controller) {
return selectFile(controller,
UserConfig.getPath(controller.getBaseName() + "SourcePath"),
controller.getSourceExtensionFilter());
}
public static File selectFile(BaseController_Files controller, int fileType) {
return selectFile(controller,
UserConfig.getPath(VisitHistoryTools.getPathKey(fileType)),
VisitHistoryTools.getExtensionFilter(fileType));
}
public static File selectFile(BaseController_Files controller, File path, List<FileChooser.ExtensionFilter> filter) {
try {
FileChooser fileChooser = new FileChooser();
if (path.exists()) {
fileChooser.setInitialDirectory(path);
}
fileChooser.getExtensionFilters().addAll(filter);
File file = fileChooser.showOpenDialog(controller.getMyStage());
if (file == null || !file.exists()) {
return null;
}
controller.recordFileOpened(file);
return file;
} catch (Exception e) {
return null;
}
}
public static List<String> getResourceFiles(String path) {
List<String> files = new ArrayList<>();
try {
if (!path.endsWith("/")) {
path += "/";
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL dirURL = classLoader.getResource(path);
if (dirURL == null) {
File filePath = new File(path);
if (!filePath.exists()) {
MyBoxLog.error(path);
return files;
}
File[] list = filePath.listFiles();
if (list != null) {
for (File file : list) {
if (file.isFile()) {
files.add(file.getName());
}
}
}
return files;
}
if (dirURL.getProtocol().equals("jar")) {
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
try (final JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"))) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (entry.isDirectory() || !name.startsWith(path)) {
continue;
}
name = name.substring(path.length());
if (!name.contains("/")) {
files.add(name);
}
}
}
} else if (dirURL.getProtocol().equals("file")) {
File[] list = new File(dirURL.getPath()).listFiles();
if (list != null) {
for (File file : list) {
if (file.isFile()) {
files.add(file.getName());
}
}
}
}
} catch (Exception e) {
MyBoxLog.console(e);
}
return files;
}
}
| 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/fxml/BaseTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/BaseTask.java | package mara.mybox.fxml;
import java.util.Date;
import javafx.application.Platform;
import javafx.concurrent.Task;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class BaseTask<P> extends Task<P> {
protected BaseTask self;
protected Date startTime, endTime;
protected long cost;
protected boolean ok, quit;
protected String error;
public BaseTask() {
error = null;
startTime = new Date();
ok = quit = false;
self = this;
}
public static BaseTask create() {
BaseTask task = new BaseTask();
return task;
}
@Override
protected P call() {
ok = false;
if (!initValues()) {
return null;
}
try {
ok = handle();
} catch (Exception e) {
error = e.toString();
ok = false;
}
return null;
}
protected boolean initValues() {
startTime = new Date();
return true;
}
protected boolean handle() {
return true;
}
@Override
protected void succeeded() {
super.succeeded();
taskQuit();
Platform.runLater(() -> {
if (isCancelled()) {
return;
}
if (ok) {
whenSucceeded();
} else {
whenFailed();
}
finalAction();
});
Platform.requestNextPulse();
}
protected void whenSucceeded() {
}
protected void whenFailed() {
}
protected void whenCanceled() {
}
@Override
protected void failed() {
super.failed();
taskQuit();
Platform.runLater(() -> {
whenFailed();
finalAction();
});
Platform.requestNextPulse();
}
@Override
protected void cancelled() {
super.cancelled();
taskQuit();
Platform.runLater(() -> {
whenCanceled();
finalAction();
});
Platform.requestNextPulse();
}
protected void taskQuit() {
endTime = new Date();
if (startTime != null) {
cost = endTime.getTime() - startTime.getTime();
}
self = null;
quit = true;
}
protected void finalAction() {
}
public String duration() {
return DateTools.datetimeMsDuration(new Date().getTime() - startTime.getTime());
}
public boolean isWorking() {
return !quit && !isCancelled() && !isDone();
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public long getCost() {
return cost;
}
public void setCost(long cost) {
this.cost = cost;
}
public boolean isOk() {
return ok;
}
public void setOk(boolean ok) {
this.ok = ok;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public BaseTask getSelf() {
return self;
}
public void setSelf(BaseTask self) {
this.self = self;
}
public boolean isQuit() {
return quit;
}
public void setQuit(boolean quit) {
this.quit = quit;
}
}
| 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/fxml/PopTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/PopTools.java | package mara.mybox.fxml;
import mara.mybox.fxml.menu.MenuTools;
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.Separator;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jdk.jshell.JShell;
import jdk.jshell.SourceCodeAnalysis;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Attributes;
import mara.mybox.controller.BaseLogsController;
import mara.mybox.controller.ControlWebView;
import mara.mybox.controller.HtmlStyleInputController;
import mara.mybox.controller.MenuController;
import mara.mybox.data2d.Data2D;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Color;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Date;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Datetime;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Double;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Enumeration;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.EnumerationEditable;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Era;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.File;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Float;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Image;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Latitude;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Long;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Longitude;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Short;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.String;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.table.BaseTableTools;
import mara.mybox.db.table.TableStringValues;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.StringTools;
import mara.mybox.tools.SystemTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.TimeFormats;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class PopTools {
/*
common
*/
public static void browseURI(BaseController controller, URI uri) {
if (uri == null) {
return;
}
if (SystemTools.isLinux()) {
// On my CentOS 7, system hangs when both Desktop.isDesktopSupported() and
// desktop.isSupported(Desktop.Action.BROWSE) are true.
// https://stackoverflow.com/questions/27879854/desktop-getdesktop-browse-hangs
// Below workaround for Linux because "Desktop.getDesktop().browse()" doesn't work on some Linux implementations
try {
if (Runtime.getRuntime().exec(new String[]{"which", "xdg-open"}).getInputStream().read() > 0) {
Runtime.getRuntime().exec(new String[]{"xdg-open", uri.toString()});
return;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
} else if (SystemTools.isMac()) {
// https://stackoverflow.com/questions/5226212/how-to-open-the-default-webbrowser-using-java/28807079#28807079
try {
Runtime.getRuntime().exec(new String[]{"open", uri.toString()});
return;
} catch (Exception e) {
MyBoxLog.debug(e);
}
} else if (Desktop.isDesktopSupported()) {
// https://stackoverflow.com/questions/23176624/javafx-freeze-on-desktop-openfile-desktop-browseuri?r=SearchResults
try {
Desktop.getDesktop().browse(uri);
return;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
if (!uri.getScheme().equals("file") || new File(uri.getPath()).isFile()) {
ControllerTools.openTarget(uri.toString());
} else {
alertError(controller, message("DesktopNotSupportBrowse"));
}
}
public static Alert alert(BaseController controller, Alert.AlertType type, String information) {
try {
Alert alert = new Alert(type);
if (controller != null) {
alert.setTitle(controller.getTitle());
}
alert.setHeaderText(null);
alert.setContentText(information);
alert.getDialogPane().setMinWidth(Region.USE_PREF_SIZE);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.getDialogPane().applyCss();
// https://stackoverflow.com/questions/38799220/javafx-how-to-bring-dialog-alert-to-the-front-of-the-screen?r=SearchResults
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
stage.sizeToScene();
alert.showAndWait();
return alert;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Alert alertInformation(BaseController controller, String information) {
return alert(controller, Alert.AlertType.INFORMATION, information);
}
public static Alert alertWarning(BaseController controller, String information) {
return alert(controller, Alert.AlertType.WARNING, information);
}
public static Alert alertError(BaseController controller, String information) {
return alert(controller, Alert.AlertType.ERROR, information);
}
public static String askValue(String title, String header, String name, String initValue) {
return askValue(title, header, name, initValue, 400);
}
public static String askValue(String title, String header, String name, String initValue, int minWidth) {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle(title);
dialog.setHeaderText(header);
dialog.setContentText(name);
dialog.getEditor().setText(initValue);
dialog.getEditor().setPrefWidth(initValue == null ? minWidth : Math.min(minWidth, initValue.length() * AppVariables.sceneFontSize));
dialog.getEditor().selectEnd();
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
stage.getScene().getRoot().requestFocus();
Optional<String> result = dialog.showAndWait();
if (result == null || !result.isPresent()) {
return null;
}
String value = result.get();
return value;
}
public static boolean askSure(String title, String sureString) {
return askSure(title, null, sureString);
}
// https://openjfx.io/javadoc/17/javafx.controls/javafx/scene/control/Dialog.html
public static boolean askSure(String title, String header, String sureString) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(title);
if (header != null) {
alert.setHeaderText(header);
}
alert.setContentText(sureString);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
ButtonType buttonSure = new ButtonType(message("Sure"));
ButtonType buttonCancel = new ButtonType(message("Cancel"), ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonSure, buttonCancel);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
Optional<ButtonType> result = alert.showAndWait();
return result != null && result.isPresent() && result.get() == buttonSure;
}
public static Popup makePopWindow(BaseController parent, String fxml) {
try {
BaseController controller = WindowTools.loadFxml(fxml);
if (controller == null) {
return null;
}
Popup popup = new Popup();
popup.setAutoHide(true);
popup.getContent().add(controller.getMyScene().getRoot());
popup.setUserData(controller);
popup.setOnHiding((WindowEvent event) -> {
WindowTools.closeWindow(popup);
});
controller.setParent(parent, BaseController_Attributes.StageType.Popup);
controller.setMyWindow(popup);
if (parent != null) {
parent.closePopup();
parent.setPopup(popup);
}
return popup;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void showError(BaseController controller, String error) {
if (controller == null) {
MyBoxLog.error(error);
} else if (controller instanceof BaseLogsController) {
((BaseLogsController) controller).updateLogs(error, true, true);
} else if (controller.getTask() != null) {
controller.getTask().setError(error);
} else {
Platform.runLater(() -> {
controller.alertError(error);
// MyBoxLog.debug(error);
});
}
}
/*
style
*/
public static ContextMenu popHtmlStyle(Event event, ControlWebView controller) {
try {
if (event == null || controller == null) {
return null;
}
List<MenuItem> items = new ArrayList<>();
String baseName = controller.getBaseName();
MenuItem menu = new MenuItem(message("HtmlStyle"));
menu.setStyle(attributeTextStyle());
items.add(menu);
items.add(new SeparatorMenuItem());
ToggleGroup sgroup = new ToggleGroup();
String prefix = UserConfig.getBoolean(baseName + "ShareHtmlStyle", true) ? "AllInterface" : baseName;
String currentStyle = UserConfig.getString(prefix + "HtmlStyle", null);
RadioMenuItem rmenu = new RadioMenuItem(message("None"));
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.setStyle(null);
}
});
rmenu.setSelected(currentStyle == null);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
boolean predefinedValue = false;
for (HtmlStyles.HtmlStyle style : HtmlStyles.HtmlStyle.values()) {
rmenu = new RadioMenuItem(message(style.name()));
String styleValue = HtmlStyles.styleValue(style);
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.setStyle(styleValue);
}
});
boolean isCurrent = currentStyle != null && currentStyle.equals(styleValue);
rmenu.setSelected(isCurrent);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
if (isCurrent) {
predefinedValue = true;
}
}
rmenu = new RadioMenuItem(message("Input") + "...");
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
HtmlStyleInputController inputController = HtmlStyleInputController.open(controller,
message("Style"), UserConfig.getString(prefix + "HtmlStyle", null));
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
if (value == null || value.isBlank()) {
value = null;
}
controller.setStyle(value);
inputController.closeStage();
}
});
}
});
rmenu.setSelected(currentStyle != null && !predefinedValue);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
items.add(new SeparatorMenuItem());
items.add(MenuTools.popCheckMenu(baseName + "HtmlStyles"));
controller.popEventMenu(event, items);
return controller.getPopMenu();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ContextMenu popWindowStyles(BaseController parent, String baseStyle, Event event) {
try {
List<MenuItem> items = new ArrayList<>();
String baseName = parent.getBaseName();
MenuItem menu = new MenuItem(message("WindowStyle"));
menu.setStyle(attributeTextStyle());
items.add(menu);
items.add(new SeparatorMenuItem());
Map<String, String> styles = new LinkedHashMap<>();
styles.put("None", "");
styles.put("Transparent", "; -fx-text-fill: black; -fx-background-color: transparent;");
styles.put("Console", "; -fx-text-fill: #CCFF99; -fx-background-color: black;");
styles.put("Blackboard", "; -fx-text-fill: white; -fx-background-color: #336633;");
styles.put("Ago", "; -fx-text-fill: white; -fx-background-color: darkblue;");
styles.put("Book", "; -fx-text-fill: black; -fx-background-color: #F6F1EB;");
ToggleGroup sgroup = new ToggleGroup();
String prefix = UserConfig.getBoolean(baseName + "ShareWindowStyle", true) ? "AllInterface" : baseName;
String currentStyle = UserConfig.getString(prefix + "WindowStyle", "");
for (String name : styles.keySet()) {
RadioMenuItem rmenu = new RadioMenuItem(message(name));
String style = styles.get(name);
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setString(prefix + "WindowStyle", style);
parent.getThisPane().setStyle(baseStyle + style);
setMenuLabelsStyle(parent.getThisPane(), baseStyle + style);
}
});
rmenu.setSelected(currentStyle != null && currentStyle.equals(style));
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
}
items.add(new SeparatorMenuItem());
CheckMenuItem checkMenu = new CheckMenuItem(message("ShareAllInterface"));
checkMenu.setSelected(UserConfig.getBoolean(baseName + "ShareWindowStyle", true));
checkMenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean(baseName + "ShareWindowStyle", checkMenu.isSelected());
}
});
items.add(checkMenu);
items.add(MenuTools.popCheckMenu(baseName + "WindowStyles"));
parent.popEventMenu(event, items);
return parent.getPopMenu();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void setMenuLabelsStyle(Node node, String style) {
if (node instanceof Label) {
node.setStyle(style);
} else if (node instanceof Parent && !(node instanceof TableView)) {
for (Node child : ((Parent) node).getChildrenUnmodifiable()) {
setMenuLabelsStyle(child, style);
}
}
}
public static void setWindowStyle(Pane pane, String baseName, String baseStyle) {
String prefix = UserConfig.getBoolean(baseName + "ShareWindowStyle", true) ? "AllInterface" : baseName;
String style = UserConfig.getString(prefix + "WindowStyle", "");
pane.setStyle(baseStyle + style);
setMenuLabelsStyle(pane, baseStyle + style);
}
/*
common parts
*/
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event) {
return valuesMenu(parent, input, valueName, title, event, null, false);
}
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event, boolean alwaysClear) {
return valuesMenu(parent, input, valueName, title, event, null, alwaysClear);
}
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event, List<Node> exTopButtons, boolean alwaysClear) {
try {
MenuController controller = MenuController.open(parent, input, event, valueName, alwaysClear);
if (title != null) {
controller.setTitleLabel(title);
}
List<Node> topButtons = new ArrayList<>();
if (input instanceof TextArea) {
Button newLineButton = new Button();
newLineButton.setGraphic(StyleTools.getIconImageView("iconTurnOver.png"));
NodeStyleTools.setTooltip(newLineButton, new Tooltip(message("Newline")));
newLineButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
input.replaceText(input.getSelection(), "\n");
controller.getThisPane().requestFocus();
input.requestFocus();
}
});
topButtons.add(newLineButton);
}
Button clearButton = new Button(message("ClearInputArea"));
clearButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
input.clear();
controller.getThisPane().requestFocus();
input.requestFocus();
}
});
topButtons.add(clearButton);
if (exTopButtons != null) {
topButtons.addAll(exTopButtons);
}
controller.addFlowPane(topButtons);
controller.addNode(new Separator());
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void addButtonsPane(MenuController controller, List<String> values) {
addButtonsPane(controller, values, -1);
}
public static void addButtonsPane(MenuController controller, List<String> values, int index) {
try {
List<Node> buttons = new ArrayList<>();
for (String value : values) {
Button button = makeMenuButton(controller, value, value);
if (button != null) {
buttons.add(button);
}
}
controller.addFlowPane(buttons);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static Button makeMenuButton(MenuController controller, String name, String value) {
try {
if (controller == null || value == null) {
return null;
}
if (name == null) {
name = value;
}
TextInputControl input = (TextInputControl) controller.getNode();
Button button = new Button(name.length() > 200 ? name.substring(0, 200) + " ..." : name);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (controller.isClearAndSet()) {
input.setText(value);
} else {
input.replaceText(input.getSelection(), value);
}
if (controller.isCloseAfterPaste()) {
controller.close();
} else {
controller.getThisPane().requestFocus();
}
input.requestFocus();
input.deselect();
}
});
return button;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
pop values
*/
public static void popListValues(BaseController parent, TextInputControl input,
String valueName, String title, List<String> values, Event event) {
try {
MenuController controller = valuesMenu(parent, input, valueName, title, event);
addButtonsPane(controller, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void popMappedValues(BaseController parent, TextInputControl input,
String valueName, LinkedHashMap<String, String> values, Event event) {
try {
MenuController controller = valuesMenu(parent, input, valueName, valueName, event);
List<Node> nodes = new ArrayList<>();
for (String value : values.keySet()) {
String msg = values.get(value);
Button button = makeMenuButton(controller,
value + (msg != null && !msg.isBlank() ? " " + msg : ""),
value);
if (button != null) {
nodes.add(button);
}
}
controller.addFlowPane(nodes);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
/*
saved values
*/
public static void popSavedValues(BaseController parent, TextInputControl input, Event event,
String valueName, boolean alwaysClear) {
try {
List<Node> setButtons = new ArrayList<>();
Button clearValuesButton = new Button(message("ClearValues"));
clearValuesButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent aevent) {
TableStringValues.clear(valueName);
parent.closePopup();
popSavedValues(parent, input, aevent, valueName, alwaysClear);
}
});
setButtons.add(clearValuesButton);
int max = UserConfig.getInt(valueName + "MaxSaved", 20);
Button maxButton = new Button(message("MaxSaved"));
maxButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent aevent) {
String value = PopTools.askValue(parent.getTitle(), null, message("MaxSaved"), max + "");
if (value == null) {
return;
}
try {
int v = Integer.parseInt(value);
UserConfig.setInt(valueName + "MaxSaved", v);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
});
setButtons.add(maxButton);
MenuController controller = valuesMenu(parent, input, valueName, null,
event, setButtons, alwaysClear);
controller.addNode(new Label(message("PopValuesComments")));
List<String> values = TableStringValues.max(valueName, max);
List<Node> buttons = new ArrayList<>();
for (String value : values) {
Button button = makeMenuButton(controller, value, value);
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent aevent) {
if (aevent.getButton() == MouseButton.SECONDARY) {
TableStringValues.delete(valueName, value);
controller.close();
popSavedValues(parent, input, event, valueName, alwaysClear);
}
}
});
buttons.add(button);
}
controller.addFlowPane(buttons);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void popSavedValues(BaseController parent, TextInputControl input, Event event,
String valueName) {
popSavedValues(parent, input, event, valueName, false);
}
/*
examples
*/
public static ContextMenu popDatetimeExamples(BaseController parent, ContextMenu inPopMenu,
TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs));
values.add(DateTools.datetimeToString(d, TimeFormats.Date));
values.add(DateTools.datetimeToString(d, TimeFormats.Month));
values.add(DateTools.datetimeToString(d, TimeFormats.Year));
values.add(DateTools.datetimeToString(d, TimeFormats.TimeMs));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZone));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsC));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZoneC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeE));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsE));
values.add(DateTools.datetimeToString(d, TimeFormats.DateE));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthE));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZoneE));
values.addAll(Arrays.asList(
"2020-07-15T36:55:09", "2020-07-10T10:10:10.532 +0800"
));
return popDateMenu(parent, inPopMenu, input, mouseEvent, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ContextMenu popDateExamples(BaseController parent, ContextMenu inPopMenu,
TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Date));
values.add(DateTools.datetimeToString(d, TimeFormats.Month));
values.add(DateTools.datetimeToString(d, TimeFormats.Year));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthC));
values.add(DateTools.datetimeToString(d, TimeFormats.DateE));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthE));
return popDateMenu(parent, inPopMenu, input, mouseEvent, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void popEraExamples(BaseController parent, TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Date + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Month + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DateA, Locale.ENGLISH, null));
Date bc = DateTools.encodeDate("770-3-9 12:56:33.498 BC");
values.add(DateTools.datetimeToString(bc, TimeFormats.DatetimeA + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.Date + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.MonthA, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.YearA, Locale.ENGLISH, null));
if (Languages.isChinese()) {
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Date + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Month + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DateA, Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.DatetimeA + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.DateA + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.MonthA, Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.YearA, Locale.CHINESE, null));
}
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsC + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.MonthC, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsB + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DateB + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DatetimeB, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.MonthB, Locale.ENGLISH, null));
| 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/fxml/TextClipboardMonitor.java | alpha/MyBox/src/main/java/mara/mybox/fxml/TextClipboardMonitor.java | package mara.mybox.fxml;
import java.sql.Connection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.scene.input.Clipboard;
import mara.mybox.controller.TextInMyBoxClipboardController;
import mara.mybox.controller.TextInSystemClipboardController;
import mara.mybox.db.table.TableTextClipboard;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-8-3
* @License Apache License Version 2.0
*/
public class TextClipboardMonitor extends Timer {
public final static int DefaultInterval = 200;
protected Date startTime = null;
protected int number;
protected final TableTextClipboard tableTextClipboard = new TableTextClipboard();
protected String lastString = "";
protected Connection conn = null;
protected TextInSystemClipboardController controller;
public TextClipboardMonitor start(int inInterval) {
int interval = TextClipboardTools.setMonitorInterval(inInterval);
startTime = new Date();
number = 0;
schedule(new MonitorTask(), 0, interval);
Platform.runLater(() -> {
TextInSystemClipboardController.updateSystemClipboardStatus();
TextInMyBoxClipboardController.updateMyBoxClipboardStatus();
});
MyBoxLog.debug("Text Clipboard Monitor started. Interval:" + interval);
return this;
}
public void stop() {
cancel();
Platform.runLater(() -> {
TextInSystemClipboardController.updateSystemClipboardStatus();
TextInMyBoxClipboardController.updateMyBoxClipboardStatus();
});
MyBoxLog.debug("Text Clipboard Monitor stopped.");
}
class MonitorTask extends TimerTask {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public synchronized void run() {
try {
controller = TextInSystemClipboardController.running();
if (!TextClipboardTools.isCopy() && controller == null) {
TextClipboardTools.stopTextClipboardMonitor();
return;
}
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasString()) {
return;
}
String clip = clipboard.getString();
if (clip == null || clip.isEmpty() || clip.equals(lastString)) {
return;
}
lastString = clip;
number++;
if (TextClipboardTools.isCopy()) {
TextClipboardTools.stringToMyBoxClipboard(tableTextClipboard, conn, lastString);
}
if (controller != null) {
controller.loadClip(clip);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
});
}
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getLastString() {
return lastString;
}
public void setLastString(String lastString) {
this.lastString = lastString;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public TextInSystemClipboardController getController() {
return controller;
}
public void setController(TextInSystemClipboardController controller) {
this.controller = controller;
}
}
| 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/fxml/DownloadTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/DownloadTask.java | package mara.mybox.fxml;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.Map;
import mara.mybox.data.DownloadItem;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.HtmlReadTools;
import mara.mybox.tools.NetworkTools;
import mara.mybox.tools.UrlTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class DownloadTask<Void> extends FxTask<Void> {
protected String address;
protected URL url;
protected HttpURLConnection connection;
protected File targetPath, targetFile, tmpFile;
protected long totalSize, currentSize;
protected boolean readHead = false;
protected Map<String, String> head;
protected int responseCode;
public static DownloadTask create() {
DownloadTask task = new DownloadTask();
return task;
}
@Override
protected boolean initValues() {
if (address == null) {
error = Languages.message("InvalidData");
return false;
}
startTime = new Date();
currentSize = 0;
try {
url = UrlTools.url(address);
return url != null;
} catch (Exception e) {
error = e.toString();
return false;
}
}
@Override
protected boolean handle() {
if (readHead) {
readHead();
} else {
download();
}
return true;
}
protected HttpURLConnection getConnection() {
try {
return NetworkTools.httpConnection(url);
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
return null;
}
}
protected void readHead() {
try {
connection = getConnection();
head = HtmlReadTools.requestHead(connection);
connection.disconnect();
connection = null;
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
}
}
protected boolean download() {
try {
String filename = url.getFile().substring(url.getFile().lastIndexOf('/'));
targetFile = new File(targetPath.getAbsolutePath() + File.separator
+ FileNameTools.filter(filename.trim()));
connection = getConnection();
connection.setRequestMethod("GET");
responseCode = connection.getResponseCode();
totalSize = connection.getContentLength();
error = connection.getResponseMessage();
connection.disconnect();
progress();
if (responseCode >= 400) {
return false;
}
error = null;
connection = getConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.connect();
tmpFile = new File(targetFile.getAbsolutePath() + ".downloading");
progress();
try (BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
RandomAccessFile tmpFileStream = new RandomAccessFile(tmpFile, "rw")) {
currentSize = tmpFile.length();
if (currentSize > 0) {
inStream.skip(currentSize);
tmpFileStream.seek(currentSize);
}
progress();
byte[] buf = new byte[AppValues.IOBufferLength];
int len;
while ((len = inStream.read(buf)) > 0) {
if (isCancelled()) {
break;
}
tmpFileStream.write(buf, 0, len);
currentSize += len;
progress();
}
}
connection.disconnect();
responseCode = 0;
Files.copy(Paths.get(tmpFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
FileDeleteTools.delete(tmpFile);
return targetFile.exists();
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
return false;
}
}
protected void progress() {
}
@Override
protected void taskQuit() {
super.taskQuit();
progress();
}
protected void assign(DownloadItem item) {
item.setTask(this);
}
/*
get/set
*/
public String getAddress() {
return address;
}
public DownloadTask setAddress(String address) {
this.address = address;
return this;
}
public URL getUrl() {
return url;
}
public DownloadTask setUrl(URL url) {
this.url = url;
return this;
}
public File getTargetPath() {
return targetPath;
}
public DownloadTask setTargetPath(File targetPath) {
this.targetPath = targetPath;
return this;
}
public Map<String, String> getHead() {
return head;
}
public DownloadTask setHead(Map<String, String> head) {
this.head = head;
return this;
}
public int getResponseCode() {
return responseCode;
}
public DownloadTask setResponseCode(int responseCode) {
this.responseCode = responseCode;
return this;
}
public File getTmpFile() {
return tmpFile;
}
public DownloadTask setTmpFile(File tmpFile) {
this.tmpFile = tmpFile;
return this;
}
public long getTotalSize() {
return totalSize;
}
public DownloadTask setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public long getCurrentSize() {
return currentSize;
}
public DownloadTask setCurrentSize(long currentSize) {
this.currentSize = currentSize;
return this;
}
public boolean isReadHead() {
return readHead;
}
public DownloadTask setReadHead(boolean readHead) {
this.readHead = readHead;
return this;
}
public File getTargetFile() {
return targetFile;
}
public DownloadTask setTargetFile(File targetFile) {
this.targetFile = targetFile;
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/fxml/FxTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/FxTask.java | package mara.mybox.fxml;
import javafx.scene.Node;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.LoadingController;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxTask<Void> extends BaseTask<Void> {
protected BaseController controller;
protected LoadingController loading;
protected Node disableNode;
public FxTask() {
}
public FxTask(BaseController controller) {
this.controller = controller;
}
@Override
protected boolean initValues() {
if (!super.initValues()) {
return false;
}
if (disableNode != null) {
disableNode.setDisable(true);
}
return true;
}
public void setInfo(String info) {
if (info == null || info.isBlank()) {
return;
}
if (loading != null) {
loading.setInfo(info);
} else if (controller != null) {
controller.displayInfo(info);
} else {
MyBoxLog.console(info);
}
}
@Override
public void setError(String error) {
this.error = error;
if (error == null || error.isBlank()) {
return;
}
if (loading != null) {
loading.setInfo(error);
} else if (controller != null) {
controller.displayError(error);
} else {
MyBoxLog.error(error);
}
}
public String getInfo() {
if (loading == null) {
return null;
}
return loading.getInfo();
}
@Override
protected void whenSucceeded() {
if (isCancelled()) {
setInfo(message("Cancelled"));
return;
}
if (controller != null) {
controller.displayInfo(message("Successful"));
}
}
@Override
protected void whenCanceled() {
setInfo(message("Cancelled"));
}
@Override
protected void whenFailed() {
if (isCancelled()) {
setInfo(message("Cancelled"));
return;
}
if (controller != null) {
MyBoxLog.console(controller.getClass());
if (error != null) {
MyBoxLog.debug(controller.getTitle() + ": " + error);
if (error.equals(message("Failed"))) {
controller.displayError(error);
} else {
if (error.contains("java.sql.SQLDataException: 22003 : [0] DOUBLE")) {
error = error + "\n\n" + message("DataOverflow");
}
controller.alertError(error);
}
} else {
controller.popFailed();
}
}
}
@Override
protected void finalAction() {
super.finalAction();
controller = null;
loading = null;
if (disableNode != null) {
disableNode.setDisable(false);
}
}
/*
get/set
*/
public BaseController getController() {
return controller;
}
public void setController(BaseController controller) {
this.controller = controller;
}
public LoadingController getLoading() {
return loading;
}
public void setLoading(LoadingController loading) {
this.loading = loading;
}
public Node getDisableNode() {
return disableNode;
}
public void setDisableNode(Node disableNode) {
this.disableNode = disableNode;
}
}
| 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/fxml/ConditionNode.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ConditionNode.java | package mara.mybox.fxml;
import javafx.scene.text.Text;
import mara.mybox.data.GeographyCode;
/**
* @Author Mara
* @CreateDate 2020-04-18
* @License Apache License Version 2.0
*/
public class ConditionNode extends Text {
private GeographyCode code;
private String title, condition;
public ConditionNode() {
}
public ConditionNode(String text) {
setText(text);
}
public static ConditionNode create(String text) {
ConditionNode item = new ConditionNode(text);
return item;
}
public GeographyCode getCode() {
return code;
}
/*
customized get/set
*/
/*
get/set
*/
public ConditionNode setCode(GeographyCode code) {
this.code = code;
return this;
}
public String getTitle() {
return title;
}
public ConditionNode setTitle(String title) {
this.title = title;
return this;
}
public String getCondition() {
return condition;
}
public ConditionNode setCondition(String condition) {
this.condition = condition;
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/fxml/ImageClipboardMonitor.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ImageClipboardMonitor.java | package mara.mybox.fxml;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Connection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.controller.ImageInMyBoxClipboardController;
import mara.mybox.controller.ImageInSystemClipboardController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ImageClipboard;
import mara.mybox.db.data.ImageClipboard.ImageSource;
import mara.mybox.db.table.TableImageClipboard;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxImageTools;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.IntTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.io.FileUtils;
/**
* @Author Mara
* @CreateDate 2021-8-3
* @License Apache License Version 2.0
*/
public class ImageClipboardMonitor extends Timer {
public final static int DefaultInterval = 1000;
protected ImageAttributes attributes;
protected Date startTime = null;
protected int recordNumber, savedNumber, copiedNumber;
protected TableImageClipboard tableImageClipboard;
private String filePrefix;
private Image lastImage = null;
public ImageClipboardMonitor start(int inInterval, ImageAttributes attributes, String filePrefix) {
int interval = ImageClipboardTools.setMonitorInterval(inInterval);
this.attributes = attributes;
this.filePrefix = filePrefix;
startTime = new Date();
recordNumber = 0;
savedNumber = 0;
copiedNumber = 0;
lastImage = null;
schedule(new MonitorTask(), 0, interval);
Platform.runLater(() -> {
ImageInSystemClipboardController.updateSystemClipboardStatus();
ImageInMyBoxClipboardController.updateClipboardsStatus();
});
MyBoxLog.debug("Image Clipboard Monitor started. Interval:" + interval);
return this;
}
public void stop() {
cancel();
Platform.runLater(() -> {
ImageInSystemClipboardController.updateSystemClipboardStatus();
ImageInMyBoxClipboardController.updateClipboardsStatus();
});
MyBoxLog.debug("Image Clipboard Monitor stopped.");
clearTmpClips();
attributes = null;
lastImage = null;
tableImageClipboard = null;
startTime = null;
filePrefix = null;
}
class MonitorTask extends TimerTask {
private Image clip;
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public synchronized void run() {
try {
clearTmpClips();
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller == null && !ImageClipboardTools.isCopy()
&& (!ImageClipboardTools.isSave() || filePrefix == null || attributes == null)) {
ImageClipboardTools.stopImageClipboardMonitor();
return;
}
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasImage()) {
return;
}
clip = clipboard.getImage();
if (clip == null || FxImageTools.sameImage(null, lastImage, clip)) {
return;
}
lastImage = clip;
recordNumber++;
if (controller != null) {
controller.loadClip(clip);
}
if (ImageClipboardTools.isCopy()) {
copyToMyBoxClipboard(clip);
}
if (ImageClipboardTools.isSave()) {
if (filePrefix == null || attributes == null) {
if (controller != null) {
controller.filesInfo(message("ImageNotSaveDueInvalidPath"));
}
} else {
saveImage(clip);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
});
}
}
public static void clearTmpClips() {
try {
System.gc();
File path = FileTools.javaIOTmpPath();
File[] files = path.listFiles();
if (files == null) {
return;
}
for (File file : files) {
try {
if (file.isFile() && file.getName().endsWith(".TMP")) {
FileUtils.deleteQuietly(file);
}
} catch (Exception e) {
}
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public void saveImage(Image image) {
if (image == null || filePrefix == null || attributes == null) {
return;
}
new Thread() {
@Override
public void run() {
File file = new File(filePrefix + DateTools.nowFileString() + "-"
+ IntTools.random(1000) + "." + attributes.getImageFormat());
while (file.exists()) {
file = new File(filePrefix + DateTools.nowFileString() + "-"
+ IntTools.random(1000) + "." + attributes.getImageFormat());
}
String fname = file.getAbsolutePath();
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller != null) {
Platform.runLater(() -> {
controller.filesInfo(message("Saving") + " " + fname);
});
}
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
int width = ImageClipboardTools.getWidth();
if (width > 0) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width);
}
BufferedImage converted = ImageConvertTools.convertColorSpace(null, bufferedImage, attributes);
ImageFileWriters.writeImageFile(null, converted, attributes, fname);
savedNumber++;
if (controller != null) {
Platform.runLater(() -> {
controller.updateNumbers();
controller.filesInfo("");
});
}
}
}.start();
}
public void copyToMyBoxClipboard(Image image) {
if (image == null) {
return;
}
new Thread() {
@Override
public void run() {
try (Connection conn = DerbyBase.getConnection()) {
int width = ImageClipboardTools.getWidth();
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
if (width > 0) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width);
}
if (bufferedImage == null) {
return;
}
if (tableImageClipboard == null) {
tableImageClipboard = new TableImageClipboard();
}
tableImageClipboard.insertData(conn,
ImageClipboard.create(null, bufferedImage, ImageSource.SystemClipBoard));
conn.commit();
ImageInMyBoxClipboardController.updateClipboards();
copiedNumber++;
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller != null) {
Platform.runLater(() -> {
controller.updateNumbers();
});
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
}.start();
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public int getNumber() {
return recordNumber;
}
public void setNumber(int number) {
this.recordNumber = number;
}
public TableImageClipboard getTableImageClipboard() {
return tableImageClipboard;
}
public void setTableImageClipboard(TableImageClipboard tableImageClipboard) {
this.tableImageClipboard = tableImageClipboard;
}
public String getFilePrefix() {
return filePrefix;
}
public void setFilePrefix(String filePrefix) {
this.filePrefix = filePrefix;
}
public Image getLastImage() {
return lastImage;
}
public void setLastImage(Image lastImage) {
this.lastImage = lastImage;
}
public ImageAttributes getAttributes() {
return attributes;
}
public void setAttributes(ImageAttributes attributes) {
this.attributes = attributes;
}
public int getRecordNumber() {
return recordNumber;
}
public void setRecordNumber(int recordNumber) {
this.recordNumber = recordNumber;
}
public int getSavedNumber() {
return savedNumber;
}
public void setSavedNumber(int savedNumber) {
this.savedNumber = savedNumber;
}
public int getCopiedNumber() {
return copiedNumber;
}
public void setCopiedNumber(int copiedNumber) {
this.copiedNumber = copiedNumber;
}
}
| 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/fxml/ControllerTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ControllerTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.Arrays;
import javafx.stage.Stage;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ControlDataJavascript;
import mara.mybox.controller.Data2DManufactureController;
import mara.mybox.controller.FileDecompressUnarchiveController;
import mara.mybox.controller.HtmlPopController;
import mara.mybox.controller.ImageEditorController;
import mara.mybox.controller.ImagePopController;
import mara.mybox.controller.JsonEditorController;
import mara.mybox.controller.MarkdownEditorController;
import mara.mybox.controller.MarkdownPopController;
import mara.mybox.controller.MediaPlayerController;
import mara.mybox.controller.PdfViewController;
import mara.mybox.controller.PptViewController;
import mara.mybox.controller.SvgEditorController;
import mara.mybox.controller.TextEditorController;
import mara.mybox.controller.TextPopController;
import mara.mybox.controller.WebBrowserController;
import mara.mybox.controller.WordViewController;
import mara.mybox.controller.XmlEditorController;
import static mara.mybox.fxml.WindowTools.replaceStage;
import mara.mybox.tools.CompressTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.value.FileExtensions;
import mara.mybox.value.Fxmls;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class ControllerTools {
public static BaseController openMyBox(Stage stage) {
return replaceStage(stage, Fxmls.MyboxFxml);
}
public static BaseController openTarget(String filename) {
return openTarget(filename, true);
}
public static BaseController openTarget(String filename, boolean mustOpen) {
if (filename == null) {
return null;
}
if (filename.startsWith("http") || filename.startsWith("ftp")) {
return WebBrowserController.openAddress(filename, true);
}
File file = new File(filename);
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
PopTools.browseURI(null, file.toURI());
return null;
}
String suffix = FileNameTools.ext(file.getName()).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
return ImageEditorController.openFile(file);
} else if ("html".equals(suffix) || "htm".equals(suffix)) {
return WebBrowserController.openFile(file);
} else if ("md".equals(suffix)) {
return MarkdownEditorController.open(file);
} else if ("pdf".equals(suffix)) {
return PdfViewController.open(file);
} else if ("csv".equals(suffix)) {
return Data2DManufactureController.openCSVFile(file, null, true, ",");
} else if ("xlsx".equals(suffix) || "xls".equals(suffix)) {
return Data2DManufactureController.openExcelFile(file, null, true);
} else if ("ppt".equals(suffix) || "pptx".equals(suffix)) {
return PptViewController.openFile(file);
} else if ("doc".equals(suffix) || "docx".equals(suffix)) {
return WordViewController.openFile(file);
} else if ("json".equals(suffix)) {
return JsonEditorController.open(file);
} else if ("xml".equals(suffix)) {
return XmlEditorController.open(file);
} else if ("svg".equals(suffix)) {
return SvgEditorController.open(file);
} else if ("js".equals(suffix)) {
return ControlDataJavascript.openFile(null, file);
} else if (Arrays.asList(FileExtensions.TextFileSuffix).contains(suffix)) {
return TextEditorController.open(file);
} else if (CompressTools.compressFormats().contains(suffix) || CompressTools.archiveFormats().contains(suffix)) {
return FileDecompressUnarchiveController.open(file);
} else if (Arrays.asList(FileExtensions.MediaPlayerSupports).contains(suffix)) {
return MediaPlayerController.open(file);
} else if (mustOpen) {
PopTools.browseURI(null, file.toURI());
}
return null;
}
public static BaseController popTarget(BaseController parent, String filename, boolean mustOpen) {
if (filename == null) {
return null;
}
if (filename.startsWith("http") || filename.startsWith("ftp")) {
return HtmlPopController.openAddress(parent, filename);
}
File file = new File(filename);
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
PopTools.browseURI(parent, file.toURI());
return null;
}
if (file.length() > 1024 * 1024) {
return openTarget(filename, true);
}
String suffix = FileNameTools.ext(file.getName()).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
return ImagePopController.openFile(parent, filename);
} else if ("html".equals(suffix) || "htm".equals(suffix)) {
return HtmlPopController.openAddress(parent, filename);
} else if ("md".equals(suffix)) {
return MarkdownPopController.openFile(parent, filename);
} else if (Arrays.asList(FileExtensions.TextFileSuffix).contains(suffix)) {
return TextPopController.openFile(parent, filename);
} else if (mustOpen) {
return openTarget(filename, mustOpen);
} else {
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/fxml/WindowTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/WindowTools.java | package mara.mybox.fxml;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ScheduledFuture;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Attributes.StageType;
import mara.mybox.controller.BaseTaskController;
import mara.mybox.controller.ClearExpiredDataController;
import mara.mybox.controller.WindowsListController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.DerbyBase.DerbyStatus;
import mara.mybox.db.table.TableUserConf;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.AppValues.AppIcon;
import mara.mybox.value.AppVariables;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2019-1-27 21:48:55
* @License Apache License Version 2.0
*/
public class WindowTools {
/*
* make stage
*/
public static BaseController initScene(Stage stage, String newFxml, StageStyle stageStyle) {
return initScene(stage, newFxml, AppVariables.CurrentBundle, stageStyle);
}
public static BaseController initScene(Stage stage, String newFxml, ResourceBundle bundle, StageStyle stageStyle) {
try {
if (stage == null) {
return null;
}
FXMLLoader fxmlLoader = new FXMLLoader(WindowTools.class.getResource(newFxml), bundle);
return initController(fxmlLoader, stage, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController initController(FXMLLoader fxmlLoader, Stage stage, StageStyle stageStyle) {
try {
if (fxmlLoader == null) {
return null;
}
Scene scene = new Scene(fxmlLoader.load());
BaseController controller = (BaseController) fxmlLoader.getController();
return initController(controller, scene, stage, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// this works for top level pane which is not part of other node
public static BaseController initController(BaseController controller, Scene scene, Stage stage, StageStyle stageStyle) {
try {
if (controller == null || scene == null || stage == null) {
return null;
}
controller.setMyScene(scene);
controller.setMyStage(stage);
controller.setMyWindow(stage);
scene.getStylesheets().add(WindowTools.class.getResource(UserConfig.getStyle()).toExternalForm());
stage.setUserData(controller);
stage.getIcons().add(AppIcon);
stage.setTitle(controller.getBaseTitle());
if (stageStyle != null) {
stage.initStyle(stageStyle);
}
// External request to close
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
if (!controller.leavingScene()) {
event.consume();
} else {
WindowTools.closeWindow(stage);
}
}
});
stage.setOnHiding(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
if (controller != null) {
controller.leaveScene();
}
WindowTools.closeWindow(stage); // Close anyway
}
});
stage.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ob, Boolean ov, Boolean nv) {
if (!nv && controller != null) {
controller.closePopup();
}
}
});
stage.setScene(scene);
stage.show();
if (controller != null) {
controller.afterSceneLoaded();
}
WindowsListController.refresh();
Platform.setImplicitExit(AppVariables.ScheduledTasks == null || AppVariables.ScheduledTasks.isEmpty());
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController initController(FXMLLoader fxmlLoader) {
return initController(fxmlLoader, newStage(), null);
}
public static BaseController loadFxml(String fxml) {
try {
if (fxml == null) {
return null;
}
return loadURL(WindowTools.class.getResource(fxml));
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController loadFile(File file) {
try {
if (file == null || !file.exists()) {
return null;
}
return loadURL(file.toURI().toURL());
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// the pane may be part of other node
public static BaseController loadURL(URL url) {
try {
if (url == null) {
return null;
}
FXMLLoader fxmlLoader = new FXMLLoader(url, AppVariables.CurrentBundle);
Pane pane = fxmlLoader.load();
try {
pane.getStylesheets().add(WindowTools.class.getResource(UserConfig.getStyle()).toExternalForm());
} catch (Exception e) {
}
Scene scene = new Scene(pane);
BaseController controller = (BaseController) fxmlLoader.getController();
controller.setMyScene(scene); // the final scene may be changed
controller.refreshStyle();
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static FXMLLoader newFxml(String fxml) {
try {
return new FXMLLoader(WindowTools.class.getResource(fxml), AppVariables.CurrentBundle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Stage newStage() {
try {
Stage newStage = new Stage();
newStage.initModality(Modality.NONE);
newStage.initStyle(StageStyle.DECORATED);
newStage.initOwner(null);
return newStage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
* open stage
*/
public static BaseController openStage(String fxml) {
return initController(newFxml(fxml), newStage(), null);
}
public static BaseController replaceStage(Window parent, String fxml) {
try {
Stage newStage = new Stage(); // new stage should be opened instead of keeping old stage, to clean resources
newStage.initModality(Modality.NONE);
newStage.initStyle(StageStyle.DECORATED);
newStage.initOwner(null);
BaseController controller = initScene(newStage, fxml, StageStyle.DECORATED);
if (controller != null) {
closeWindow(parent);
}
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController openStage(Window parent, String fxml, ResourceBundle bundle,
boolean isOwned, Modality modality, StageStyle stageStyle) {
try {
Stage stage = new Stage();
stage.initModality(modality);
if (isOwned && parent != null) {
if (parent instanceof Popup) {
stage.initOwner(((Popup) parent).getOwnerWindow());
} else {
stage.initOwner(parent);
}
} else {
stage.initOwner(null);
}
return initScene(stage, fxml, bundle, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController openStage(Window parent, String newFxml) {
return openStage(parent, newFxml, AppVariables.CurrentBundle, false, Modality.NONE, null);
}
public static BaseController openStage(String fxml, ResourceBundle bundle) {
return openStage(null, fxml, bundle, false, Modality.NONE, null);
}
/*
* sub stage
*/
public static BaseController childStage(BaseController parent, String newFxml) {
try {
if (parent == null) {
return openStage(newFxml);
}
BaseController c = openStage(parent.getMyWindow(), newFxml,
AppVariables.CurrentBundle, true, Modality.WINDOW_MODAL, null);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Child);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController popupStage(BaseController parent, String newFxml) {
try {
if (parent == null) {
return null;
}
BaseController c = openStage(parent.getMyWindow(), newFxml,
AppVariables.CurrentBundle, true, Modality.WINDOW_MODAL, null);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Popup);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController referredTopStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.RefferredTop);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController forkStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Fork);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController referredStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Referred);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController topStage(BaseController parent, String newFxml) {
try {
BaseController c = parent != null
? openStage(parent.getMyWindow(), newFxml)
: openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Top);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
* handle stage
*/
public static void reloadAll() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.reload();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void refreshInterfaceAll() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.refreshInterface();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void styleAll(String style) {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.setInterfaceStyle(style);
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static boolean resetWindows() {
if (!TableUserConf.deletePrefix("Interface_")) {
return false;
}
List<String> keys = new ArrayList<>();
keys.addAll(AppVariables.UserConfigValues.keySet());
for (String key : keys) {
if (key.startsWith("Interface_")) {
AppVariables.UserConfigValues.remove(key);
}
}
return true;
}
public static void closeWindow(Window window) {
try {
if (window == null) {
return;
}
Object object = window.getUserData();
if (object != null) {
try {
if (object instanceof BaseController) {
((BaseController) object).leaveScene();
}
} catch (Exception e) {
}
window.setUserData(null);
}
window.hide();
WindowsListController.refresh();
checkExit();
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void checkExit() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (window != null && window.isShowing()) {
return;
}
}
appExit();
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static synchronized void appExit() {
if (AppVariables.handlingExit) {
return;
}
if (UserConfig.getBoolean("ClearExpiredDataBeforeExit", true)) {
AppVariables.handlingExit = true;
Platform.runLater(new Runnable() {
@Override
public void run() {
ClearExpiredDataController.open(true);
}
});
} else {
handleExit();
}
}
public static synchronized void handleExit() {
try {
if (AppVariables.handlingExit) {
return;
}
AppVariables.handlingExit = true;
if (Window.getWindows() != null) {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
closeWindow(window);
}
}
ImageClipboardTools.stopImageClipboardMonitor();
TextClipboardTools.stopTextClipboardMonitor();
if (AppVariables.ScheduledTasks != null && !AppVariables.ScheduledTasks.isEmpty()) {
if (UserConfig.getBoolean("StopAlarmsWhenExit")) {
for (String key : AppVariables.ScheduledTasks.keySet()) {
ScheduledFuture future = AppVariables.ScheduledTasks.get(key);
future.cancel(true);
}
AppVariables.ScheduledTasks = null;
if (AppVariables.ExecutorService != null) {
AppVariables.ExecutorService.shutdownNow();
AppVariables.ExecutorService = null;
}
}
} else {
if (AppVariables.ScheduledTasks != null) {
AppVariables.ScheduledTasks = null;
}
if (AppVariables.ExecutorService != null) {
AppVariables.ExecutorService.shutdownNow();
AppVariables.ExecutorService = null;
}
}
if (AppVariables.ExitTimer != null) {
AppVariables.ExitTimer.cancel();
AppVariables.ExitTimer = null;
}
if (AppVariables.ScheduledTasks == null || AppVariables.ScheduledTasks.isEmpty()) {
doExit();
return;
}
} catch (Exception e) {
}
AppVariables.handlingExit = false;
}
public static synchronized void doExit() {
MyBoxLog.info("Exit now. Bye!");
if (DerbyBase.status == DerbyStatus.Embedded) {
MyBoxLog.info("Shut down Derby...");
DerbyBase.shutdownEmbeddedDerby();
}
// AppVariables.handlingExit = false;
Platform.setImplicitExit(true);
System.gc();
Platform.exit(); // Some thread may still be alive after this
System.exit(0); // Go
Runtime.getRuntime().halt(0);
}
public static void taskInfo(FxTask task, String info) {
if (task != null) {
task.setInfo(info);
}
MyBoxLog.console(info);
}
public static void taskError(FxTask task, String error) {
if (task != null) {
task.setError(error);
}
MyBoxLog.error(error);
}
public static void recordInfo(BaseTaskController taskController, String info) {
if (taskController != null) {
taskController.updateLogs(info);
}
MyBoxLog.console(info);
}
public static void recordError(BaseTaskController taskController, String error) {
if (taskController != null) {
taskController.showLogs(error);
}
MyBoxLog.error(error);
}
public static void closeAllPopup() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (window instanceof Popup) {
window.hide();
}
}
} catch (Exception e) {
}
}
public static BaseController getController(Window window) {
if (window == null) {
return null;
}
Object object = window.getUserData();
if (object != null) {
try {
if (object instanceof BaseController) {
return (BaseController) object;
}
} catch (Exception e) {
}
}
return null;
}
public static BaseController find(String interfaceName) {
try {
if (interfaceName == null || interfaceName.isBlank()) {
return null;
}
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
if (interfaceName.equals(controller.getInterfaceName())) {
return controller;
}
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
return null;
}
public static boolean isRunning(BaseController controller) {
return controller != null
&& controller.getMyStage() != null
&& controller.getMyStage().isShowing();
}
}
| 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/fxml/NodeTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/NodeTools.java | package mara.mybox.fxml;
import java.awt.Toolkit;
import java.net.URL;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.geometry.Bounds;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Control;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.stage.Screen;
import javafx.stage.Stage;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2018-6-11 11:19:42
* @License Apache License Version 2.0
*/
public class NodeTools {
public static String getFxmlName(URL url) {
if (url == null) {
return null;
}
try {
String fullPath = url.getPath();
if (!fullPath.endsWith(".fxml")) {
return null;
}
String fname;
int pos = fullPath.lastIndexOf('/');
if (pos < 0) {
fname = fullPath;
} else {
fname = fullPath.substring(pos + 1);
}
return fname.substring(0, fname.length() - 5);
} catch (Exception e) {
return null;
}
}
public static String getFxmlFile(URL url) {
return "/fxml/" + getFxmlName(url) + ".fxml";
}
public static Node findNode(Pane pane, String nodeId) {
try {
Node node = pane.lookup("#" + nodeId);
return node;
} catch (Exception e) {
return null;
}
}
public static void children(int level, Node node) {
try {
if (node == null) {
return;
}
MyBoxLog.debug(" ".repeat(level) + node.getClass() + " " + node.getId() + " " + node.getStyle());
if (node instanceof SplitPane) {
for (Node child : ((SplitPane) node).getItems()) {
children(level + 1, child);
}
} else if (node instanceof ScrollPane) {
children(level + 1, ((ScrollPane) node).getContent());
} else if (node instanceof TitledPane) {
children(level + 1, ((TitledPane) node).getContent());
} else if (node instanceof StackPane) {
for (Node child : ((StackPane) node).getChildren()) {
children(level + 1, child);
}
} else if (node instanceof TabPane) {
for (Tab tab : ((TabPane) node).getTabs()) {
children(level + 1, tab.getContent());
}
} else if (node instanceof Parent) {
for (Node child : ((Parent) node).getChildrenUnmodifiable()) {
children(level + 1, child);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static Node parent(int level, Node node) {
if (node == null) {
return node;
}
MyBoxLog.console(" ".repeat(level) + node.getClass() + " id:" + node.getId() + " style:" + node.getStyle());
Node parent = node.getParent();
if (parent == null) {
return node;
}
return parent(level + 1, parent);
}
public static Node root(Node node) {
if (node == null) {
return node;
}
MyBoxLog.console(node.getClass() + " id:" + node.getId() + " style:" + node.getStyle());
Node parent = node.getParent();
if (parent == null) {
MyBoxLog.console(parent == null);
return node;
}
return root(parent);
}
public static boolean setRadioFirstSelected(ToggleGroup group) {
if (group == null) {
return false;
}
ObservableList<Toggle> buttons = group.getToggles();
for (Toggle button : buttons) {
RadioButton radioButton = (RadioButton) button;
radioButton.setSelected(true);
return true;
}
return false;
}
public static boolean setRadioSelected(ToggleGroup group, String text) {
if (group == null || text == null) {
return false;
}
ObservableList<Toggle> buttons = group.getToggles();
for (Toggle button : buttons) {
RadioButton radioButton = (RadioButton) button;
if (text.equals(radioButton.getText())) {
button.setSelected(true);
return true;
}
}
return false;
}
public static String getSelectedText(ToggleGroup group) {
if (group == null) {
return null;
}
Toggle button = group.getSelectedToggle();
if (button == null || !(button instanceof RadioButton)) {
return null;
}
return ((RadioButton) button).getText();
}
public static boolean setItemSelected(ComboBox<String> box, String text) {
if (box == null || text == null) {
return false;
}
ObservableList<String> items = box.getItems();
for (String item : items) {
if (text.equals(item)) {
box.getSelectionModel().select(item);
return true;
}
}
return false;
}
public static int getInputInt(TextField input) {
try {
return Integer.parseInt(input.getText());
} catch (Exception e) {
throw new IllegalArgumentException(
"InvalidData");
}
}
public static Object textInputFocus(Scene scene) {
if (scene == null) {
return null;
}
return isTextInput(scene.getFocusOwner());
}
public static Object isTextInput(Object node) {
if (node == null) {
return null;
}
if (node instanceof TextInputControl) {
return node;
}
if (node instanceof ComboBox) {
ComboBox cb = (ComboBox) node;
return cb.isEditable() ? node : null;
}
if (node instanceof WebView) {
return WebViewTools.editor((WebView) node);
}
return null;
}
public static Rectangle2D getScreen() {
return Screen.getPrimary().getVisualBounds();
}
// https://stackoverflow.com/questions/38599588/javafx-stage-setmaximized-only-works-once-on-mac-osx-10-9-5
public static void setMaximized(Stage stage, boolean max) {
stage.setMaximized(max);
if (max) {
Rectangle2D primaryScreenBounds = getScreen();
stage.setX(primaryScreenBounds.getMinX());
stage.setY(primaryScreenBounds.getMinY());
stage.setWidth(primaryScreenBounds.getWidth());
stage.setHeight(primaryScreenBounds.getHeight());
}
}
public static double getWidth(Control control) {
return control.getBoundsInParent().getWidth();
}
public static double getHeight(Control control) {
return control.getBoundsInParent().getHeight();
}
public static void setScrollPane(ScrollPane scrollPane, double xOffset, double yOffset) {
final Bounds visibleBounds = scrollPane.getViewportBounds();
double scrollWidth = scrollPane.getContent().getBoundsInLocal().getWidth() - visibleBounds.getWidth();
double scrollHeight = scrollPane.getContent().getBoundsInLocal().getHeight() - visibleBounds.getHeight();
scrollPane.setHvalue(scrollPane.getHvalue() + xOffset / scrollWidth);
scrollPane.setVvalue(scrollPane.getVvalue() + yOffset / scrollHeight);
}
// https://stackoverflow.com/questions/11552176/generating-a-mouseevent-in-javafx/11567122?r=SearchResults#11567122
public static void fireMouseClicked(Node node) {
try {
Event.fireEvent(node, new MouseEvent(MouseEvent.MOUSE_CLICKED,
node.getLayoutX(), node.getLayoutY(), node.getLayoutX(), node.getLayoutY(),
MouseButton.PRIMARY, 1,
true, true, true, true, true, true, true, true, true, true, null));
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static double screenDpi() {
return Screen.getPrimary().getDpi();
}
public static double screenResolution() {
return Toolkit.getDefaultToolkit().getScreenResolution();
}
public static double dpiScale() {
return dpiScale(screenResolution());
}
public static double dpiScale(double dpi) {
try {
return dpi / screenDpi();
} catch (Exception e) {
return 1;
}
}
public static Image snap(Node node) {
return snap(node, dpiScale());
}
public static Image snap(Node node, double scale) {
try {
if (node == null) {
return null;
}
final SnapshotParameters snapPara = new SnapshotParameters();
snapPara.setFill(Color.TRANSPARENT);
snapPara.setTransform(javafx.scene.transform.Transform.scale(scale, scale));
WritableImage snapshot = node.snapshot(snapPara, null);
return snapshot;
} 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/fxml/ConditionTreeView.java | alpha/MyBox/src/main/java/mara/mybox/fxml/ConditionTreeView.java | package mara.mybox.fxml;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.NodeStyleTools;
/**
* @Author Mara
* @CreateDate 2020-04-19
* @License Apache License Version 2.0
*/
public class ConditionTreeView extends TreeView {
protected String finalConditions, finalTitle;
protected List<String> selectedTitles, selectedConditions, expandedNodes;
public ConditionTreeView() {
finalConditions = null;
finalTitle = "";
selectedTitles = new ArrayList();
selectedConditions = new ArrayList();
expandedNodes = new ArrayList();
setCellFactory(p -> new CheckBoxTreeCell<ConditionNode>() {
@Override
public void updateItem(ConditionNode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getText());
Node node = getGraphic();
if (node != null && node instanceof CheckBox) {
CheckBox checkBox = (CheckBox) node;
if (item.getCondition() != null && !item.getCondition().isBlank()) {
NodeStyleTools.setTooltip(checkBox, item.getTitle() + "\n" + item.getCondition());
} else {
NodeStyleTools.removeTooltip(checkBox);
}
}
}
});
}
public void checkSelection() {
try {
finalConditions = null;
finalTitle = "";
selectedTitles.clear();
if (getRoot() == null) {
return;
}
checkSelection(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void checkSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (!citem.isLeaf() && citem.isIndeterminate()) {
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkSelection(child);
}
} else if (citem.isSelected()) {
if (finalConditions == null || finalConditions.isBlank()) {
if (node.getCondition() == null || node.getCondition().isBlank()) {
finalConditions = "";
} else {
finalConditions = " ( " + node.getCondition() + ") ";
}
} else {
if (node.getCondition() != null && !node.getCondition().isBlank()) {
finalConditions += " OR ( " + node.getCondition() + " ) ";
}
}
if (finalTitle == null || finalTitle.isBlank()) {
finalTitle = "\"" + node.getTitle() + "\"";
} else {
finalTitle += " + \"" + node.getTitle() + "\"";
}
if (!selectedTitles.contains(node.getTitle())) {
selectedTitles.add(node.getTitle());
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void setSelection() {
TreeItem<ConditionNode> root = getRoot();
if (selectedTitles == null || selectedTitles.isEmpty()
|| root == null) {
selectNone();
}
setSelection(root);
}
public void setSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (selectedTitles.contains(node.getTitle())) {
citem.setSelected(true);
return;
} else if (item.isLeaf()) {
return;
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
setSelection(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void selectAll() {
TreeItem<ConditionNode> root = getRoot();
if (root == null) {
return;
}
CheckBoxTreeItem<ConditionNode> rootCheck = (CheckBoxTreeItem<ConditionNode>) getRoot();
rootCheck.setSelected(true);
}
public void selectNone() {
TreeItem<ConditionNode> root = getRoot();
if (root == null) {
return;
}
CheckBoxTreeItem<ConditionNode> rootCheck = (CheckBoxTreeItem<ConditionNode>) root;
rootCheck.setSelected(false);
}
public void select(List<String> titles) {
selectedTitles = titles;
setSelection();
}
public void select(String title) {
if (title == null) {
selectNone();
return;
}
selectedTitles = new ArrayList();
selectedTitles.add(title);
setSelection();
}
public void checkExpanded() {
try {
expandedNodes.clear();
if (getRoot() == null) {
return;
}
checkExpanded(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void checkExpanded(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf() || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (citem.isExpanded() && !expandedNodes.contains(node.getTitle())) {
expandedNodes.add(node.getTitle());
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkExpanded(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void check() {
checkExpanded();
checkSelection();
}
public void expandAll() {
try {
if (getRoot() == null) {
return;
}
expandNode(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNode(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf()) {
return;
}
item.setExpanded(true);
for (TreeItem<ConditionNode> child : item.getChildren()) {
expandNode(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNone() {
try {
if (getRoot() == null) {
return;
}
expandNone(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNone(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf()) {
return;
}
item.setExpanded(true);
for (TreeItem<ConditionNode> child : item.getChildren()) {
expandNode(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
/*
get/set
*/
public String getFinalConditions() {
return finalConditions;
}
public void setFinalConditions(String finalConditions) {
this.finalConditions = finalConditions;
}
public String getFinalTitle() {
return finalTitle;
}
public void setFinalTitle(String finalTitle) {
this.finalTitle = finalTitle;
}
public List<String> getSelectedTitles() {
return selectedTitles;
}
public void setSelectedTitles(List<String> selectedTitles) {
this.selectedTitles = selectedTitles;
}
public List<String> getSelectedConditions() {
return selectedConditions;
}
public void setSelectedConditions(List<String> selectedConditions) {
this.selectedConditions = selectedConditions;
}
public List<String> getExpandedNodes() {
return expandedNodes;
}
public void setExpandedNodes(List<String> expandedNodes) {
this.expandedNodes = expandedNodes;
}
}
| 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/fxml/LocateTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/LocateTools.java | package mara.mybox.fxml;
import java.awt.Point;
import javafx.event.Event;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.robot.Robot;
import javafx.stage.PopupWindow;
import javafx.stage.Stage;
import mara.mybox.tools.SystemTools;
/**
* @Author Mara
* @CreateDate 2021-8-5
* @License Apache License Version 2.0
*/
public class LocateTools {
public static final int PopOffsetY = 30;
public static Point2D coordinate(Event event) {
double x, y;
try {
Point2D everntCoord = getScreenCoordinate(event);
x = everntCoord.getX();
y = everntCoord.getY() + PopOffsetY;
} catch (Exception e) {
javafx.scene.robot.Robot r = new javafx.scene.robot.Robot();
x = r.getMouseX();
y = r.getMouseY() + PopOffsetY;
}
return new Point2D(x, y);
}
public static Point2D getScreenCoordinate(Event event) {
try {
Node node = (Node) (event.getTarget());
return node.localToScreen(0, 0);
} catch (Exception e) {
// MyBoxLog.error(e);
return null;
}
}
public static Point2D center(Node node) {
double x, y;
try {
Point2D p = node.localToScreen(0, 0);
x = p.getX();
y = p.getY() + LocateTools.PopOffsetY;
} catch (Exception e) {
javafx.scene.robot.Robot r = new javafx.scene.robot.Robot();
x = r.getMouseX();
y = r.getMouseY() + PopOffsetY;
}
return new Point2D(x, y);
}
public static double getScreenX(Node node) {
Point2D localToScreen = node.localToScreen(0, 0);
return localToScreen.getX();
}
public static double getScreenY(Node node) {
Point2D localToScreen = node.localToScreen(0, 0);
return localToScreen.getY();
}
public static void locateRight(Stage stage) {
Rectangle2D screen = NodeTools.getScreen();
stage.setX(screen.getWidth() - stage.getWidth());
}
public static void locateUp(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + 2, bounds.getMinY() - 50);
}
public static void locateCenter(Stage stage, Node node) {
if (stage == null || node == null) {
return;
}
Rectangle2D screen = NodeTools.getScreen();
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
double centerX = bounds.getMinX() - stage.getWidth() / 2;
centerX = Math.min(screen.getWidth(), Math.max(0, centerX));
stage.setX(centerX);
double centerY = bounds.getMinY() - stage.getHeight() / 2;
centerY = Math.min(screen.getHeight(), Math.max(0, centerY));
stage.setY(centerY);
}
public static void locateCenter(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + bounds.getWidth() / 2, bounds.getMinY() + bounds.getHeight() / 2);
}
public static void locateRightTop(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMaxX() - window.getWidth() - 20, bounds.getMinY() + 50);
}
public static void aboveCenter(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMinY() - 10);
}
public static void belowCenter(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMaxY() + 10);
}
public static void center(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
double yOffset = referBounds.getHeight() - regionBounds.getHeight();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMinY() + yOffset / 2);
}
public static void locateBelow(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + 2, bounds.getMinY() + bounds.getHeight());
}
public static void locateMouse(MouseEvent event, PopupWindow window) {
window.show((Node) event.getSource(), event.getScreenX(), event.getScreenY());
}
public static void locateEvent(Event event, PopupWindow window) {
if (window == null || event == null) {
return;
}
Point2D everntCoord = coordinate(event);
window.show((Node) event.getSource(), everntCoord.getX(), everntCoord.getY());
}
public static void locateMouse(Node owner, PopupWindow window) {
Point point = SystemTools.getMousePoint();
window.show(owner, point.getX(), point.getY());
}
public static void moveXCenter(Node pNnode, Node node) {
if (node == null || pNnode == null) {
return;
}
double xOffset = pNnode.getBoundsInLocal().getWidth() - node.getBoundsInLocal().getWidth();
if (xOffset > 0) {
node.setLayoutX(xOffset / 2);
} else {
node.setLayoutX(0);
}
}
public static void moveXCenter(Node node) {
if (node == null) {
return;
}
double xOffset = node.getBoundsInLocal().getWidth() - node.getBoundsInLocal().getWidth();
if (xOffset > 0) {
node.setLayoutX(xOffset / 2);
} else {
node.setLayoutX(0);
}
}
public static void moveYCenter(Node pNnode, Node node) {
if (node == null || pNnode == null) {
return;
}
double yOffset = pNnode.getBoundsInLocal().getHeight() - node.getBoundsInLocal().getHeight();
if (yOffset > 0) {
node.setLayoutY(yOffset / 2);
} else {
node.setLayoutY(0);
}
}
public static void moveYCenter(Node node) {
if (node == null) {
return;
}
double yOffset = node.getBoundsInLocal().getHeight() - node.getBoundsInLocal().getHeight();
if (yOffset > 0) {
node.setLayoutY(yOffset / 2);
} else {
node.setLayoutY(0);
}
}
public static void mouseCenter() {
Rectangle2D screen = NodeTools.getScreen();
try {
Robot robot = new Robot();
robot.mouseMove((int) screen.getWidth() / 2, (int) screen.getHeight() / 2);
} catch (Exception e) {
}
}
public static void mouseCenter(Stage stage) {
try {
Robot robot = new Robot();
robot.mouseMove((int) (stage.getX() + stage.getWidth() / 2), (int) (stage.getY() + stage.getHeight() / 2));
} catch (Exception e) {
}
}
public static void moveCenter(Node pNnode, Node node) {
moveXCenter(pNnode, node);
moveYCenter(pNnode, node);
}
public static void moveCenter(Node node) {
moveXCenter(node);
moveYCenter(node);
}
public static void fitSize(Node pNnode, Region region, int margin) {
try {
if (pNnode == null || region == null) {
return;
}
Bounds bounds = pNnode.getBoundsInLocal();
region.setPrefSize(bounds.getWidth() - 2 * margin, bounds.getHeight() - 2 * margin);
LocateTools.moveCenter(pNnode, region);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/HelpTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/HelpTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
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.ColorQueryController;
import mara.mybox.controller.WebBrowserController;
import mara.mybox.data.ImageItem;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.menu.MenuTools;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.HtmlWriteTools;
import mara.mybox.tools.MarkdownTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.AppValues.JavaVersion;
import mara.mybox.value.AppVariables;
import mara.mybox.value.InternalImages;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-8-8
* @License Apache License Version 2.0
*/
public class HelpTools {
public static void readMe(BaseController controller) {
try {
File htmlFile = makeReadMe(Languages.embedFileLang());
if (htmlFile == null) {
return;
}
PopTools.browseURI(controller, htmlFile.toURI());
SoundTools.miao5();
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static File makeReadMe(String fileLang) {
try {
File htmlFile = new File(AppVariables.MyboxDataPath + "/doc/readme_" + fileLang + ".html");
File mdFile = FxFileTools.getInternalFile("/doc/" + fileLang + "/README.md",
"doc", "README-" + fileLang + ".md", true);
String html = MarkdownTools.md2html(null,
MarkdownTools.htmlOptions(), mdFile, HtmlStyles.DefaultStyle);
if (html == null) {
return null;
}
html = html.replaceAll("href=\"", "target=_blank href=\"");
TextFileTools.writeFile(htmlFile, html);
return htmlFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutColor() {
try {
StringTable table = new StringTable(null, message("ResourcesAboutColor"));
table.newLinkRow(message("ICCWebsite"), "http://www.color.org");
table.newLinkRow(message("ICCProfileTags"), "https://sno.phy.queensu.ca/~phil/exiftool/TagNames/ICC_Profile.html");
table.newLinkRow(message("IccProfilesECI"), "http://www.eci.org/en/downloads");
table.newLinkRow(message("IccProfilesAdobe"), "https://supportdownloads.adobe.com/detail.jsp?ftpID=3680");
table.newLinkRow(message("ColorSpace"), "http://brucelindbloom.com/index.html?WorkingSpaceInfo.html#Specifications");
table.newLinkRow(message("StandardsRGB"), "https://www.w3.org/Graphics/Color/sRGB.html");
table.newLinkRow(message("RGBXYZMatrices"), "http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html");
table.newLinkRow(message("ColorCalculator"), "http://www.easyrgb.com/en/math.php");
table.newLinkRow("", "http://brucelindbloom.com/index.html?ColorCalculator.html");
table.newLinkRow("", "http://davengrace.com/cgi-bin/cspace.pl");
table.newLinkRow(message("ColorData"), "https://www.rit.edu/science/pocs/useful-data");
table.newLinkRow("", "http://www.thefullwiki.org/Standard_illuminant");
table.newLinkRow(message("ColorTopics"), "https://www.codeproject.com/Articles/1202772/Color-Topics-for-Programmers");
table.newLinkRow("", "https://www.w3.org/TR/css-color-4/#lab-to-rgb");
table.newLinkRow(message("ChromaticAdaptation"), "http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html");
table.newLinkRow(message("ChromaticityDiagram"), "http://demonstrations.wolfram.com/CIEChromaticityDiagram/");
table.newLinkRow(message("ArtHuesWheel"), "https://blog.csdn.net/weixin_44938037/article/details/90599711");
table.newLinkRow("", "https://stackoverflow.com/questions/4945457/conversion-between-rgb-and-ryb-color-spaces");
table.newLinkRow("", "https://math.stackexchange.com/questions/305395/ryb-and-rgb-color-space-conversion");
table.newLinkRow("", "http://bahamas10.github.io/ryb/about.html");
table.newLinkRow("", "https://redyellowblue.org/ryb-color-model/");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutDataAnalysis() {
try {
StringTable table = new StringTable(null, message("AboutDataAnalysis"));
table.newLinkRow(message("Dataset"), "http://archive.ics.uci.edu/ml/datasets.php");
table.newLinkRow("", "https://www4.stat.ncsu.edu/~boos/var.select/");
table.newLinkRow("", "http://lib.stat.cmu.edu/datasets/");
table.newLinkRow("", "http://yann.lecun.com/exdb/mnist/");
table.newLinkRow("", "https://docs.microsoft.com/en-us/azure/open-datasets/");
table.newLinkRow("", "https://github.com/tomsharp/SVR/tree/master/data");
table.newLinkRow("", "https://github.com/krishnaik06/simple-Linear-Regression");
table.newLinkRow("", "https://github.com/susanli2016/Machine-Learning-with-Python/tree/master/data");
table.newLinkRow("", "https://www.datarepository.movebank.org");
table.newLinkRow("", "https://github.com/CSSEGISandData/COVID-19");
table.newLinkRow("", "https://data.stats.gov.cn/index.htm");
table.newLinkRow("Apache-Math", "https://commons.apache.org/proper/commons-math/");
table.newLinkRow("", "https://commons.apache.org/proper/commons-math/apidocs/index.html");
table.newLinkRow(message("Study"), "https://github.com/InfolabAI/DeepLearning");
table.newLinkRow("", "https://www.deeplearningbook.org/");
table.newLinkRow("", "https://github.com/zsdonghao/deep-learning-book");
table.newLinkRow("", "https://github.com/hadrienj/deepLearningBook-Notes");
table.newLinkRow("", "https://github.com/janishar/mit-deep-learning-book-pdf");
table.newLinkRow("", "https://clauswilke.com/dataviz/");
table.newLinkRow("", "https://www.kancloud.cn/apachecn/dataviz-zh/1944809");
table.newLinkRow("", "https://www.bilibili.com/video/BV1Ua4y1e7YG");
table.newLinkRow("", "https://www.bilibili.com/video/BV1i7411d7aP");
table.newLinkRow("", "https://github.com/fengdu78/Coursera-ML-AndrewNg-Notes");
table.newLinkRow(message("Tools"), "https://scikit-learn.org/stable/");
table.newLinkRow("", "https://www.mathworks.com/help/index.html");
table.newLinkRow(message("Example"), "https://www.xycoon.com/simple_linear_regression.htm");
table.newLinkRow("", "https://www.scribbr.com/statistics/simple-linear-regression/");
table.newLinkRow("", "http://www.datasetsanalysis.com/regressions/simple-linear-regression.html");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutCoordinateSystem() {
try {
StringTable table = new StringTable(null, message("AboutCoordinateSystem"));
table.newLinkRow(message("ChinaCommonGeospatialInformationServices"), "https://www.tianditu.gov.cn/");
table.newLinkRow("", "https://www.tianditu.gov.cn/world_coronavirusmap/");
table.newLinkRow(message("ChineseCoordinateSystems"), "https://politics.stackexchange.com/questions/40991/why-must-chinese-maps-be-obfuscated");
table.newLinkRow("", "https://zhuanlan.zhihu.com/p/62243160");
table.newLinkRow("", "https://blog.csdn.net/qq_36377037/article/details/86479796");
table.newLinkRow("", "https://www.zhihu.com/question/31204062?sort=created");
table.newLinkRow("", "https://blog.csdn.net/ssxueyi/article/details/102622156");
table.newLinkRow(message("EPSGCodes"), "http://epsg.io/4490");
table.newLinkRow("", "http://epsg.io/4479");
table.newLinkRow("", "http://epsg.io/4326");
table.newLinkRow("", "http://epsg.io/3857");
table.newLinkRow(message("TrackingData"), "https://www.microsoft.com/en-us/download/details.aspx?id=52367");
table.newLinkRow("", "https://www.datarepository.movebank.org/discover");
table.newLinkRow("", "https://sumo.dlr.de/docs/Data/Scenarios/TAPASCologne.html");
table.newLinkRow("", "https://blog.csdn.net/souvenir001/article/details/52180335");
table.newLinkRow("", "https://www.cnblogs.com/genghenggao/p/9625511.html");
table.newLinkRow(message("TianDiTuAPI"), "http://lbs.tianditu.gov.cn/api/js4.0/guide.html");
table.newLinkRow(message("TianDiTuKey"), "https://console.tianditu.gov.cn/api/key");
table.newLinkRow(message("GaoDeAPI"), "https://lbs.amap.com/api/javascript-api/summary");
table.newLinkRow(message("GaoDeKey"), "https://console.amap.com/dev/index");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutMedia() {
try {
StringTable table = new StringTable(null, message("AboutMedia"));
table.newLinkRow(message("FFmpegDocuments"), "http://ffmpeg.org/documentation.html");
table.newLinkRow(message("FFmpeg wiki"), "https://trac.ffmpeg.org");
table.newLinkRow(message("H264VideoEncodingGuide"), "http://trac.ffmpeg.org/wiki/Encode/H.264");
table.newLinkRow(message("AACEncodingGuide"), "https://trac.ffmpeg.org/wiki/Encode/AAC");
table.newLinkRow(message("UnderstandingRateControlModes"), "https://slhck.info/video/2017/03/01/rate-control.html");
table.newLinkRow(message("CRFGuide"), "https://slhck.info/video/2017/02/24/crf-guide.html");
table.newLinkRow(message("CapturingDesktopScreenRecording"), "http://trac.ffmpeg.org/wiki/Capture/Desktop");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutMacro() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_macro_" + lang + ".html",
"doc", "mybox_about_macro_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutData2D() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_data2d_" + lang + ".html",
"doc", "mybox_about_data2d_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutGroupingRows() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_grouping_" + lang + ".html",
"doc", "mybox_about_grouping_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutRowExpression() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_row_expression_" + lang + ".html",
"doc", "mybox_about_row_expression_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutTreeInformation() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_tree_" + lang + ".html",
"doc", "mybox_about_tree_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutImageScope() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_image_scope_" + lang + ".html",
"doc", "mybox_about_image_scope_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static void imageStories(BaseController controller) {
FxTask task = new FxTask<Void>(controller) {
private File htmFile;
@Override
protected boolean handle() {
htmFile = imageStories(this, false, AppVariables.CurrentLangName);
return htmFile != null && htmFile.exists();
}
@Override
protected void whenSucceeded() {
controller.browse(htmFile);
}
};
controller.start(task);
}
public static File imageStories(FxTask task, boolean isRemote, String lang) {
try {
StringTable table = new StringTable(null, message(lang, "StoriesOfImages"));
List<ImageItem> imageItems = InternalImages.all(lang);
for (ImageItem item : imageItems) {
String comments = item.getComments();
File file = item.getFile();
if (comments == null || comments.isBlank()
|| file == null || !file.exists()) {
continue;
}
task.setInfo(file.getAbsolutePath());
table.newNameValueRow(
"<Img src='" + (isRemote
? "https://mara-mybox.sourceforge.io/images/" + file.getName()
: file.toURI().toString())
+ "' width=" + item.getWidth() + ">",
comments);
}
String html = HtmlWriteTools.html(table.getTitle(), "utf-8",
HtmlStyles.styleValue("Table"), table.body());
File file = new File(FileTmpTools.generatePath("html")
+ "/MyBox-StoriesOfImages-" + lang + ".html");
return TextFileTools.writeFile(file, html);
} catch (Exception e) {
task.setError(e.toString());
return null;
}
}
public static File usefulLinks(String lang) {
try {
StringTable table = new StringTable(null, message(lang, "Links"));
table.newLinkRow(message(lang, "DecimalFormat"), decimalFormatLink());
table.newLinkRow(message(lang, "DateFormat"), simpleDateFormatLink());
table.newLinkRow(message(lang, "Charset"), charsetLink());
table.newLinkRow(message(lang, "Color"), colorLink());
table.newLinkRow("URI", uriLink());
table.newLinkRow("URL", urlLink());
table.newLinkRow("Full list of Math functions", javaMathLink());
table.newLinkRow("Learning the Java Language", javaLink());
table.newLinkRow("Java Development Kit (JDK) APIs", javaAPILink());
table.newLinkRow(message(lang, "JavafxCssGuide"), javaFxCssLink());
table.newLinkRow(message(lang, "DerbyReferenceManual"), derbyLink());
table.newLinkRow(message(lang, "SqlIdentifier"), sqlLink());
table.newLinkRow(message(lang, "HtmlTutorial") + " - " + message(lang, "Chinese"), htmlZhLink());
table.newLinkRow(message(lang, "HtmlTutorial") + " - " + message(lang, "English"), htmlEnLink());
table.newLinkRow(message(lang, "JavaScriptTutorial") + " - " + message(lang, "Chinese"), javaScriptZhLink());
table.newLinkRow(message(lang, "JavaScriptTutorial") + " - " + message(lang, "English"), javaScriptEnLink());
table.newLinkRow("JavaScript language specification", javaScriptSpecification());
table.newLinkRow("Nashorn User's Guide", nashornLink());
table.newLinkRow(message(lang, "CssTutorial") + " - " + message(lang, "Chinese"), cssZhLink());
table.newLinkRow(message(lang, "CssTutorial") + " - " + message(lang, "English"), cssEnLink());
table.newLinkRow(message(lang, "CssReference"), cssSpecificationLink());
table.newLinkRow("RenderingHints", renderingHintsLink());
table.newLinkRow(message(lang, "JsonTutorial") + " - " + message(lang, "Chinese"), jsonZhLink());
table.newLinkRow(message(lang, "JsonTutorial") + " - " + message(lang, "English"), jsonEnLink());
table.newLinkRow(message(lang, "JsonSpecification"), jsonSpecification());
table.newLinkRow(message(lang, "XmlTutorial") + " - " + message(lang, "Chinese"), xmlZhLink());
table.newLinkRow(message(lang, "XmlTutorial") + " - " + message(lang, "English"), xmlEnLink());
table.newLinkRow(message(lang, "DomSpecification"), domSpecification());
table.newLinkRow(message(lang, "SvgTutorial") + " - " + message(lang, "Chinese"), svgZhLink());
table.newLinkRow(message(lang, "SvgTutorial") + " - " + message(lang, "English"), svgEnLink());
table.newLinkRow(message(lang, "SvgSpecification"), svgSpecification());
table.newLinkRow("SVGPath in JavaFX", javafxSVGPathLink());
table.newLinkRow("Shape 2D in JavaFX", javafxShape2DLink());
table.newLinkRow("Shape 2D in Java", javaShape2DLink());
String html = HtmlWriteTools.html(message(lang, "Links"), HtmlStyles.DefaultStyle, table.div());
File file = new File(FileTmpTools.generatePath("html")
+ "/mybox_useful_link_" + lang + ".html");
return TextFileTools.writeFile(file, html);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File makeInterfaceTips(String lang) {
try {
StringBuilder s = new StringBuilder();
s.append("<BODY>\n");
s.append("<H1>").append(message(lang, "DocumentTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "PdfView")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PdfViewTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MarkdownEditer")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MarkdownEditerTips"))).append("\n");
s.append(" <H3>").append(message(lang, "HtmlEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HtmlFormatTips"))).append("\n");
s.append(" <H3>").append(message(lang, "HtmlSnap")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HtmlSnapComments"))).append("\n");
s.append(" <H3>").append(message(lang, "JsonEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JsonEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "XmlEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "XmlEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextEditer")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextEditerTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Charset")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "EncodeComments"))).append("\n");
s.append(" <H3>").append("BOM").append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BOMcomments"))).append("\n");
s.append(" <H3>").append(message(lang, "FindReplace")).append(" - ").append(message(lang, "Texts")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FindReplaceTextsTips"))).append("\n");
s.append(" <H3>").append(message(lang, "FindReplace")).append(" - ").append(message(lang, "Bytes")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FindReplaceBytesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "FilterLines")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FilterTypesComments"))).append("\n");
s.append(" <H3>").append(message(lang, "TextFindBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextFindBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextReplaceBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextReplaceBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextToHtml")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PasteTextAsHtml"))).append("\n");
s.append(" <H3>").append(message(lang, "BytesFindBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BytesFindBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextInMyBoxClipboard")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextClipboardUseComments"))).append("</BR>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextInMyBoxClipboardTips"))).append("\n");
s.append(" <H3>").append(message(lang, "WordView")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WordViewTips"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "ImageTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "EditImage")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageEditTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SVGEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SVGEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageQuantization")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageQuantizationComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Dithering")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DitherComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ColorMatching")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColorMatchComments"))).append("\n");
s.append(" <H3>").append(message(lang, "PremultipliedAlpha")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PremultipliedAlphaTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Thresholding")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageThresholdingComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Contrast")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageContrastComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Shear")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageShearComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageRepeatTile")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageRepeatTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageSample")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageSampleTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageSplit")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageSplitTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImagesEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesPlay")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImagesPlayTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageOCR")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageOCRComments"))).append("</BR>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "OCRPreprocessComment"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageAlphaExtract")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageAlphaExtractTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageToSvg")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SvgFromImageComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesInSystemClipboard")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "RecordImagesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ManageColors")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColorsManageTips"))).append("\n");
s.append(" <H3>").append(message(lang, "DrawChromaticityDiagram")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ChromaticityDiagramTips"))).append("\n");
s.append(" <H3>").append(message(lang, "IccProfileEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "IccProfileTips"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "NetworkTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "DownloadHtmls")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DownloadFirstLevelLinksComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ConvertUrl")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ConvertUrlTips"))).append("\n");
s.append(" <H3>").append(message(lang, "QueryDNSBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "QueryDNSBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "WeiboSnap")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WeiboAddressComments"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "DataTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "Column")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColumnComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ManageData")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataManageTips"))).append("\n");
s.append(" <H3>").append(message(lang, "DatabaseTable")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataTableTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SqlIdentifier")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SqlIdentifierComments"))).append("\n");
s.append(" <H3>").append(message(lang, "XYChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataChartXYTips"))).append("\n");
s.append(" <H3>").append(message(lang, "PieChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataChartPieTips"))).append("\n");
s.append(" <H3>").append(message(lang, "BoxWhiskerChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BoxWhiskerChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ComparisonBarsChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ComparisonBarsChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SelfComparisonBarsChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SelfComparisonBarsChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "XYZChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WebglComments"))).append("\n");
s.append(" <H3>").append(message(lang, "SetStyles")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SetStylesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SimpleLinearRegression")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SimpleLinearRegressionTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SimpleLinearRegressionCombination")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SimpleLinearRegressionCombinationTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MultipleLinearRegression")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MultipleLinearRegressionTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MultipleLinearRegressionCombination")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MultipleLinearRegressionCombinationTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Matrix")).append("</H3>\n");
s.append(" <H4>").append(message(lang, "Plus")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesPlusComments"))).append("\n");
s.append(" <H4>").append(message(lang, "Minus")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesMinusComments"))).append("\n");
s.append(" <H4>").append(message(lang, "Multiply")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesMultiplyComments"))).append("\n");
s.append(" <H4>").append(message(lang, "HadamardProduct")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HadamardProductComments"))).append("\n");
s.append(" <H4>").append(message(lang, "KroneckerProduct")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "KroneckerProductComments"))).append("\n");
s.append(" <H4>").append(message(lang, "VerticalMerge")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "VerticalMergeComments"))).append("\n");
s.append(" <H4>").append(message(lang, "HorizontalMerge")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HorizontalMergeComments"))).append("\n");
s.append("\n");
s.append(" <H3>").append(message(lang, "JavaScript")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JavaScriptTips"))).append("\n");
s.append(" <H3>").append(message(lang, "JShell")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JShellTips"))).append("\n");
| 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/fxml/RecentVisitMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/RecentVisitMenu.java | package mara.mybox.fxml;
import mara.mybox.fxml.menu.MenuTools;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.stage.FileChooser;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Files;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.db.data.VisitHistoryTools;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @License Apache License Version 2.0
*/
public abstract class RecentVisitMenu {
protected BaseController controller;
protected Event event;
protected List<String> examples;
protected int SourceFileType, SourcePathType, AddFileType, AddPathType, TargetFileType, TargetPathType;
protected List<FileChooser.ExtensionFilter> sourceExtensionFilter;
protected String baseName, defaultPath;
protected boolean onlyPath;
public RecentVisitMenu() {
}
public RecentVisitMenu(BaseController_Files controller, Event event, boolean onlyPath) {
this.controller = (BaseController) controller;
this.event = event;
this.baseName = controller.getBaseName();
this.onlyPath = onlyPath;
SourceFileType = controller.getSourceFileType();
SourcePathType = controller.getSourcePathType();
AddFileType = controller.getAddFileType();
AddPathType = controller.getAddPathType();
TargetFileType = controller.getTargetFileType();
TargetPathType = controller.getTargetPathType();
if (AddFileType <= 0) {
AddFileType = SourceFileType;
}
}
public RecentVisitMenu setFileType(int fileType) {
SourceFileType = fileType;
SourcePathType = fileType;
TargetFileType = fileType;
TargetPathType = fileType;
AddFileType = fileType;
AddPathType = fileType;
return this;
}
public void pop() {
try {
if (controller == null || event == null) {
return;
}
List<MenuItem> items = menu();
controller.popEventMenu(event, items);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public List<MenuItem> menu() {
try {
List<MenuItem> items = MenuTools.initMenu(message("SelectFile"));
MenuItem menu = new MenuItem(message("Select..."));
menu.setOnAction((ActionEvent event1) -> {
handleSelect();
});
items.add(menu);
items.add(new SeparatorMenuItem());
if (onlyPath) {
List<String> paths = paths();
if (paths != null && !paths.isEmpty()) {
menu = new MenuItem(message("RecentAccessedDirectories"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String path : paths) {
menu = new MenuItem(StringTools.menuSuffix(path));
menu.setOnAction((ActionEvent event1) -> {
handlePath(path);
});
items.add(menu);
}
items.add(new SeparatorMenuItem());
}
} else {
List<VisitHistory> written = recentWrittenFiles();
if (written != null && !written.isEmpty()) {
List<String> files = new ArrayList<>();
for (VisitHistory h : written) {
String fname = h.getResourceValue();
if (!files.contains(fname)) {
files.add(fname);
}
}
if (!files.isEmpty()) {
Menu wmenu = new Menu(message("RecentWrittenFiles"));
items.add(wmenu);
for (String fname : files) {
menu = new MenuItem(StringTools.menuSuffix(fname));
menu.setOnAction((ActionEvent event1) -> {
handleFile(fname);
});
wmenu.getItems().add(menu);
}
}
}
List<String> paths = paths();
if (paths != null && !paths.isEmpty()) {
Menu pmenu = new Menu(message("RecentAccessedDirectories"));
items.add(pmenu);
for (String path : paths) {
menu = new MenuItem(StringTools.menuSuffix(path));
menu.setOnAction((ActionEvent event1) -> {
handlePath(path);
});
pmenu.getItems().add(menu);
}
}
List<VisitHistory> opened = recentOpenedFiles();
if (opened != null && !opened.isEmpty()) {
List<String> files = new ArrayList<>();
for (VisitHistory h : opened) {
String fname = h.getResourceValue();
if (!files.contains(fname)) {
files.add(fname);
}
}
if (!files.isEmpty()) {
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("RecentOpenedFiles"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String fname : files) {
menu = new MenuItem(StringTools.menuSuffix(fname));
menu.setOnAction((ActionEvent event1) -> {
handleFile(fname);
});
items.add(menu);
}
}
}
if (examples != null && !examples.isEmpty()) {
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("Examples"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String example : examples) {
menu = new MenuItem(StringTools.menuSuffix(example));
menu.setOnAction((ActionEvent event1) -> {
handleFile(example);
});
items.add(menu);
}
}
items.add(new SeparatorMenuItem());
}
items.add(MenuTools.popCheckMenu("RecentVisit"));
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public abstract void handleSelect();
public List<VisitHistory> recentFiles() {
return recentOpenedFiles();
}
public List<VisitHistory> recentPaths() {
return recentSourcePathsBesidesFiles();
}
public void handleFile(String fname) {
}
public void handlePath(String fname) {
handleSourcePath(fname);
}
public List<String> paths() {
List<VisitHistory> his = recentPaths();
List<String> paths = new ArrayList<>();
if (his != null) {
for (VisitHistory h : his) {
String pathname = h.getResourceValue();
if (!paths.contains(pathname)) {
paths.add(pathname);
}
}
}
if (defaultPath != null && !paths.contains(defaultPath)) {
paths.add(defaultPath);
}
File lastPath = UserConfig.getPath("LastPath");
if (lastPath != null) {
String lastPathString = lastPath.getAbsolutePath();
if (!paths.contains(lastPathString)) {
paths.add(lastPathString);
}
}
return paths;
}
public List<VisitHistory> recentOpenedFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileRead(SourceFileType, fileNumber);
}
public List<VisitHistory> recentWrittenFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileWrite(SourceFileType, fileNumber);
}
public List<VisitHistory> recentAddFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileRead(AddFileType, fileNumber);
}
public List<VisitHistory> recentSourcePathsBesidesFiles() {
int pathNumber = AppVariables.fileRecentNumber;
if (pathNumber == 0) {
pathNumber = 1;
}
return VisitHistoryTools.getRecentPathRead(SourcePathType, pathNumber);
}
public List<VisitHistory> recentTargetPathsBesidesFiles() {
int pathNumber = AppVariables.fileRecentNumber;
if (pathNumber == 0) {
pathNumber = 1;
}
return VisitHistoryTools.getRecentPathWrite(TargetPathType, pathNumber);
}
public List<VisitHistory> recentSourcePaths() {
return VisitHistoryTools.getRecentPathRead(SourcePathType);
}
public List<VisitHistory> recentTargetPaths() {
return VisitHistoryTools.getRecentPathWrite(TargetPathType);
}
public void handleSourcePath(String fname) {
File file = new File(fname);
if (!file.exists()) {
handleSelect();
return;
}
UserConfig.setString(baseName + "SourcePath", fname);
handleSelect();
}
public void handleTargetPath(String fname) {
File file = new File(fname);
if (!file.exists()) {
handleSelect();
return;
}
UserConfig.setString(baseName + "TargetPath", fname);
handleSelect();
}
/*
get/set
*/
public List<String> getExamples() {
return examples;
}
public RecentVisitMenu setExamples(List<String> examples) {
this.examples = examples;
return this;
}
public int getSourceFileType() {
return SourceFileType;
}
public RecentVisitMenu setSourceFileType(int SourceFileType) {
this.SourceFileType = SourceFileType;
return this;
}
public int getSourcePathType() {
return SourcePathType;
}
public RecentVisitMenu setSourcePathType(int SourcePathType) {
this.SourcePathType = SourcePathType;
return this;
}
public int getAddFileType() {
return AddFileType;
}
public RecentVisitMenu setAddFileType(int AddFileType) {
this.AddFileType = AddFileType;
return this;
}
public int getAddPathType() {
return AddPathType;
}
public RecentVisitMenu setAddPathType(int AddPathType) {
this.AddPathType = AddPathType;
return this;
}
public int getTargetPathType() {
return TargetPathType;
}
public RecentVisitMenu setTargetPathType(int TargetPathType) {
this.TargetPathType = TargetPathType;
return this;
}
public List<FileChooser.ExtensionFilter> getSourceExtensionFilter() {
return sourceExtensionFilter;
}
public RecentVisitMenu setSourceExtensionFilter(List<FileChooser.ExtensionFilter> sourceExtensionFilter) {
this.sourceExtensionFilter = sourceExtensionFilter;
return this;
}
public String getDefaultPath() {
return defaultPath;
}
public RecentVisitMenu setDefaultPath(String defaultPath) {
this.defaultPath = defaultPath;
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/fxml/SoundTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/SoundTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.Arrays;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Mixer;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2018-7-12
* @License Apache License Version 2.0
*/
public class SoundTools {
public static void audioSystem() {
Mixer.Info[] infos = AudioSystem.getMixerInfo();
for (Mixer.Info info : infos) {
MyBoxLog.debug(info.getName() + " " + info.getVendor() + " " + info.getVersion() + " " + info.getDescription());
}
AudioFileFormat.Type[] formats = AudioSystem.getAudioFileTypes();
MyBoxLog.debug(Arrays.asList(formats).toString());
}
public static void miao6() {
playClip("/sound/guaiMiao6.mp3", "guaiMiao6.mp3");
}
public static void GuaiAO() {
playClip("/sound/GuaiAO.mp3", "GuaiAO.mp3");
}
public static void mp3(File file) {
playClip(file);
}
public static void miao5() {
playClip("/sound/guaiMiao5.mp3", "guaiMiao5.mp3");
}
public static void miao3() {
playClip("/sound/guaiMiao3.mp3", "guaiMiao3.mp3");
}
public static void miao2() {
playClip("/sound/guaiMiao2.mp3", "guaiMiao2.mp3");
}
public static void miao7() {
playClip("/sound/guaiMiao7.mp3", "guaiMiao7.mp3");
}
public static void BenWu() {
playClip("/sound/BenWu.mp3", "BenWu.mp3");
}
public static void BenWu2() {
playClip("/sound/BenWu2.mp3", "BenWu2.mp3");
}
public static void playSound(final String file, final String userFile) {
File miao = FxFileTools.getInternalFile(file, "sound", userFile);
play(miao, 1, 1);
}
public static void playClip(final String file, final String userFile) {
File sound = FxFileTools.getInternalFile(file, "sound", userFile);
playClip(sound);
}
public static void playClip(File file) {
FxTask miaoTask = new FxTask<Void>() {
@Override
protected boolean handle() {
try {
AudioClip plonkSound = new AudioClip(file.toURI().toString());
plonkSound.play();
} catch (Exception e) {
}
return true;
}
};
Thread thread = new Thread(miaoTask);
thread.setDaemon(false);
thread.start();
}
public static MediaPlayer play(File file, double volumn, int cycle) {
return play(file.toURI().toString(), volumn, cycle);
}
public static MediaPlayer play(String address, double volumn, int cycle) {
MediaPlayer mp = new MediaPlayer(new Media(address));
mp.setVolume(volumn);
mp.setCycleCount(cycle);
mp.setAutoPlay(true);
return mp;
}
public static void audio(File file) {
audio(file, 1, 1);
}
public static void audio(File file, double volumn, int cycle) {
AudioClip clip = new AudioClip(file.toURI().toString());
clip.setVolume(volumn);
clip.setCycleCount(cycle);
clip.play();
}
public static AudioClip clip(File file, double volumn) {
AudioClip clip = new AudioClip(file.toURI().toString());
clip.setVolume(volumn);
return clip;
}
}
| 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/fxml/image/ShapeTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ShapeTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.image.data.ImageMosaic;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.data.DoublePolylines;
import mara.mybox.data.DoubleShape;
import mara.mybox.data.ShapeStyle;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ShapeTools {
public static Image drawShape(FxTask task, Image image, DoubleShape shape, ShapeStyle style, PixelsBlend blender) {
if (shape == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawShape(task, source, shape, style, blender);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image drawErase(FxTask task, Image image, DoublePolylines penData, ShapeStyle style) {
if (penData == null || style == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawErase(task, source, penData, style);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image drawMosaic(FxTask task, Image image, DoublePolylines penData,
ImageMosaic.MosaicType mosaicType, int strokeWidth, int intensity) {
if (penData == null || mosaicType == null || strokeWidth < 1) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawMosaic(task, source, penData, mosaicType, strokeWidth, intensity);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/FxImageTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/FxImageTools.java | package mara.mybox.fxml.image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.Random;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.ImageInput;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.data.DoubleShape;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.image.FxColorTools.toAwtColor;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
/**
* @Author Mara
* @CreateDate 2018-6-11 11:19:42
* @License Apache License Version 2.0
*/
public class FxImageTools {
public class ManufactureType {
public static final int Brighter = 0;
public static final int Darker = 1;
public static final int Gray = 2;
public static final int Invert = 3;
public static final int Saturate = 4;
public static final int Desaturate = 5;
}
public static Image createImage(int width, int height, Color color) {
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < newImage.getHeight(); y++) {
for (int x = 0; x < newImage.getWidth(); x++) {
pixelWriter.setColor(x, y, color);
}
}
return newImage;
}
public static Image readImage(FxTask task, File file) {
BufferedImage bufferedImage = ImageFileReaders.readImage(task, file);
if (bufferedImage == null) {
return null;
}
return SwingFXUtils.toFXImage(bufferedImage, null);
}
public static File writeImage(FxTask task, Image image) {
if (image == null) {
return null;
}
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
if (bufferedImage == null) {
return null;
}
File tmpFile = FileTmpTools.getTempFile(".png");
if (ImageFileWriters.writeImageFile(task, bufferedImage, "png", tmpFile.getAbsolutePath())
&& tmpFile.exists()) {
return tmpFile;
} else {
return null;
}
}
public static byte[] bytes(FxTask task, Image image, String format) {
return BufferedImageTools.bytes(task, SwingFXUtils.fromFXImage(image, null), format);
}
public static String base64(FxTask task, File file, String format) {
try {
BufferedImage bufferedImage = ImageFileReaders.readImage(task, file);
if (bufferedImage == null) {
return null;
}
return BufferedImageTools.base64(task, bufferedImage, format);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static String base64(FxTask task, Image image, String format) {
try {
if (image == null || format == null) {
return null;
}
return BufferedImageTools.base64(task, SwingFXUtils.fromFXImage(image, null), format);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image clone(FxTask task, Image srcImage) {
if (srcImage == null) {
return srcImage;
}
double w = srcImage.getWidth();
double h = srcImage.getHeight();
PixelReader pixelReader = srcImage.getPixelReader();
WritableImage newImage = new WritableImage((int) w, (int) h);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
}
}
return newImage;
}
// This way may be more quicker than comparing digests
public static boolean sameImage(FxTask task, Image imageA, Image imageB) {
try {
if (imageA == null || imageB == null
|| imageA.getWidth() != imageB.getWidth()
|| imageA.getHeight() != imageB.getHeight()) {
return false;
}
int width = (int) imageA.getWidth(), height = (int) imageA.getHeight();
PixelReader readA = imageA.getPixelReader();
PixelReader readB = imageB.getPixelReader();
for (int y = 0; y < height / 2; y++) {
if (task != null && !task.isWorking()) {
return false;
}
for (int x = 0; x < width / 2; x++) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
for (int x = width - 1; x >= width / 2; x--) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
}
for (int y = height - 1; y >= height / 2; y--) {
if (task != null && !task.isWorking()) {
return false;
}
for (int x = 0; x < width / 2; x++) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
for (int x = width - 1; x >= width / 2; x--) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
// https://stackoverflow.com/questions/19548363/image-saved-in-javafx-as-jpg-is-pink-toned
public static BufferedImage toBufferedImage(Image image) {
if (image == null) {
return null;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
return source;
}
public static BufferedImage checkAlpha(FxTask task, Image image, String format) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = AlphaTools.checkAlpha(task, source, format);
return target;
}
public static Image clearAlpha(FxTask task, Image image) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = AlphaTools.removeAlpha(task, source);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
// This way may fail for big image
public static Image addTextFx(Image image, String textString,
Font font, Color color, int x, int y, float transparent, int shadow) {
try {
Group group = new Group();
Text text = new Text(x, y, textString);
text.setFill(color);
text.setFont(font);
if (shadow > 0) {
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetX(shadow);
dropShadow.setOffsetY(shadow);
text.setEffect(dropShadow);
}
group.getChildren().add(text);
Blend blend = new Blend(BlendMode.SRC_OVER);
blend.setBottomInput(new ImageInput(image));
blend.setOpacity(1.0 - transparent);
group.setEffect(blend);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage newImage = group.snapshot(parameters, null);
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image setRound(FxTask task, Image image, int roundX, int roundY, Color bgColor) {
if (image == null || roundX <= 0 || roundY <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.setRound(task, source, roundX, roundY, toAwtColor(bgColor));
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image addShadow(FxTask task, Image image, int offsetX, int offsetY, Color color, boolean isBlur) {
if (image == null || color == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.addShadow(task, source, offsetX, offsetY, toAwtColor(color), isBlur);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image blend(FxTask task, Image foreImage, Image backImage,
int x, int y, PixelsBlend blender) {
if (foreImage == null || backImage == null || blender == null) {
return null;
}
BufferedImage source1 = SwingFXUtils.fromFXImage(foreImage, null);
BufferedImage source2 = SwingFXUtils.fromFXImage(backImage, null);
BufferedImage target = PixelsBlend.blend(task, source1, source2, x, y, blender);
if (target == null) {
target = source1;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image makeMosaic(FxTask task, Image image, DoubleShape shape, int size,
boolean isMosaic, boolean isExcluded) {
if (!shape.isValid()) {
return image;
}
int w = (int) image.getWidth();
int h = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(w, h);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < h; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < w; x++) {
if (task != null && !task.isWorking()) {
return null;
}
if (isExcluded) {
if (DoubleShape.contains(shape, x, y)) {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
} else {
if (isMosaic) {
int mx = Math.max(0, Math.min(w - 1, x - x % size));
int my = Math.max(0, Math.min(h - 1, y - y % size));
pixelWriter.setColor(x, y, pixelReader.getColor(mx, my));
} else {
int fx = Math.max(0, Math.min(w - 1, x - new Random().nextInt(size)));
int fy = Math.max(0, Math.min(h - 1, y - new Random().nextInt(size)));
pixelWriter.setColor(x, y, pixelReader.getColor(fx, fy));
}
}
} else {
if (DoubleShape.contains(shape, x, y)) {
if (isMosaic) {
int mx = Math.max(0, Math.min(w - 1, x - x % size));
int my = Math.max(0, Math.min(h - 1, y - y % size));
pixelWriter.setColor(x, y, pixelReader.getColor(mx, my));
} else {
int fx = Math.max(0, Math.min(w - 1, x - new Random().nextInt(size)));
int fy = Math.max(0, Math.min(h - 1, y - new Random().nextInt(size)));
pixelWriter.setColor(x, y, pixelReader.getColor(fx, fy));
}
} else {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
}
}
}
}
return newImage;
}
public static Image replaceColor(FxTask task, Image image, Color oldColor, Color newColor, int distance) {
if (image == null || oldColor == null || newColor == null || distance < 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = PixelsOperationFactory.replaceColor(task, source,
ColorConvertTools.converColor(oldColor), ColorConvertTools.converColor(newColor), distance);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image applyRenderHints(Image image, Map<RenderingHints.Key, Object> hints) {
if (image == null || hints == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.applyRenderHints(source, hints);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/TransformTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/TransformTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class TransformTools {
public static Image horizontalImage(FxTask task, Image image) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
int l = 0;
int r = width - 1;
while (l <= r) {
if (task != null && !task.isWorking()) {
return null;
}
Color cl = pixelReader.getColor(l, j);
Color cr = pixelReader.getColor(r, j);
pixelWriter.setColor(l, j, cr);
pixelWriter.setColor(r, j, cl);
l++;
r--;
}
}
return newImage;
}
public static Image verticalImage(FxTask task, Image image) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
int t = 0;
int b = height - 1;
while (t <= b) {
if (task != null && !task.isWorking()) {
return null;
}
Color ct = pixelReader.getColor(i, t);
Color cb = pixelReader.getColor(i, b);
pixelWriter.setColor(i, t, cb);
pixelWriter.setColor(i, b, ct);
t++;
b--;
}
}
return newImage;
}
public static Image rotateImage(FxTask task, Image image, int angle, boolean cutMargins) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.TransformTools.rotateImage(task, source, angle, cutMargins);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image shearImage(FxTask task, Image image, float shearX, float shearY, boolean cutMargins) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.TransformTools.shearImage(task, source, shearX, shearY, cutMargins);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/ImageDemos.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ImageDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.TransformTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ImageDemos {
public static void shear(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Shear");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = TransformTools.shearImage(demoTask, demoImage, 1f, 0, true);
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, "radio_(1,0)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -1f, 0, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-1,0)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 0, 1f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(0,1)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 0, -1f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(0,-1)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 1.5f, 2, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(1.5,2)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 2, -1.5f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(2,-1.5)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -1.5f, 2, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-1.5,2)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -2, -1.5f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-2,-1.5)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void round(FxTask demoTask, List<String> files,
BufferedImage demoImage, Color color, File demoFile) {
if (demoTask == null || demoImage == null || files == null || color == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Round");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
int width = demoImage.getWidth();
int height = demoImage.getHeight();
List<Integer> values = Arrays.asList(1, 2, 4, 8, 10, 20, 30);
BufferedImage bufferedImage;
String tmpFile;
for (int r : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
int v = Math.min(width / r, height / r);
bufferedImage = BufferedImageTools.setRound(demoTask, demoImage, v, v, color);
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Round") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/image/ScaleTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ScaleTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ScaleTools {
public static Image scaleImage(Image image, float scale) {
int targetW = (int) Math.round(image.getWidth() * scale);
int targetH = (int) Math.round(image.getHeight() * scale);
return scaleImage(image, targetW, targetH);
}
public static Image scaleImage(Image image, int width) {
if (width <= 0 || width == image.getWidth()) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImageWidthKeep(source, width);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image scaleImage(Image image, int width, int height) {
if (width == image.getWidth() && height == image.getHeight()) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImageBySize(source, width, height);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image scaleImage(Image image, int width, int height, boolean keepRatio, int keepType) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImage(source, width, height, keepRatio, keepType);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image demoImage(Image image) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.demoImage(source);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/FxColorTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/FxColorTools.java | package mara.mybox.fxml.image;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javafx.scene.paint.Color;
import mara.mybox.color.SRGB;
import mara.mybox.data.StringTable;
import mara.mybox.db.data.ColorData;
import mara.mybox.db.table.TableColor;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class FxColorTools {
public static Map<String, Color> WebColors, ChineseColors, JapaneseColors;
public static Map<Color, String> WebColorNames, ChineseColorNames, JapaneseColorNames;
public static int compareColor(Color o1, Color o2) {
double diff = o2.getHue() - o1.getHue();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getSaturation() - o1.getSaturation();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getBrightness() - o1.getBrightness();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getOpacity() - o1.getOpacity();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
}
}
}
}
public static String colorNameDisplay(TableColor tableColor, Color color) {
if (color == null) {
return "";
}
ColorData data = tableColor.read(color);
if (data != null) {
return data.display();
}
data = new ColorData(FxColorTools.color2rgba(color));
return data.display();
}
public static String colorDisplaySimple(Color color) {
if (color == null) {
return "";
}
String s = FxColorTools.color2rgba(color) + "\n";
s += "sRGB " + Languages.message("Red") + ":" + Math.round(color.getRed() * 255) + " "
+ Languages.message("Green") + ":" + Math.round(color.getGreen() * 255) + " "
+ Languages.message("Blue") + ":" + Math.round(color.getBlue() * 255)
+ Languages.message("Opacity") + ":" + Math.round(color.getOpacity() * 100) + "%\n";
s += "HSB " + Languages.message("Hue") + ":" + Math.round(color.getHue()) + " "
+ Languages.message("Saturation") + ":" + Math.round(color.getSaturation() * 100) + "% "
+ Languages.message("Brightness") + ":" + Math.round(color.getBrightness() * 100) + "%\n";
return s;
}
public static String color2rgb(Color color) {
return String.format("#%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
}
public static String color2RGBA(Color color) {
return String.format("#%02X%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
}
public static String color2css(Color color) {
return "rgba(" + (int) (color.getRed() * 255) + ","
+ (int) (color.getGreen() * 255) + ","
+ (int) (color.getBlue() * 255) + ","
+ color.getOpacity() + ")";
}
public static String color2hsla(Color color) {
return "hsla("
+ Math.round(color.getHue()) + ","
+ Math.round(color.getSaturation() * 100) + "%,"
+ Math.round(color.getBrightness() * 100) + "%,"
+ DoubleTools.scale2(color.getOpacity()) + ")";
}
public static String color2rgba(Color color) {
return String.format("0x%02X%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
}
public static Color value2color(int value) {
return ColorConvertTools.converColor(new java.awt.Color(value, true));
}
public static Color invert(Color color) {
return new Color(1 - color.getRed(), 1 - color.getGreen(), 1 - color.getBlue(), color.getOpacity());
}
public static boolean isLightColor(Color color) {
return color.grayscale().getRed() > 0.5;
}
public static boolean isTransparent(Color color) {
return color.equals(Color.TRANSPARENT);
}
public static Color foreColor(Color backColor) {
return isLightColor(backColor) ? Color.BLACK : Color.WHITE;
}
public static int color2Value(Color color) {
return color == null ? AppValues.InvalidInteger
: ColorConvertTools.converColor(color).getRGB();
}
public static int web2Value(String web) {
try {
return FxColorTools.color2Value(Color.web(web));
} catch (Exception e) {
return AppValues.InvalidInteger;
}
}
public static java.awt.Color toAwtColor(Color color) {
java.awt.Color newColor = new java.awt.Color((int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
return newColor;
}
public static java.awt.Color cssToAwt(String css) {
return toAwtColor(Color.web(css));
}
public static String randomRGB() {
Random random = new Random();
return randomRGB(random);
}
public static String randomRGB(Random random) {
String color = String.format("#%02X%02X%02X",
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
return color;
}
public static List<String> randomRGB(int size) {
Random random = new Random();
List<String> colors = new ArrayList<>();
if (size > 256 * 256 * 256 - 1) {
return null;
}
while (colors.size() < size) {
while (true) {
String color = randomRGB(random);
if (!colors.contains(color)) {
colors.add(color);
break;
}
}
}
return colors;
}
public static String randomRGBExcept(Collection<String> excepts) {
Random random = new Random();
while (true) {
String color = randomRGB(random);
if (!excepts.contains(color)) {
return color;
}
}
}
public static String randomRGBA() {
Random random = new Random();
return randomRGBA(random);
}
public static String randomRGBA(Random random) {
while (true) {
String color = String.format("0x%02X%02X%02X%02X",
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
if (!"0xFFFFFFFF".equals(color)) {
return color;
}
}
}
public static Color randomColor() {
return Color.web(randomRGB());
}
public static Color randomColor(Random random) {
return Color.web(randomRGB(random));
}
public static List<String> randomRGBA(int size) {
Random random = new Random();
List<String> colors = new ArrayList<>();
if (size > 256 * 256 * 256 - 1) {
return null;
}
while (colors.size() < size) {
while (true) {
String color = randomRGBA(random);
if (!colors.contains(color)) {
colors.add(color);
break;
}
}
}
return colors;
}
public static String randomRGBAExcept(Collection<String> excepts) {
Random random = new Random();
while (true) {
String color = randomRGBA(random);
if (!excepts.contains(color)) {
return color;
}
}
}
public static String color2rgb(java.awt.Color color) {
return String.format("#%02X%02X%02X",
color.getRed(), color.getGreen(), color.getBlue());
}
public static String color2css(java.awt.Color color) {
return "rgba(" + color.getRed() + ","
+ color.getGreen() + ","
+ color.getBlue() + ","
+ color.getAlpha() / 255f + ")";
}
public static String hsb2rgba(float h, float s, float b) {
return color2rgba(Color.hsb(h, s, b));
}
public static String color2AlphaHex(java.awt.Color color) {
return String.format("#%02X%02X%02X%02X",
color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue());
}
public static float[] color2srgb(Color color) {
float[] srgb = new float[3];
srgb[0] = (float) color.getRed();
srgb[1] = (float) color.getGreen();
srgb[2] = (float) color.getBlue();
return srgb;
}
public static double[] toDouble(Color color) {
double[] srgb = new double[3];
srgb[0] = color.getRed();
srgb[1] = color.getGreen();
srgb[2] = color.getBlue();
return srgb;
}
public static double[] SRGBtoAdobeRGB(Color color) {
return SRGB.SRGBtoAdobeRGB(toDouble(color));
}
public static double[] SRGBtoAppleRGB(Color color) {
return SRGB.SRGBtoAppleRGB(toDouble(color));
}
public static int calculateColorDistanceSquare(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
double redDiff = (color1.getRed() - color2.getRed()) * 255;
double greenDiff = (color1.getGreen() - color2.getGreen()) * 255;
double blueDiff = (color1.getBlue() - color2.getBlue()) * 255;
int v = (int) Math.round(2 * redDiff * redDiff + 4 * greenDiff * greenDiff + 3 * blueDiff * blueDiff);
return v;
}
// distance2 = Math.pow(distance, 2)
// distance: 0-255
public static boolean isColorMatchSquare(Color color1, Color color2, int distance2) {
if (color1 == null || color2 == null) {
return false;
}
if (color1.equals(color2)) {
return true;
} else if (distance2 == 0 || color1.equals(Color.TRANSPARENT) || color2.equals(Color.TRANSPARENT)) {
return false;
}
return calculateColorDistanceSquare(color1, color2) <= distance2;
}
public static StringTable colorsTable(StringTable table, ColorData color1, ColorData color2, ColorData color3) {
List<String> row = new ArrayList<>();
row.add(message("Color"));
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color1.getColor()) + "; \"> </DIV>");
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color2.getColor()) + "; \"> </DIV>");
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color3.getColor()) + "; \"> </DIV>");
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Name"), color1.getColorName() + "", color2.getColorName() + "", color3.getColorName() + ""));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Hue"), color1.getHue(), color2.getHue(), color3.getHue()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Saturation"), color1.getSaturation(), color2.getSaturation(), color3.getSaturation()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Brightness"), color1.getBrightness(), color2.getBrightness(), color3.getBrightness()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("RYBAngle"), color1.getRybAngle(), color2.getRybAngle(), color3.getRybAngle()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Opacity"), color1.getOpacity(), color2.getOpacity(), color3.getOpacity()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("RGBA", color1.getRgba(), color2.getRgba(), color3.getRgba()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("RGB", color1.getRgb(), color2.getRgb(), color3.getRgb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("sRGB", color1.getSrgb(), color2.getSrgb(), color3.getSrgb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("HSBA", color1.getHsb(), color2.getHsb(), color3.getHsb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("CalculatedCMYK"), color1.getCalculatedCMYK(), color2.getCalculatedCMYK(), color3.getCalculatedCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe RGB", color1.getAdobeRGB(), color2.getAdobeRGB(), color3.getAdobeRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Apple RGB", color1.getAppleRGB(), color2.getAppleRGB(), color3.getAppleRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("ECI RGB", color1.getEciRGB(), color2.getEciRGB(), color3.getEciRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("sRGB Linear", color1.getSRGBLinear(), color2.getSRGBLinear(), color3.getSRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe RGB Linear", color1.getAdobeRGBLinear(), color2.getAdobeRGBLinear(), color3.getAdobeRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Apple RGB Linear", color1.getAppleRGBLinear(), color2.getAppleRGBLinear(), color3.getAppleRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("ECI CMYK", color1.getEciCMYK(), color2.getEciCMYK(), color3.getEciCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe CMYK Uncoated FOGRA29", color1.getAdobeCMYK(), color2.getAdobeCMYK(), color3.getAdobeCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("XYZ", color1.getXyz(), color2.getXyz(), color3.getXyz()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("CIE-L*ab", color1.getCieLab(), color2.getCieLab(), color3.getCieLab()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("LCH(ab)", color1.getLchab(), color2.getLchab(), color3.getLchab()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("CIE-L*uv", color1.getCieLuv(), color2.getCieLuv(), color3.getCieLuv()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("LCH(uv)", color1.getLchuv(), color2.getLchuv(), color3.getLchuv()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Value"), color1.getColorValue() + "", color2.getColorValue() + "", color3.getColorValue() + ""));
table.add(row);
return table;
}
}
| 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/fxml/image/CropTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/CropTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class CropTools {
public static Image cropInsideFx(FxTask task, Image image, DoubleRectangle rect, Color bgColor) {
if (image == null || rect == null || rect.isEmpty() || bgColor == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.data.CropTools.cropInside(task,
source, rect, ColorConvertTools.converColor(bgColor));
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image cropOutsideFx(FxTask task, Image image, DoubleRectangle rect, Color bgColor) {
try {
if (image == null || rect == null || rect.isEmpty() || bgColor == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
if (source == null) {
return image;
}
BufferedImage target = mara.mybox.image.data.CropTools.cropOutside(task,
source, rect, ColorConvertTools.converColor(bgColor));
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
} catch (Exception e) {
MyBoxLog.debug(e);
return image;
}
}
public static Image cropOutsideFx(FxTask task, Image image, DoubleRectangle rect) {
return cropOutsideFx(task, image, rect, Color.TRANSPARENT);
}
public static Image cropOutsideFx(FxTask task, Image image, double x1, double y1, double x2, double y2) {
return cropOutsideFx(task, image, DoubleRectangle.xy12(x1, y1, x2, y2), Color.TRANSPARENT);
}
}
| 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/fxml/image/ShapeDemos.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ShapeDemos.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import mara.mybox.controller.ControlImageText;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.image.data.PixelsBlendFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.image.tools.ImageTextTools;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ShapeDemos {
public static void blendImage(FxTask currentTask, List<String> files, String op,
BufferedImage baseImage, BufferedImage overlay, int x, int y, File demoFile) {
if (currentTask == null || baseImage == null || overlay == null || files == null) {
return;
}
try {
BufferedImage baseBI = ScaleTools.demoImage(baseImage);
BufferedImage overlayBI = ScaleTools.demoImage(overlay);
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + op;
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsBlend.ImagesBlendMode mode;
PixelsBlend blender;
BufferedImage blended;
String tmpFile;
for (String name : PixelsBlendFactory.blendModes()) {
if (currentTask == null || !currentTask.isWorking()) {
return;
}
mode = PixelsBlendFactory.blendMode(name);
blender = PixelsBlendFactory.create(mode).setBlendMode(mode);
blender.setWeight(1.0F).setBaseAbove(false)
.setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity")
+ "1_" + message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("Transparent"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
}
} catch (Exception e) {
if (currentTask != null) {
currentTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void text(FxTask currentTask, List<String> files,
BufferedImage baseImage, ControlImageText optionsController, File demoFile) {
if (currentTask == null || baseImage == null || optionsController == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Text");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsBlend.ImagesBlendMode mode;
PixelsBlend blend;
BufferedImage blended;
String tmpFile;
for (String name : PixelsBlendFactory.blendModes()) {
if (currentTask == null || !currentTask.isWorking()) {
return;
}
mode = PixelsBlendFactory.blendMode(name);
blend = PixelsBlendFactory.create(mode).setBlendMode(mode);
blend.setWeight(1.0F).setBaseAbove(false).setBaseTransparentAs(
PixelsBlend.TransparentAs.Another).setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity")
+ "1_" + message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("Transparent"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
}
} catch (Exception e) {
if (currentTask != null) {
currentTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/image/ImageViewInfoTask.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ImageViewInfoTask.java | package mara.mybox.fxml.image;
import javafx.application.Platform;
import javafx.scene.control.IndexedCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-12-9
* @License Apache License Version 2.0
*/
public class ImageViewInfoTask<Void> extends FxTask<Void> {
private IndexedCell cell;
private ImageInformation item = null;
private ImageView view = null;
public ImageViewInfoTask(BaseController controller) {
this.controller = controller;
}
public ImageViewInfoTask<Void> setCell(IndexedCell cell) {
this.cell = cell;
return this;
}
public ImageViewInfoTask<Void> setItem(ImageInformation item) {
this.item = item;
return this;
}
public ImageViewInfoTask<Void> setView(ImageView view) {
this.view = view;
return this;
}
@Override
public void run() {
if (view == null || item == null) {
return;
}
int width = item.getWidth() > AppVariables.thumbnailWidth
? AppVariables.thumbnailWidth : (int) item.getWidth();
Image image = item.loadThumbnail(this, width);
if (image != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
view.setImage(image);
view.setRotate(item.getThumbnailRotation());
view.setFitWidth(width);
if (cell != null) {
cell.setGraphic(view);
}
}
});
}
}
}
| 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/fxml/image/PaletteTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/PaletteTools.java | package mara.mybox.fxml.image;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Window;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.controller.ControlColorPaletteSelector;
import mara.mybox.controller.ControlColorSet;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColorData;
import mara.mybox.db.data.ColorDataTools;
import mara.mybox.db.data.ColorPaletteName;
import mara.mybox.db.table.TableColor;
import mara.mybox.db.table.TableColorPalette;
import mara.mybox.db.table.TableColorPaletteName;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.style.StyleData;
import mara.mybox.fxml.style.StyleData.StyleColor;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Colors.color;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-11-22
* @License Apache License Version 2.0
*/
public class PaletteTools {
public static List<MenuItem> paletteExamplesMenu(BaseController parent) {
try {
List<MenuItem> menus = new ArrayList<>();
MenuItem menu;
menu = new MenuItem(defaultPaletteName(AppVariables.CurrentLangName));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, defaultPaletteName(AppVariables.CurrentLangName));
});
menus.add(menu);
menu = new MenuItem(message("WebCommonColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("WebCommonColors"));
});
menus.add(menu);
menu = new MenuItem(message("ChineseTraditionalColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ChineseTraditionalColors"));
});
menus.add(menu);
menu = new MenuItem(message("JapaneseTraditionalColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("JapaneseTraditionalColors"));
});
menus.add(menu);
menu = new MenuItem(message("HexaColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("HexaColors"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors12"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors12"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors24"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors24"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors360"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors360"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors12"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors12"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors24"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors24"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors360"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors360"));
});
menus.add(menu);
menu = new MenuItem(message("ArtPaints"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtPaints"));
});
menus.add(menu);
menu = new MenuItem(message("MyBoxColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("MyBoxColors"));
});
menus.add(menu);
menu = new MenuItem(message("GrayScale"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("GrayScale"));
});
menus.add(menu);
return menus;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void importPalette(BaseController parent, String paletteName) {
if (parent == null || paletteName == null) {
return;
}
if (parent.getTask() != null) {
parent.getTask().cancel();
}
FxTask task = new FxTask<Void>(parent) {
@Override
protected boolean handle() {
List<ColorData> colors;
String fileLang = Languages.embedFileLang();
if (defaultPaletteName(AppVariables.CurrentLangName).equals(paletteName)) {
colors = defaultColors(AppVariables.CurrentLangName);
} else if (message("WebCommonColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsWeb.csv",
"data", "ColorsWeb.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("ArtPaints").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsArtPaints.csv",
"data", "ColorsArtPaints.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("ChineseTraditionalColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsChinese.csv",
"data", "ColorsChinese.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("JapaneseTraditionalColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsJapanese.csv",
"data", "ColorsJapanese.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("HexaColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsColorhexa.csv",
"data", "ColorsColorhexa.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("MyBoxColors").equals(paletteName)) {
colors = new ArrayList<>();
for (StyleColor style : StyleData.StyleColor.values()) {
colors.add(new ColorData(color(style, true).getRGB(), message("MyBoxColor" + style.name() + "Dark")));
colors.add(new ColorData(color(style, false).getRGB(), message("MyBoxColor" + style.name() + "Light")));
}
} else if ((message("ArtHuesWheel") + "-" + message("Colors12")).equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsRYB12_" + fileLang + ".csv",
"data", "ColorsRYB12_" + fileLang + ".csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if ((message("ArtHuesWheel") + "-" + message("Colors360")).equals(paletteName)) {
colors = artHuesWheel(AppVariables.CurrentLangName, 1);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors12")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 30);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors24")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 15);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors360")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 1);
} else if ((message("GrayScale")).equals(paletteName)) {
colors = greyScales(AppVariables.CurrentLangName);
} else {
File file = FxFileTools.getInternalFile("/data/examples/ColorsRYB24_" + fileLang + ".csv",
"data", "ColorsRYB24_" + fileLang + ".csv", true);
colors = ColorDataTools.readCSV(this, file, true);
}
if (colors == null || colors.isEmpty()) {
return false;
}
colors.addAll(speicalColors(AppVariables.CurrentLangName));
try (Connection conn = DerbyBase.getConnection()) {
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, paletteName);
if (palette == null) {
return false;
}
TableColorPalette tableColorPalette = new TableColorPalette();
tableColorPalette.clear(conn, palette.getCpnid());
tableColorPalette.write(conn, palette.getCpnid(), colors, true, false);
} catch (Exception e) {
error = e.toString();
return false;
}
return true;
}
@Override
protected void whenSucceeded() {
afterPaletteChanged(parent, paletteName);
}
};
parent.setTask(task);
parent.start(task);
}
public static void importFile(BaseController parent,
File file, String paletteName, boolean reOrder) {
if (parent == null || (parent.getTask() != null && !parent.getTask().isQuit())
|| file == null || !file.exists()) {
return;
}
FxTask task = new FxTask<Void>(parent) {
@Override
protected boolean handle() {
try (Connection conn = DerbyBase.getConnection()) {
List<ColorData> colors = ColorDataTools.readCSV(this, file, reOrder);
if (colors == null || colors.isEmpty()) {
return false;
}
if (paletteName == null || paletteName.isBlank()) {
new TableColor().writeData(conn, colors, true);
} else {
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, paletteName);
if (palette == null) {
return false;
}
new TableColorPalette().write(conn, palette.getCpnid(), colors, true, false);
}
} catch (Exception e) {
error = e.toString();
return false;
}
return true;
}
@Override
protected void whenSucceeded() {
afterPaletteChanged(parent, paletteName);
}
};
parent.setTask(task);
parent.start(task);
}
public static List<ColorData> opticalHuesWheel(String lang, int step) {
try {
List<ColorData> colors = new ArrayList<>();
for (int hue = 0; hue < 360; hue += step) {
Color color = Color.hsb(hue, 1f, 1f);
ColorData data = new ColorData(color).calculate();
data.setColorName(message(lang, "Hue") + ":" + Math.round(data.getColor().getHue()));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> artHuesWheel(String lang, int step) {
try {
List<ColorData> colors = new ArrayList<>();
for (int angle = 0; angle < 360; angle += step) {
java.awt.Color color = ColorConvertTools.ryb2rgb(angle);
ColorData data = new ColorData(color.getRGB()).calculate();
data.setColorName(message(lang, "RYBAngle") + ":" + angle + " "
+ message(lang, "Hue") + ":" + Math.round(data.getColor().getHue()));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> greyScales(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
for (int v = 0; v < 256; v++) {
Color color = Color.gray(v / 255d);
ColorData data = new ColorData(color).calculate();
data.setColorName(message(lang, "Gray") + ":" + Math.round(color.getRed() * 255));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> speicalColors(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
colors.add(new ColorData(FxColorTools.color2rgba(Color.WHITE), message(lang, "White")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.LIGHTGREY), message(lang, "LightGrey")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREY), message(lang, "Grey")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.BLACK), message(lang, "Black")).calculate());
colors.add(new ColorData(0, message(lang, "Transparent")).calculate());
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String defaultPaletteName(String lang) {
return message(lang, "DefaultPalette");
}
public static List<ColorData> defaultColors(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
colors.add(new ColorData(FxColorTools.color2rgba(Color.RED), message(lang, "Red")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.ORANGE), message(lang, "Orange")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.YELLOW), message(lang, "Yellow")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREENYELLOW), message(lang, "GreenYellow")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREEN), message(lang, "Green")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.LIGHTSEAGREEN), message(lang, "SeaGreen")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.DODGERBLUE), message(lang, "Blue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.BLUE), message(lang, "MediumBlue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.PURPLE), message(lang, "Purple")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.PINK), message(lang, "Pink")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.DEEPSKYBLUE), message(lang, "SkyBlue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GOLD), message(lang, "GoldColor")).calculate());
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static ColorPaletteName defaultPalette(String lang, Connection conn) {
try {
if (conn == null) {
return null;
}
boolean ac = conn.getAutoCommit();
conn.setAutoCommit(true);
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, defaultPaletteName(lang));
if (palette == null) {
conn.setAutoCommit(ac);
return null;
}
conn.setAutoCommit(false);
long paletteid = palette.getCpnid();
TableColorPalette tableColorPalette = new TableColorPalette();
if (tableColorPalette.size(conn, paletteid) == 0) {
List<ColorData> colors = defaultColors(lang);
colors.addAll(speicalColors(lang));
tableColorPalette.write(conn, palette.getCpnid(), colors, true, false);
conn.commit();
}
conn.setAutoCommit(ac);
return palette;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static void afterPaletteChanged(BaseController parent, String paletteName) {
if (paletteName == null || paletteName.isBlank()) {
return;
}
UserConfig.setString("ColorPalettePopupPalette", paletteName);
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
Object object = window.getUserData();
if (object != null && object instanceof ColorPalettePopupController) {
try {
ColorPalettePopupController controller = (ColorPalettePopupController) object;
controller.loadColors();
break;
} catch (Exception e) {
}
}
}
if (parent == null) {
return;
}
if (parent instanceof ControlColorPaletteSelector) {
ControlColorPaletteSelector controller = (ControlColorPaletteSelector) parent;
UserConfig.setString(controller.getBaseName() + "Palette", paletteName);
controller.loadPalettes();
parent.popSuccessful();
} else if (parent instanceof ControlColorSet) {
ControlColorSet controller = (ControlColorSet) parent;
controller.showColorPalette();
}
}
}
| 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/fxml/image/ImageViewTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ImageViewTools.java | package mara.mybox.fxml.image;
import javafx.geometry.Bounds;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import mara.mybox.data.DoublePoint;
import mara.mybox.fxml.LocateTools;
/**
* @Author Mara
* @CreateDate 2018-6-11
* @License Apache License Version 2.0
*/
public class ImageViewTools {
public static void imageSize(ScrollPane sPane, ImageView iView) {
try {
if (iView == null || iView.getImage() == null || sPane == null) {
return;
}
iView.setFitWidth(iView.getImage().getWidth());
iView.setFitHeight(iView.getImage().getHeight());
LocateTools.moveCenter(sPane, iView);
// MyBoxLog.console(iView.getImage().getWidth() + " " + iView.getImage().getHeight());
// iView.setLayoutY(10);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void paneSize(ScrollPane sPane, ImageView iView) {
try {
if (iView == null || iView.getImage() == null || sPane == null) {
return;
}
Bounds bounds = sPane.getBoundsInParent();
double ratioW = bounds.getWidth() / iView.getImage().getWidth();
double ratioH = bounds.getHeight() / iView.getImage().getHeight();
if (ratioW < ratioH) {
double w = bounds.getWidth() - 10;
iView.setFitHeight(iView.getImage().getHeight() * w / iView.getImage().getWidth());
iView.setFitWidth(w);
} else {
double h = bounds.getHeight() - 10;
iView.setFitWidth(iView.getImage().getWidth() * h / iView.getImage().getHeight());
iView.setFitHeight(h);
}
LocateTools.moveCenter(sPane, iView);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void zoomIn(ScrollPane sPane, ImageView iView, int xZoomStep, int yZoomStep) {
double currentWidth = iView.getFitWidth();
if (currentWidth == -1) {
currentWidth = iView.getImage().getWidth();
}
iView.setFitWidth(currentWidth + xZoomStep);
double currentHeight = iView.getFitHeight();
if (currentHeight == -1) {
currentHeight = iView.getImage().getHeight();
}
iView.setFitHeight(currentHeight + yZoomStep);
LocateTools.moveCenter(sPane, iView);
}
public static void zoomOut(ScrollPane sPane, ImageView iView, int xZoomStep, int yZoomStep) {
double currentWidth = iView.getFitWidth();
if (currentWidth == -1) {
currentWidth = iView.getImage().getWidth();
}
if (currentWidth <= xZoomStep) {
return;
}
iView.setFitWidth(currentWidth - xZoomStep);
double currentHeight = iView.getFitHeight();
if (currentHeight == -1) {
currentHeight = iView.getImage().getHeight();
}
if (currentHeight <= yZoomStep) {
return;
}
iView.setFitHeight(currentHeight - yZoomStep);
LocateTools.moveCenter(sPane, iView);
}
public static DoublePoint getImageXY(MouseEvent event, ImageView view) {
if (event == null || view.getImage() == null) {
return null;
}
double offsetX = event.getX() - view.getLayoutX() - view.getX();
double offsetY = event.getY() - view.getLayoutY() - view.getY();
// if (offsetX < 0 || offsetX >= view.getBoundsInParent().getWidth()
// || offsetY < 0 || offsetY >= view.getBoundsInParent().getHeight()) {
// return null;
// }
double x = offsetX * view.getImage().getWidth() / view.getBoundsInParent().getWidth();
double y = offsetY * view.getImage().getHeight() / view.getBoundsInParent().getHeight();
return new DoublePoint(x, y);
}
public static Color viewPixel(MouseEvent event, ImageView view) {
DoublePoint p = ImageViewTools.getImageXY(event, view);
if (p == null) {
return null;
}
return viewPixel(p, view);
}
public static Color viewPixel(DoublePoint p, ImageView view) {
return imagePixel(p, view.getImage());
}
public static Color imagePixel(DoublePoint p, Image image) {
if (p == null || image == null) {
return null;
}
int x = (int) p.getX();
int y = (int) p.getY();
if (x >= 0 && x < image.getWidth()
&& y >= 0 && y < image.getHeight()) {
PixelReader pixelReader = image.getPixelReader();
return pixelReader.getColor(x, y);
} else {
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/fxml/image/ColorDemos.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ColorDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.color.ColorMatch;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageBinary;
import mara.mybox.image.data.ImageQuantization;
import mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm;
import mara.mybox.image.data.ImageQuantizationFactory;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ColorDemos {
public static void replaceColor(FxTask demoTask, List<String> files,
PixelsOperation pixelsOperation, File demoFile) {
if (demoTask == null || pixelsOperation == null || files == null) {
return;
}
try {
pixelsOperation.setTask(demoTask);
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("ReplaceColor");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = pixelsOperation
.setBoolPara1(true).setBoolPara2(false).setBoolPara3(false)
.start();
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Hue"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(true).setBoolPara3(false).start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Saturation"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(false).setBoolPara3(true)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Brightness"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(true).setBoolPara3(false)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("All"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void adjustColor(FxTask demoTask, List<String> files,
BufferedImage demoImage, ImageScope scope, File demoFile) {
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("AdjustColor");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsOperation pixelsOperation;
BufferedImage bufferedImage;
String tmpFile;
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Color, PixelsOperation.ColorActionType.Set);
pixelsOperation.setColorPara1(Color.PINK)
.setBoolPara1(true).setBoolPara2(false).setBoolPara3(false)
.setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Color") + "_" + message("Filter"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Brightness, PixelsOperation.ColorActionType.Increase)
.setFloatPara1(0.5f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Brightness") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Hue, PixelsOperation.ColorActionType.Decrease)
.setFloatPara1(0.3f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Hue") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Saturation, PixelsOperation.ColorActionType.Increase)
.setFloatPara1(0.5f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Saturation") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Opacity, PixelsOperation.ColorActionType.Decrease)
.setIntPara1(128).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Opacity") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Increase)
.setIntPara1(60).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Yellow") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Decrease)
.setIntPara1(60).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Magenta") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.RGB, PixelsOperation.ColorActionType.Invert,
message("RGB") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Red, PixelsOperation.ColorActionType.Invert,
message("Red") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Green, PixelsOperation.ColorActionType.Invert,
message("Green") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Blue, PixelsOperation.ColorActionType.Invert,
message("Blue") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Invert,
message("Yellow") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Invert,
message("Magenta") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Cyan, PixelsOperation.ColorActionType.Invert,
message("Cyan") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Red, PixelsOperation.ColorActionType.Filter,
message("Red") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Green, PixelsOperation.ColorActionType.Filter,
message("Green") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Blue, PixelsOperation.ColorActionType.Filter,
message("Blue") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Filter,
message("Yellow") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Filter,
message("Magenta") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Cyan, PixelsOperation.ColorActionType.Filter,
message("Cyan") + "_" + message("Filter"));
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void adjustColor(FxTask demoTask, List<String> files,
BufferedImage demoImage, ImageScope scope, String path,
PixelsOperation.OperationType type,
PixelsOperation.ColorActionType action, String name) {
try {
PixelsOperation pixelsOperation = PixelsOperationFactory.create(
demoImage, scope, type, action)
.setTask(demoTask);
BufferedImage bufferedImage = pixelsOperation.start();
String tmpFile = FileTmpTools.getPathTempFile(path, name, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void blendColor(FxTask currentTask, List<String> files, BufferedImage baseImage,
javafx.scene.paint.Color color, File demoFile) {
if (currentTask == null || baseImage == null || files == null) {
return;
}
if (color == null) {
color = javafx.scene.paint.Color.PINK;
}
Image overlay = FxImageTools.createImage(
(int) (baseImage.getWidth() * 7 / 8), (int) (baseImage.getHeight() * 7 / 8),
color);
int x = (int) (baseImage.getWidth() - overlay.getWidth()) / 2;
int y = (int) (baseImage.getHeight() - overlay.getHeight()) / 2;
ShapeDemos.blendImage(currentTask, files, message("BlendColor"),
baseImage, SwingFXUtils.fromFXImage(overlay, null), x, y, demoFile);
}
public static void blackWhite(FxTask demoTask, List<String> files,
ImageBinary binary, File demoFile) {
if (demoTask == null || binary == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("BlackOrWhite");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
binary.setTask(demoTask);
int threshold = binary.getIntPara1();
BufferedImage bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Default)
.setIsDithering(true)
.start();
String tmpFile = FileTmpTools.getPathTempFile(path, message("Default")
+ "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Default)
.setIsDithering(false)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Default"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
List<Integer> inputs = new ArrayList<>();
inputs.addAll(Arrays.asList(64, 96, 112, 128, 144, 160, 176, 198, 228));
if (threshold > 0 && threshold < 255 && !inputs.contains(threshold)) {
inputs.add(threshold);
}
for (int v : inputs) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(v)
.setIsDithering(true)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + v
+ "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(v)
.setIsDithering(false)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + v, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
int otsu = ImageBinary.threshold(demoTask, binary.getImage());
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(otsu)
.setIsDithering(true)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("OTSU")
+ otsu + "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(otsu)
.setIsDithering(false)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("OTSU") + otsu, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void sepia(FxTask demoTask, List<String> files,
PixelsOperation pixelsOperation, File demoFile) {
if (demoTask == null || pixelsOperation == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Sepia");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
pixelsOperation.setTask(demoTask);
List<Integer> values = Arrays.asList(60, 80, 20, 50, 10, 5, 100, 15, 20);
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
BufferedImage bufferedImage = pixelsOperation.setIntPara1(v).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void reduceColors(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("ReduceColors");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageQuantization quantization;
BufferedImage bufferedImage;
String tmpFile;
ColorMatch colorMatch = new ColorMatch();
for (QuantizationAlgorithm a : QuantizationAlgorithm.values()) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 8, 256, 1, 1, 1, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "8", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 27, 1024, 1, 1, 1, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "27", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 256, 1024, 2, 4, 3, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "256", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void thresholding(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Thresholding");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsOperation op = PixelsOperationFactory.create(
demoImage, null, PixelsOperation.OperationType.Thresholding)
.setIsDithering(false).setTask(demoTask);
BufferedImage bufferedImage = op.setIntPara1(128).setIntPara2(255).setIntPara3(0).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "128_"
+ message("BigValue") + "255_" + message("SmallValue") + "0", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(60).setIntPara2(190).setIntPara3(10).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "60_"
+ message("BigValue") + "190_" + message("SmallValue") + "10", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(200).setIntPara2(255).setIntPara3(60).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "200_"
+ message("BigValue") + "255_" + message("SmallValue") + "60", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(160).setIntPara2(225).setIntPara3(0).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "160_"
+ message("BigValue") + "225_" + message("SmallValue") + "0", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/image/ScopeTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/ScopeTools.java | package mara.mybox.fxml.image;
import java.awt.Color;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.tools.ColorConvertTools;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ScopeTools {
public static Image selectedScope(FxTask task, Image srcImage, ImageScope scope, Color bgColor,
boolean cutMargins, boolean exclude, boolean ignoreTransparent) {
try {
if (scope == null) {
return srcImage;
} else {
PixelsOperation pixelsOperation = PixelsOperationFactory.createFX(srcImage, scope,
PixelsOperation.OperationType.SelectPixels)
.setColorPara1(bgColor)
.setExcludeScope(exclude)
.setSkipTransparent(ignoreTransparent)
.setTask(task);
Image scopeImage = pixelsOperation.startFx();
if (cutMargins) {
return MarginTools.cutMarginsByColor(task, scopeImage,
ColorConvertTools.converColor(bgColor),
0, true, true, true, true);
} else {
return scopeImage;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static Image maskScope(FxTask task, Image srcImage, ImageScope scope,
boolean exclude, boolean ignoreTransparent) {
try {
PixelsOperation pixelsOperation = PixelsOperationFactory.createFX(
srcImage, scope,
PixelsOperation.OperationType.ShowScope)
.setExcludeScope(exclude)
.setSkipTransparent(ignoreTransparent)
.setTask(task);
return pixelsOperation.startFx();
} 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/fxml/image/PixelDemos.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/PixelDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageContrast;
import mara.mybox.image.data.ImageContrast.ContrastAlgorithm;
import mara.mybox.image.data.ImageConvolution;
import mara.mybox.image.data.ImageMosaic;
import mara.mybox.image.data.ImageMosaic.MosaicType;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.BufferedImageTools.Direction;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class PixelDemos {
public static void mosaic(FxTask demoTask, List<String> files, BufferedImage demoImage,
MosaicType type, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Mosaic");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageMosaic mosaic = ImageMosaic.create().setType(type);
mosaic.setImage(demoImage).setTask(demoTask);
List<Integer> values = Arrays.asList(1, 3, 5, 8, 10, 15, 20, 25, 30, 50, 60, 80, 100);
BufferedImage bufferedImage;
String tmpFile;
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = mosaic.setIntensity(v).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Intensity") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void shadow(FxTask demoTask, List<String> files, BufferedImage demoImage,
Color color, File demoFile) {
if (demoTask == null || color == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Shadow");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
int offsetX = Math.max(30, demoImage.getWidth() / 20);
int offsetY = Math.max(30, demoImage.getHeight() / 20);
shadow(demoTask, files, demoImage, path, color, offsetX, offsetY, true);
shadow(demoTask, files, demoImage, path, color, offsetX, -offsetY, true);
shadow(demoTask, files, demoImage, path, color, -offsetX, offsetY, true);
shadow(demoTask, files, demoImage, path, color, -offsetX, -offsetY, true);
shadow(demoTask, files, demoImage, path, color, offsetX, offsetY, false);
shadow(demoTask, files, demoImage, path, color, offsetX, -offsetY, false);
shadow(demoTask, files, demoImage, path, color, -offsetX, offsetY, false);
shadow(demoTask, files, demoImage, path, color, -offsetX, -offsetY, false);
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void shadow(FxTask demoTask, List<String> files, BufferedImage demoImage,
String path, Color color, int offsetX, int offsetY, boolean blur) {
try {
BufferedImage bufferedImage = BufferedImageTools.addShadow(demoTask, demoImage,
-offsetX, -offsetY, color, blur);
String tmpFile = FileTmpTools.getPathTempFile(path,
ColorConvertTools.color2css(color)
+ "_x-" + offsetX + "_y-" + offsetY + (blur ? ("_" + message("Blur")) : ""),
".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void smooth(FxTask demoTask, List<String> files,
ImageConvolution convolution, File demoFile) {
if (demoTask == null || convolution == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Smooth");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
List<Integer> values = Arrays.asList(1, 2, 3, 4);
BufferedImage bufferedImage;
String tmpFile;
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeAverageBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("AverageBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeGaussBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("GaussianBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeMotionBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("MotionBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void sharpen(FxTask demoTask, List<String> files,
ImageConvolution convolution, File demoFile) {
if (demoTask == null || convolution == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Sharpen");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(1))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_1", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_2", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_3", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_4", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.MakeSharpenEightNeighborLaplace())
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("EightNeighborLaplace"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.MakeSharpenFourNeighborLaplace())
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("FourNeighborLaplace"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void contrast(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Contrast");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageContrast contrast = new ImageContrast();
contrast.setImage(demoImage).setTask(demoTask);
BufferedImage bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramEqualization"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
long size = (long) (demoImage.getWidth() * demoImage.getHeight());
List<Integer> pvalues = new ArrayList<>(Arrays.asList(1, 5, 10, 20, 30));
long threshold = (long) (size * 0.05);
for (int v : pvalues) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
List<Integer> values = new ArrayList<>(Arrays.asList(5, 15, 30, 50, -5, -15, -30, -50));
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void edge(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("EdgeDetection");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageConvolution convolution = ImageConvolution.create();
convolution.setImage(demoImage).setTask(demoTask);
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionEightNeighborLaplace()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionEightNeighborLaplaceInvert()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionFourNeighborLaplace()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionFourNeighborLaplaceInvert()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void emboss(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Emboss");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageConvolution convolution = ImageConvolution.create();
convolution.setImage(demoImage).setTask(demoTask);
for (Direction d : Direction.values()) {
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEmbossKernel(d, 3, ConvolutionKernel.Color.Grey)));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEmbossKernel(d, 5, ConvolutionKernel.Color.Grey)));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void convolution(FxTask demoTask, List<String> files,
String path, ImageConvolution convolution) {
try {
BufferedImage bufferedImage = convolution.setColor(ConvolutionKernel.Color.Keep).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, convolution.getKernel().getName(), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution.setColor(ConvolutionKernel.Color.Grey).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, convolution.getKernel().getName()
+ "_" + message("Grey"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/fxml/image/MarginTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/image/MarginTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorInput;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class MarginTools {
public static Image cutTransparentMargins(FxTask task, Image image) {
return cutMarginsByColor(task, image, Color.TRANSPARENT, 10, true, true, true, true);
}
public static Image cutMarginsByWidth(FxTask task, Image image,
int MarginWidth, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) {
try {
int imageWidth = (int) image.getWidth();
int imageHeight = (int) image.getHeight();
int top = 0;
int bottom = imageHeight;
int left = 0;
int right = imageWidth;
if (cutTop) {
top = MarginWidth;
}
if (cutBottom) {
bottom -= MarginWidth;
}
if (cutLeft) {
left = MarginWidth;
}
if (cutRight) {
right -= MarginWidth;
}
return CropTools.cropOutsideFx(task, image, left, top, right, bottom);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image cutMarginsByColor(FxTask task, Image image, Color mColor, int colorDistance,
boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) {
try {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
int top = 0;
int bottom = height;
int left = 0;
int right = width;
int distance2 = colorDistance * colorDistance;
if (cutTop) {
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
top = j;
break;
}
}
}
// MyBoxLog.debug("top: " + top);
if (top < 0) {
return null;
}
if (cutBottom) {
for (int j = height - 1; j >= 0; --j) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
bottom = j + 1;
break;
}
}
}
// MyBoxLog.debug("bottom: " + bottom);
if (bottom < 0) {
return null;
}
if (cutLeft) {
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
left = i;
break;
}
}
}
// MyBoxLog.debug("left: " + left);
if (left < 0) {
return null;
}
if (cutRight) {
for (int i = width - 1; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
right = i + 1;
break;
}
}
}
// MyBoxLog.debug("right: " + right);
if (right < 0) {
return null;
}
// MyBoxLog.debug(left + " " + top + " " + right + " " + bottom);
return CropTools.cropOutsideFx(task, image, left, top, right, bottom);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image dragMarginsFx(FxTask task, Image image, Color color, DoubleRectangle rect) {
try {
if (image == null || rect == null) {
return image;
}
int iwidth = (int) image.getWidth();
int iheight = (int) image.getHeight();
int rwidth = (int) rect.getWidth();
int rheight = (int) rect.getHeight();
int rx = (int) rect.getX();
int ry = (int) rect.getY();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(rwidth, rheight);
PixelWriter pixelWriter = newImage.getPixelWriter();
int ix;
int iy;
for (int j = 0; j < rheight; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
for (int i = 0; i < rwidth; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
ix = i + rx;
iy = j + ry;
if (ix >= 0 && ix < iwidth && iy >= 0 && iy < iheight) {
pixelWriter.setColor(i, j, pixelReader.getColor(ix, iy));
} else {
pixelWriter.setColor(i, j, color);
}
}
}
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
public static Image addMarginsFx(FxTask task, Image image, Color color, int MarginWidth,
boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) {
if (image == null || MarginWidth <= 0) {
return image;
}
return addMarginsFx(task, image, color,
addTop ? MarginWidth : -1,
addBottom ? MarginWidth : -1,
addLeft ? MarginWidth : -1,
addRight ? MarginWidth : -1);
}
public static Image addMarginsFx(FxTask task, Image image, Color color,
int top, int bottom, int left, int right) {
try {
if (image == null) {
return image;
}
int width = (int) image.getWidth();
int height = (int) image.getHeight();
// MyBoxLog.debug(width + " " + height);
int totalWidth = width;
int totalHegiht = height;
int x1 = 0;
int y1 = 0;
if (left > 0) {
totalWidth += left;
x1 = left;
}
if (right > 0) {
totalWidth += right;
}
if (top > 0) {
totalHegiht += top;
y1 = top;
}
if (bottom > 0) {
totalHegiht += bottom;
}
// MyBoxLog.debug(totalWidth + " " + totalHegiht);
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(totalWidth, totalHegiht);
PixelWriter pixelWriter = newImage.getPixelWriter();
pixelWriter.setPixels(x1, y1, width, height, pixelReader, 0, 0);
// MyBoxLog.debug(x1 + " " + y1);
if (left > 0) {
for (int x = 0; x < left; x++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int y = 0; y < totalHegiht; y++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (right > 0) {
for (int x = totalWidth - 1; x > totalWidth - right - 1; x--) {
if (task != null && !task.isWorking()) {
return null;
}
for (int y = 0; y < totalHegiht; y++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (top > 0) {
for (int y = 0; y < top; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < totalWidth; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (bottom > 0) {
for (int y = totalHegiht - 1; y > totalHegiht - bottom - 1; y--) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < totalWidth; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
// This way may fail for big image
public static Image addMarginsFx2(Image image, Color color, int MarginWidth,
boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) {
try {
if (image == null || MarginWidth <= 0) {
return image;
}
Group group = new Group();
double imageWidth = image.getWidth();
double imageHeight = image.getHeight();
double totalWidth = image.getWidth();
double totalHeight = image.getHeight();
ImageView view = new ImageView(image);
view.setPreserveRatio(true);
view.setFitWidth(imageWidth);
view.setFitHeight(imageHeight);
if (addLeft) {
view.setX(MarginWidth);
totalWidth += MarginWidth;
} else {
view.setX(0);
}
if (addTop) {
view.setY(MarginWidth);
totalHeight += MarginWidth;
} else {
view.setY(0);
}
if (addBottom) {
totalHeight += MarginWidth;
}
if (addRight) {
totalWidth += MarginWidth;
}
group.getChildren().add(view);
Blend blend = new Blend(BlendMode.SRC_OVER);
blend.setBottomInput(new ColorInput(0, 0, totalWidth, totalHeight, color));
group.setEffect(blend);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage newImage = group.snapshot(parameters, null);
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
public static Image blurMarginsNoAlpha(FxTask task, Image image, int blurWidth,
boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) {
if (image == null || blurWidth <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.MarginTools.blurMarginsNoAlpha(task, source,
blurWidth, blurTop, blurBottom, blurLeft, blurRight);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image blurMarginsAlpha(FxTask task, Image image,
int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) {
if (image == null || blurWidth <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.MarginTools.blurMarginsAlpha(task, source,
blurWidth, blurTop, blurBottom, blurLeft, blurRight);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/cell/TableDateCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDateCell.java | package mara.mybox.fxml.cell;
import java.util.Date;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableDateCell<T> extends TableCell<T, Date>
implements Callback<TableColumn<T, Date>, TableCell<T, Date>> {
@Override
public TableCell<T, Date> call(TableColumn<T, Date> param) {
TableCell<T, Date> cell = new TableCell<T, Date>() {
@Override
public void updateItem(Date item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataBooleanEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataBooleanEditCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2022-10-5
* @License Apache License Version 2.0
*/
public class TableDataBooleanEditCell extends TableCheckboxCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int colIndex;
public TableDataBooleanEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn, int colIndex) {
super();
this.dataTable = dataTable;
this.dataColumn = dataColumn;
this.colIndex = colIndex;
}
@Override
protected boolean getCellValue(int rowIndex) {
try {
if (rowIndex < 0 || rowIndex >= dataTable.getTableData().size()) {
return false;
}
List<String> row = dataTable.getTableData().get(rowIndex);
return StringTools.isTrue(row.get(colIndex));
} catch (Exception e) {
return false;
}
}
@Override
protected void setCellValue(int rowIndex, boolean value) {
try {
if (isChanging || rowIndex < 0
|| rowIndex >= dataTable.getTableData().size()) {
return;
}
List<String> row = dataTable.getTableData().get(rowIndex);
if ((value + "").equalsIgnoreCase(getItem())) {
return;
}
isChanging = true;
row.set(colIndex, value + "");
dataTable.getTableData().set(rowIndex, row);
isChanging = false;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
}
public static Callback<TableColumn, TableCell>
create(BaseData2DTableController dataTable, Data2DColumn dataColumn, int colIndex) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataBooleanEditCell(dataTable, dataColumn, colIndex);
}
};
}
}
| 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/fxml/cell/TreeTableFileSizeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableFileSizeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2019-11-12
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TreeTableFileSizeCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
setText(FileTools.showFileSize(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableLatitudeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableLatitudeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-2-22
* @License Apache License Version 2.0
*/
public class TableLatitudeCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
setTextFill(null);
return;
}
if (item >= -90 && item <= 90) {
setText(item + "");
} else {
setText(null);
}
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TreeTableIDCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableIDCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableIDCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null || item < 0) {
setText(null);
return;
}
setText(item + "");
}
};
return cell;
}
}
| 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/fxml/cell/TableDataEnumCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataEnumCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableDataEnumCell<S, T> extends ComboBoxTableCell<S, T> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int maxVisibleCount;
public TableDataEnumCell(BaseData2DTableController dataTable, Data2DColumn dataColumn,
ObservableList<T> valueslist, int maxCount) {
super(valueslist);
this.dataTable = dataTable;
this.dataColumn = dataColumn;
setComboBoxEditable(dataColumn.getType() == ColumnType.EnumerationEditable);
maxVisibleCount = maxCount;
if (maxVisibleCount <= 0) {
maxVisibleCount = 10;
}
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TableView<S> table = getTableView();
if (table != null && table.getItems() != null) {
int index = rowIndex();
if (index < table.getItems().size()) {
table.edit(index, getTableColumn());
}
}
}
});
}
@Override
public void startEdit() {
super.startEdit();
Node g = getGraphic();
if (g != null && g instanceof ComboBox) {
ComboBox cb = (ComboBox) g;
cb.setVisibleRowCount(maxVisibleCount);
cb.setValue(getItem());
if (isComboBoxEditable()) {
NodeStyleTools.setTooltip(cb.getEditor(), message("EditCellComments"));
}
}
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
if (dataColumn.getType() == ColumnType.EnumeratedShort) {
setText(dataColumn.formatValue(item));
} else {
setText(item != null ? item + "" : null);
}
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(
BaseData2DTableController dataTable, Data2DColumn dataColumn,
List<T> items, int maxVisibleCount) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
ObservableList<T> olist = FXCollections.observableArrayList();
for (T item : items) {
olist.add(item);
}
return new TableDataEnumCell<>(dataTable, dataColumn, olist, maxVisibleCount);
}
};
}
}
| 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/fxml/cell/TableRowSelectionCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableRowSelectionCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableRowSelectionCell<S, T> extends CheckBoxTableCell<S, T> {
protected TableView tableView;
protected SimpleBooleanProperty checked;
protected boolean selectingRow, checkingBox;
protected ChangeListener<Boolean> checkedListener;
protected ListChangeListener selectedListener;
public TableRowSelectionCell(TableView tView) {
tableView = tView;
checked = new SimpleBooleanProperty(false);
selectingRow = checkingBox = false;
getStyleClass().add("row-number");
initListeners();
tableView.getSelectionModel().getSelectedIndices().addListener(selectedListener);
checked.addListener(checkedListener);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
int row = rowIndex();
if (row < 0) {
setText("");
return null;
}
setText("" + (row + 1));
checkingBox = true;
checked.set(tableView.getSelectionModel().isSelected(row));
checkingBox = false;
return checked;
}
});
}
private void initListeners() {
checkedListener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
int row = rowIndex();
if (checkingBox || row < 0) {
return;
}
selectingRow = true;
if (newValue) {
tableView.getSelectionModel().select(row);
} else {
tableView.getSelectionModel().clearSelection(row);
}
selectingRow = false;
}
};
selectedListener = new ListChangeListener<Integer>() {
@Override
public void onChanged(ListChangeListener.Change c) {
int row = rowIndex();
if (checked == null || selectingRow || row < 0) {
return;
}
checkingBox = true;
checked.set(tableView.getSelectionModel().isSelected(row));
checkingBox = false;
}
};
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(TableView tableView) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableRowSelectionCell<>(tableView);
}
};
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = 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/fxml/cell/TableColorCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableColorCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-1-8
* @License Apache License Version 2.0
*/
public class TableColorCell<T> extends TableCell<T, Color>
implements Callback<TableColumn<T, Color>, TableCell<T, Color>> {
@Override
public TableCell<T, Color> call(TableColumn<T, Color> param) {
final Rectangle rectangle;
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
TableCell<T, Color> cell = new TableCell<T, Color>() {
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
} else {
rectangle.setFill((Paint) item);
setGraphic(rectangle);
}
}
};
return cell;
}
}
| 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/fxml/cell/TreeTableDateCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableDateCell.java | package mara.mybox.fxml.cell;
import java.util.Date;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableDateCell<T> extends TreeTableCell<T, Date>
implements Callback<TreeTableColumn<T, Date>, TreeTableCell<T, Date>> {
@Override
public TreeTableCell<T, Date> call(TreeTableColumn<T, Date> param) {
TreeTableCell<T, Date> cell = new TreeTableCell<T, Date>() {
@Override
protected void updateItem(final Date item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableRowIndexCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableRowIndexCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2023-7-8
* @License Apache License Version 2.0
*/
public class TableRowIndexCell<T> extends TableCell<T, Object>
implements Callback<TableColumn<T, Object>, TableCell<T, Object>> {
@Override
public TableCell<T, Object> call(TableColumn<T, Object> param) {
TableCell<T, Object> cell = new TableCell<T, Object>() {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
try {
int v = getTableRow().getIndex();
if (v >= 0) {
setText((v + 1) + "");
}
} catch (Exception e) {
}
}
};
return cell;
}
}
| 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/fxml/cell/TreeConditionCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeConditionCell.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mara.mybox.fxml.cell;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.cell.CheckBoxTreeCell;
import mara.mybox.fxml.ConditionNode;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.fxml.NodeTools;
/**
* @Author Mara
* @CreateDate 2020-4-18
* @License Apache License Version 2.0
*/
public class TreeConditionCell extends CheckBoxTreeCell<ConditionNode> {
@Override
public void updateItem(ConditionNode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getText());
Node node = getGraphic();
if (node != null && node instanceof CheckBox) {
CheckBox checkBox = (CheckBox) node;
if (item.getCondition() != null && !item.getCondition().isBlank()) {
NodeStyleTools.setTooltip(checkBox, item.getCondition());
} else {
NodeStyleTools.removeTooltip(checkBox);
}
}
}
}
| 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/fxml/cell/ListColorCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/ListColorCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:30:16
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ListColorCell extends ListCell<Color> {
private final Rectangle rectangle;
public ListColorCell() {
setContentDisplay(ContentDisplay.LEFT);
rectangle = new Rectangle(30, 20);
}
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
} else {
rectangle.setFill(item);
setGraphic(rectangle);
setText(item.toString());
}
}
}
| 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/fxml/cell/TableImageCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableImageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableImageCell<T> extends TableCell<T, Image>
implements Callback<TableColumn<T, Image>, TableCell<T, Image>> {
@Override
public TableCell<T, Image> call(TableColumn<T, Image> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
imageview.setFitWidth(AppVariables.thumbnailWidth);
imageview.setFitHeight(AppVariables.thumbnailWidth);
TableCell<T, Image> cell = new TableCell<T, Image>() {
@Override
public void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
imageview.setImage(item);
setGraphic(imageview);
}
};
return cell;
}
}
| 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/fxml/cell/ListImageCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/ListImageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class ListImageCell extends ListCell<Image> {
private ImageView view;
private final int height;
public ListImageCell() {
height = 30;
init();
}
public ListImageCell(int height) {
this.height = height;
init();
}
private void init() {
view = new ImageView();
view.setPreserveRatio(true);
view.setFitHeight(height);
}
@Override
protected void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
view.setImage(item);
setGraphic(view);
setText(item.getUrl());
} else {
setGraphic(null);
setText(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/fxml/cell/TableIDCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableIDCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2025-4-25
* @License Apache License Version 2.0
*/
public class TableIDCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null || item < 0) {
setText(null);
return;
}
setText(item + "");
}
};
return cell;
}
}
| 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/fxml/cell/TableDurationCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDurationCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableDurationCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
text.setText(DateTools.datetimeMsDuration(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataColorEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataColorEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.table.TableColor;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-10-8
* @License Apache License Version 2.0
*/
public class TableDataColorEditCell extends TableDataEditCell {
protected TableColor tableColor;
protected Rectangle rectangle;
protected String msgPrefix;
public TableDataColorEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn, TableColor tableColor) {
super(dataTable, dataColumn);
this.tableColor = tableColor;
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
rectangle.setStroke(Color.BLACK);
rectangle.setStrokeWidth(1);
msgPrefix = message("ClickColorToPalette");
}
@Override
public void editCell() {
Node g = getGraphic();
if (g == null || !(g instanceof Rectangle)) {
return;
}
ColorPalettePopupController inputController = ColorPalettePopupController.open(dataTable, rectangle);
inputController.getSetNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
Color color = (Color) rectangle.getFill();
setCellValue(color.toString());
inputController.closeStage();
}
});
}
@Override
public void displayData(String item) {
Color color;
try {
color = Color.web(item);
} catch (Exception e) {
color = Color.WHITE;
}
if (tableColor == null) {
tableColor = new TableColor();
}
rectangle.setFill(color);
NodeStyleTools.setTooltip(rectangle, msgPrefix + "\n---------\n"
+ FxColorTools.colorNameDisplay(tableColor, color));
setGraphic(rectangle);
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable,
Data2DColumn dataColumn, TableColor tableColor) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataColorEditCell(dataTable, dataColumn, tableColor);
}
};
}
}
| 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/fxml/cell/TableBooleanCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableBooleanCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.fxml.style.StyleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableBooleanCell<T> extends TableCell<T, Boolean>
implements Callback<TableColumn<T, Boolean>, TableCell<T, Boolean>> {
@Override
public TableCell<T, Boolean> call(TableColumn<T, Boolean> param) {
final ImageView imageview = StyleTools.getIconImageView("iconYes.png");
imageview.setPreserveRatio(true);
TableCell<T, Boolean> cell = new TableCell<T, Boolean>() {
@Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || !item) {
setText(null);
setGraphic(null);
return;
}
setGraphic(imageview);
setText(null);
}
};
return cell;
}
}
| 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.