diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4f3df9e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,93 @@ +name: CI/CD Pipeline + +on: + push: + branches: [ main, work ] + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Setup Java + uses: actions/setup-java@v3 + with: + java-version: '21' + distribution: 'temurin' + + - name: Run tests + run: ./gradlew test + + - name: Run SpotBugs + run: ./gradlew spotbugsMain + + - name: Build + run: ./gradlew build + + - name: Create fat JAR + run: ./gradlew fatJar + + - name: Upload JAR artifact + uses: actions/upload-artifact@v4 + with: + name: image-filtering-app + path: app/build/libs/image-filtering-all.jar + retention-days: 30 + + release: + needs: build + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + + steps: + - uses: actions/checkout@v3 + + - name: Setup Java + uses: actions/setup-java@v3 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build and create fat JAR + run: ./gradlew fatJar + + - name: Create Release + uses: softprops/action-gh-release@v1 + with: + tag_name: v${{ github.run_number }} + name: Image Filtering App v${{ github.run_number }} + body: | + ## Image Filtering Application + + Automated build from commit ${{ github.sha }} + + ## Usage + ```bash + java -jar image-filtering-all.jar [convolution_mode] [output_path] + ``` + + ## Available Filters + - blur + - emboss + - find_edges + - glass_distortion + - motion_blur + - negative + - pixelate + - radial_blur + + ## Convolution Modes + - sequential (default) + - row + - column + - pixel + - grid + files: app/build/libs/image-filtering-all.jar + draft: false + prerelease: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 524f096..db8bf51 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,14 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* replay_pid* + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +.idea + +.DS_Store + diff --git a/README.md b/README.md index 31a2646..8999d7c 100644 --- a/README.md +++ b/README.md @@ -1 +1,103 @@ -# image-filtering \ No newline at end of file +### Image Filtering Application + +A Java application for applying various image filters using different convolution algorithms. + +--- + +### Project Structure + +``` +app/src/main/java/com/vicitori/ +├── app/ +│ ├── Main.java # Application entry point +│ ├── ImageFilteringApp.java # CLI interface using Picocli +│ ├── FilteringEngine.java # Main processing engine +│ +├── core/ +│ ├── Filter.java # Filter record with kernel, factor, bias +│ ├── Convolution.java # Abstract convolution interface +│ ├── AbstractConvolution.java # Base convolution implementation +│ └── conv/ +│ ├── SequentialConvolution.java +│ ├── RowConvolution.java +│ ├── ColumnConvolution.java +│ ├── PixelConvolution.java +│ └── GridConvolution.java +├── filters/ +│ └── FiltersLibrary.java +├── io/ +│ └── ImageIO.java +└── pipeline/ + └── ImagePipeline.java # Multi-threaded batch processing +``` + +### How to Run + +#### Prerequisites +- Download the latest `image-filtering-all.jar` from the Releases page +- Java 21 or higher + +#### Single Image Processing +```bash +java -jar image-filtering-all.jar [convolution_mode] [output_path] +``` + +#### Batch Processing (Images in directory) +```bash +java -jar image-filtering-all.jar -d [convolution_mode] [output_directory] [-t threads] +``` + +### Command Line Options +- `-d, --directory` - Enable directory mode for batch processing +- `-t, --threads` - Number of worker threads (default: 4) +- `-h, --help` - Show help message + +### Available Filters + +- `blur` - gaussian blur +- `emboss` - emboss effect +- `find_edges` - edge detection +- `glass_distortion` - glass distortion effect +- `motion_blur` - motion blur +- `negative` - negative/invert colors +- `pixelate` - pixelation effect +- `radial_blur` - radial blur effect + +### Convolution Modes + +- `sequential` (default) - Standard sequential processing +- `row` - Row-based parallel processing +- `column` - Column-based parallel processing +- `pixel` - Pixel-by-pixel processing +- `grid` - Grid-based parallel processing + +### Usage + +```bash +# Apply blur filter to single image +java -jar image-filtering-all.jar input.jpg blur output.jpg + +# Apply emboss filter with row convolution +java -jar image-filtering-all.jar input.jpg emboss row output.jpg + +# Apply edge detection filter +java -jar image-filtering-all.jar input.jpg find_edges output.jpg + +# Apply negative effect +java -jar image-filtering-all.jar input.jpg negative output.jpg + +# Apply motion blur effect +java -jar image-filtering-all.jar input.jpg motion_blur output.jpg + +# Batch process directory with 4 threads +java -jar image-filtering-all.jar -d ./images blur sequential ./output -t 4 +``` + +### Building + +```bash +./gradlew build +./gradlew fatJar +# image-filtering-all.jar will be at app/build/libs +``` + diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..b4306f7 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,54 @@ +import org.gradle.internal.classpath.Instrumented.systemProperty + +plugins { + application + id("com.github.spotbugs") version "6.0.14" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("info.picocli:picocli:4.7.5") + + // Lincheck for concurrency testing + testImplementation("org.jetbrains.kotlinx:lincheck:2.24") + + // JUnit for testing + testImplementation("org.junit.jupiter:junit-jupiter:5.10.1") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +application { + mainClass = "com.vicitori.app.Main" +} + +tasks.register("fatJar") { + group = "build" + archiveClassifier.set("all") + archiveBaseName.set("image-filtering") + + manifest { + attributes["Main-Class"] = "com.vicitori.app.Main" + } + + from(sourceSets.main.get().output) + dependsOn(configurations.runtimeClasspath) + from({ + configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) } + }) +} + +// SpotBugs configuration +spotbugs { + ignoreFailures = false +} + + diff --git a/app/src/main/java/com/vicitori/app/FilteringEngine.java b/app/src/main/java/com/vicitori/app/FilteringEngine.java new file mode 100644 index 0000000..793545a --- /dev/null +++ b/app/src/main/java/com/vicitori/app/FilteringEngine.java @@ -0,0 +1,60 @@ +package com.vicitori.app; + +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; +import com.vicitori.core.conv.*; +import com.vicitori.core.filters.FiltersLibrary; +import com.vicitori.io.ImageIO; +import com.vicitori.pipeline.ImagePipeline; + +import java.awt.image.BufferedImage; +import java.util.Objects; + +public class FilteringEngine { + private final ImageIO io; + + public FilteringEngine(ImageIO io) { + this.io = Objects.requireNonNull(io, "ImageIO cannot be null"); + } + + public String process(String filterName, String convMode) throws ProcessingException { + try { + Filter filter = FiltersLibrary.get(filterName.toLowerCase()); + if (filter == null) { + throw new ProcessingException("FilteringEngine: process: Unknown filter: " + filterName + ". Available: " + FiltersLibrary.getNames()); + } + Convolution convolution = createConvolution(convMode); + BufferedImage image = io.getImage(); + BufferedImage result = convolution.apply(image, filter); + io.writeImage(result); + return io.getOutputPath().toString(); + } catch (Exception e) { + throw new ProcessingException("FilteringEngine: process: " + e.getMessage()); + } + } + + public String process(String filterName, String convMode, int workers) throws ProcessingException { + try { + Filter filter = FiltersLibrary.get(filterName.toLowerCase()); + if (filter == null) { + throw new ProcessingException("FilteringEngine: process: with workers: Unknown filter: " + filterName + ". Available: " + FiltersLibrary.getNames()); + } + Convolution convolution = createConvolution(convMode); + new ImagePipeline(io.getInputFiles(), io.getOutputDir(), workers, convolution, filter).start(); + return io.getOutputDir().toString(); + } catch (Exception e) { + throw new ProcessingException("FilteringEngine: process: with workers: " + e.getMessage()); + } + } + + private Convolution createConvolution(String convMode) { + if (convMode == null) return new SequentialConvolution(); + return switch (convMode.toLowerCase()) { + case "row" -> new RowConvolution(); + case "column" -> new ColumnConvolution(); + case "pixel" -> new PixelConvolution(); + case "grid" -> new GridConvolution(); + default -> new SequentialConvolution(); + }; + } +} diff --git a/app/src/main/java/com/vicitori/app/ImageFilteringApp.java b/app/src/main/java/com/vicitori/app/ImageFilteringApp.java new file mode 100644 index 0000000..fbd8e2b --- /dev/null +++ b/app/src/main/java/com/vicitori/app/ImageFilteringApp.java @@ -0,0 +1,57 @@ +package com.vicitori.app; + +import com.vicitori.io.ImageIO; +import picocli.CommandLine.Command; +import picocli.CommandLine.Parameters; +import picocli.CommandLine.Option; +import java.util.concurrent.Callable; + +@Command( + name = "ImageFilteringApp", + description = "Apply convolution filters to an image.", + mixinStandardHelpOptions = true +) +public class ImageFilteringApp implements Callable { + + @Parameters(index = "0", description = "Path to the input image.", paramLabel = "INPUT_PATH") + private String inputPath; + + @Parameters(index = "1", description = "Filter name: ${COMPLETION-CANDIDATES}", paramLabel = "FILTER_NAME") + private String filterName; + + @Parameters(index = "2", arity = "0..1", + description = "Convolution mode (sequential, parallel (row), parallel (column), parallel (pixel), parallel (grid)). Default: sequential", + paramLabel = "CONVOLUTION_MODE") + private String convMode; + + @Parameters(index = "3", arity = "0..1", + description = "Path to the output image. Default: _filtered.png", + paramLabel = "OUTPUT_PATH") + private String outputPath; + + @Option(names = {"-d", "--directory"}, description = "If specified, treat INPUT_PATH as a directory and process all images inside.") + private boolean directoryMode = false; + + @Option(names = {"-t", "--threads"}, description = "Number of worker threads for directory processing. Default: 4") + private int workers = 4; + + @Override + public Integer call() { + try { + ImageIO io = ImageIO.create(directoryMode, inputPath, outputPath); + FilteringEngine imgProcessor = new FilteringEngine(io); + String savedPath; + if (directoryMode) { + savedPath = imgProcessor.process(filterName, convMode, workers); + } else { + savedPath = imgProcessor.process(filterName, convMode); + } + System.out.printf("Applied filter '%s' with mode '%s'. Saved result to %s%n", + filterName, convMode == null ? "sequential" : convMode, savedPath); + return 0; + } catch (ProcessingException e) { + System.err.println("Error: " + e.getMessage()); + return 1; + } + } +} diff --git a/app/src/main/java/com/vicitori/app/Main.java b/app/src/main/java/com/vicitori/app/Main.java new file mode 100644 index 0000000..bc9460c --- /dev/null +++ b/app/src/main/java/com/vicitori/app/Main.java @@ -0,0 +1,10 @@ +package com.vicitori.app; + +import picocli.CommandLine; + +public class Main { + public static void main(String[] args) { + int exitCode = new CommandLine(new ImageFilteringApp()).execute(args); + System.exit(exitCode); + } +} diff --git a/app/src/main/java/com/vicitori/app/ProcessingException.java b/app/src/main/java/com/vicitori/app/ProcessingException.java new file mode 100644 index 0000000..d81de3b --- /dev/null +++ b/app/src/main/java/com/vicitori/app/ProcessingException.java @@ -0,0 +1,8 @@ +package com.vicitori.app; + +// Exception for high-level image processing failures +public class ProcessingException extends Exception { + public ProcessingException(String message) { + super(message); + } +} diff --git a/app/src/main/java/com/vicitori/core/AbstractConvolution.java b/app/src/main/java/com/vicitori/core/AbstractConvolution.java new file mode 100644 index 0000000..cd2cce1 --- /dev/null +++ b/app/src/main/java/com/vicitori/core/AbstractConvolution.java @@ -0,0 +1,43 @@ +package com.vicitori.core; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public abstract class AbstractConvolution implements Convolution { + protected final Color applyKernel(BufferedImage image, int x, int y, Filter filter) { + float[][] kernel = filter.kernel(); + float factor = filter.factor(); + float bias = filter.bias(); + + int filterHeight = kernel.length; + int filterWidth = kernel[0].length; + + int filterHalfH = filterHeight / 2; + int filterHalfW = filterWidth / 2; + + int width = image.getWidth(); + int height = image.getHeight(); + + float red = 0f, green = 0f, blue = 0f; + + for (int filterY = 0; filterY < filterHeight; filterY++) { + for (int filterX = 0; filterX < filterWidth; filterX++) { + + int imageX = (x - filterHalfW + filterX + width) % width; + int imageY = (y - filterHalfH + filterY + height) % height; + Color pixel = new Color(image.getRGB(imageX, imageY)); + + red += pixel.getRed() * kernel[filterY][filterX]; + green += pixel.getGreen() * kernel[filterY][filterX]; + blue += pixel.getBlue() * kernel[filterY][filterX]; + } + } + return new Color(calibrate(red, factor, bias), calibrate(green, factor, bias), calibrate(blue, factor, bias)); + } + + protected final int calibrate(float value, float factor, float bias) { + float newValue = value * factor + bias; + int intValue = Math.round(newValue); + return Math.max(0, Math.min(255, intValue)); + } +} diff --git a/app/src/main/java/com/vicitori/core/Convolution.java b/app/src/main/java/com/vicitori/core/Convolution.java new file mode 100644 index 0000000..60bc98d --- /dev/null +++ b/app/src/main/java/com/vicitori/core/Convolution.java @@ -0,0 +1,7 @@ +package com.vicitori.core; + +import java.awt.image.BufferedImage; + +public interface Convolution { + BufferedImage apply(BufferedImage image, Filter filter); +} diff --git a/app/src/main/java/com/vicitori/core/Filter.java b/app/src/main/java/com/vicitori/core/Filter.java new file mode 100644 index 0000000..46109e1 --- /dev/null +++ b/app/src/main/java/com/vicitori/core/Filter.java @@ -0,0 +1,24 @@ +package com.vicitori.core; + +public record Filter(float[][] kernel, float factor, float bias) { + public Filter { + // Defensive copy to prevent external modification + if (kernel != null) { + float[][] copy = new float[kernel.length][]; + for (int i = 0; i < kernel.length; i++) { + copy[i] = kernel[i].clone(); + } + kernel = copy; + } + } + + public float[][] kernel() { + // Return defensive copy + if (kernel == null) return null; + float[][] copy = new float[kernel.length][]; + for (int i = 0; i < kernel.length; i++) { + copy[i] = kernel[i].clone(); + } + return copy; + } +} diff --git a/app/src/main/java/com/vicitori/core/conv/ColumnConvolution.java b/app/src/main/java/com/vicitori/core/conv/ColumnConvolution.java new file mode 100644 index 0000000..915bf63 --- /dev/null +++ b/app/src/main/java/com/vicitori/core/conv/ColumnConvolution.java @@ -0,0 +1,45 @@ +package com.vicitori.core.conv; + +import com.vicitori.core.AbstractConvolution; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ColumnConvolution extends AbstractConvolution implements Convolution { + private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + + @Override + public BufferedImage apply(BufferedImage image, Filter filter) { + int width = image.getWidth(); + int height = image.getHeight(); + + BufferedImage outputImage = new BufferedImage(width, height, image.getType()); + + List> tasks = new ArrayList<>(); + for (int x = 0; x < width; x++) { + final int fx = x; + tasks.add(() -> { + for (int y = 0; y < height; y++) { + Color newPixel = applyKernel(image, fx, y, filter); + // memory areas of different threads do not overlap + outputImage.setRGB(fx, y, newPixel.getRGB()); + } + return null; + }); + } + + try { + executor.invokeAll(tasks); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return outputImage; + } +} diff --git a/app/src/main/java/com/vicitori/core/conv/GridConvolution.java b/app/src/main/java/com/vicitori/core/conv/GridConvolution.java new file mode 100644 index 0000000..01794b2 --- /dev/null +++ b/app/src/main/java/com/vicitori/core/conv/GridConvolution.java @@ -0,0 +1,72 @@ +package com.vicitori.core.conv; + +import com.vicitori.core.AbstractConvolution; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class GridConvolution extends AbstractConvolution implements Convolution { + private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + // in the future it will be possible to set via cli + private final int blocksCntX; + private final int blocksCntY; + + public GridConvolution(int blocksCntX, int blocksCntY) { + this.blocksCntX = blocksCntX; + this.blocksCntY = blocksCntY; + } + + // now uses these randomly selected values + public GridConvolution() { + this.blocksCntX = 10; + this.blocksCntY = 6; + } + + @Override + public BufferedImage apply(BufferedImage image, Filter filter) { + int width = image.getWidth(); + int height = image.getHeight(); + + BufferedImage outputImage = new BufferedImage(width, height, image.getType()); + + int blockWidth = (int) Math.ceil((double) width / this.blocksCntX); + int blockHeight = (int) Math.ceil((double) height / this.blocksCntY); + + List> tasks = new ArrayList<>(); + + // divide the picture into blocksCntY * blocksCntX of rectangles + for (int by = 0; by < this.blocksCntY; by++) { + for (int bx = 0; bx < this.blocksCntX; bx++) { + final int startX = bx * blockWidth; + final int startY = by * blockHeight; + final int endX = Math.min(startX + blockWidth, width); + final int endY = Math.min(startY + blockHeight, height); + + tasks.add(() -> { + for (int y = startY; y < endY; y++) { + for (int x = startX; x < endX; x++) { + Color newPixel = applyKernel(image, x, y, filter); + // memory areas of different threads do not overlap + outputImage.setRGB(x, y, newPixel.getRGB()); + } + } + return null; + }); + } + } + + try { + executor.invokeAll(tasks); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return outputImage; + } +} diff --git a/app/src/main/java/com/vicitori/core/conv/PixelConvolution.java b/app/src/main/java/com/vicitori/core/conv/PixelConvolution.java new file mode 100644 index 0000000..e110a7a --- /dev/null +++ b/app/src/main/java/com/vicitori/core/conv/PixelConvolution.java @@ -0,0 +1,48 @@ +package com.vicitori.core.conv; + +import com.vicitori.core.AbstractConvolution; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class PixelConvolution extends AbstractConvolution implements Convolution { + private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + + @Override + public BufferedImage apply(BufferedImage image, Filter filter) { + int width = image.getWidth(); + int height = image.getHeight(); + + BufferedImage outputImage = new BufferedImage(width, height, image.getType()); + + List> tasks = new ArrayList<>(); + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + final int fx = x; + final int fy = y; + + tasks.add(() -> { + Color newPixel = applyKernel(image, fx, fy, filter); + // memory areas of different threads do not overlap + outputImage.setRGB(fx, fy, newPixel.getRGB()); + return null; + }); + } + } + + try { + executor.invokeAll(tasks); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return outputImage; + } +} diff --git a/app/src/main/java/com/vicitori/core/conv/RowConvolution.java b/app/src/main/java/com/vicitori/core/conv/RowConvolution.java new file mode 100644 index 0000000..f4e8dfd --- /dev/null +++ b/app/src/main/java/com/vicitori/core/conv/RowConvolution.java @@ -0,0 +1,46 @@ +package com.vicitori.core.conv; + +import com.vicitori.core.AbstractConvolution; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class RowConvolution extends AbstractConvolution implements Convolution { + private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + + @Override + public BufferedImage apply(BufferedImage image, Filter filter) { + int width = image.getWidth(); + int height = image.getHeight(); + + BufferedImage outputImage = new BufferedImage(width, height, image.getType()); + + List> tasks = new ArrayList<>(); + for (int y = 0; y < height; y++) { + final int fy = y; + + tasks.add(() -> { + for (int x = 0; x < width; x++) { + Color newPixel = applyKernel(image, x, fy, filter); + // memory areas of different threads do not overlap + outputImage.setRGB(x, fy, newPixel.getRGB()); + } + return null; + }); + } + + try { + executor.invokeAll(tasks); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return outputImage; + } +} diff --git a/app/src/main/java/com/vicitori/core/conv/SequentialConvolution.java b/app/src/main/java/com/vicitori/core/conv/SequentialConvolution.java new file mode 100644 index 0000000..56a06ac --- /dev/null +++ b/app/src/main/java/com/vicitori/core/conv/SequentialConvolution.java @@ -0,0 +1,25 @@ +package com.vicitori.core.conv; + +import com.vicitori.core.AbstractConvolution; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public class SequentialConvolution extends AbstractConvolution implements Convolution { + @Override + public BufferedImage apply(BufferedImage image, Filter filter) { + int width = image.getWidth(); + int height = image.getHeight(); + + BufferedImage outputImage = new BufferedImage(width, height, image.getType()); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Color newPixel = applyKernel(image, x, y, filter); + outputImage.setRGB(x, y, newPixel.getRGB()); + } + } + return outputImage; + } +} diff --git a/app/src/main/java/com/vicitori/core/filters/FiltersLibrary.java b/app/src/main/java/com/vicitori/core/filters/FiltersLibrary.java new file mode 100644 index 0000000..61af15b --- /dev/null +++ b/app/src/main/java/com/vicitori/core/filters/FiltersLibrary.java @@ -0,0 +1,77 @@ +package com.vicitori.core.filters; + +import com.vicitori.core.Filter; + +import java.util.Map; +import java.util.Set; + +public class FiltersLibrary { + private static final Map FILTERS = Map.of( + "motion_blur", new Filter( + new float[][]{ + {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, + }, 1.0f / 9, 0.0f + ), "radial_blur", new Filter( + new float[][]{ + {0.0f, 0.1f, 0.0f}, + {0.1f, 0.6f, 0.1f}, + {0.0f, 0.1f, 0.0f} + }, 1.0f, 0.0f + ),"blur", new Filter( + new float[][]{ + {1.0f, 4.0f, 6.0f, 4.0f, 1.0f}, + {4.0f, 16.0f, 24.0f, 16.0f, 4.0f}, + {6.0f, 24.0f, 36.0f, 24.0f, 6.0f}, + {4.0f, 16.0f, 24.0f, 16.0f, 4.0f}, + {1.0f, 4.0f, 6.0f, 4.0f, 1.0f} + }, 1.0f / 256, 0.0f + ),"emboss", new Filter( + new float[][]{ + {-2.0f, -1.0f, 0.0f}, + {-1.0f, 1.0f, 1.0f}, + {0.0f, 1.0f, 2.0f} + }, 0.7f, 128.0f + ),"find_edges", new Filter( + new float[][]{ + {-1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, -2.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 6.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, -2.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 0.0f, -1.0f}, + + }, 1.0f, 0.0f + ),"glass_distortion", new Filter( + new float[][]{ + {0.0f, 1.0f, 0.0f}, + {1.0f, -4.0f, 1.0f}, + {0.0f, 1.0f, 0.0f} + }, 1.5f, 128.0f + ),"negative", new Filter( + new float[][]{ + {-1.0f} + }, 0.9f, 255.0f + ),"pixelate", new Filter( + new float[][]{ + {1.0f, 1.0f, 0.0f, 0.0f}, + {1.0f, 1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f, 1.0f}, + {0.0f, 0.0f, 1.0f, 1.0f} + }, 0.15f, 0.0f + )); + + public static Filter get(String name) { + return FILTERS.get(name.toLowerCase()); + } + + public static Set getNames() { + return FILTERS.keySet(); + } +} diff --git a/app/src/main/java/com/vicitori/io/ImageIO.java b/app/src/main/java/com/vicitori/io/ImageIO.java new file mode 100644 index 0000000..b0ba9c1 --- /dev/null +++ b/app/src/main/java/com/vicitori/io/ImageIO.java @@ -0,0 +1,155 @@ +package com.vicitori.io; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class ImageIO { + private final Path inputPath; + private final Path outputPath; + private final String outputFormat; + public final List inputFiles; + public final File outputDir; + + private ImageIO(Path inputPath, Path outputPath, String outputFormat, List inputFiles, File outputDir) { + this.inputPath = inputPath; + this.outputPath = outputPath; + this.outputFormat = outputFormat; + this.inputFiles = inputFiles; + this.outputDir = outputDir; + } + + public static ImageIO create(boolean isDirectory, String inputPathStr, String outputPathStr) { + if (inputPathStr == null) { + throw new IllegalArgumentException("IOService: INPUT_PATH must not be null. Restart program."); + } + + try { + if (isDirectory) { + File inputDir = validateInputDir(inputPathStr); + List inputFiles = collectInputFiles(inputDir); + File outputDir = prepareOutputDir(inputDir, outputPathStr); + String outputFormat = detectOutputFormat(inputFiles); + + return new ImageIO(null, null, outputFormat, inputFiles, outputDir); + } else { + Path inputPath = Paths.get(inputPathStr); + PathAndFormat out = resolveOutputPathAndFormat(inputPathStr, outputPathStr, inputPath); + + return new ImageIO(inputPath, out.path(), out.format(), null, null); + } + } catch (Exception e) { + throw new RuntimeException("Failed to create ImageIO", e); + } + } + + private static File validateInputDir(String inputPathStr) { + File inputDir = new File(inputPathStr); + if (!inputDir.exists() || !inputDir.isDirectory()) { + throw new IllegalArgumentException("Error: " + inputPathStr + " is not a valid directory."); + } + return inputDir; + } + + + private static List collectInputFiles(File inputDir) { + List inputFiles = Arrays.stream(Objects.requireNonNull(inputDir.listFiles())) + .filter(File::isFile) + .filter(f -> { + String name = f.getName().toLowerCase(); + return name.endsWith(".png") || name.endsWith(".jpg") || name.endsWith(".jpeg"); + }) + .toList(); + if (inputFiles.isEmpty()) { + throw new IllegalArgumentException("Error: No image files found in " + inputDir.getAbsolutePath()); + } + return inputFiles; + } + + + private static File prepareOutputDir(File inputDir, String outputPathStr) { + File outputDir = (outputPathStr == null) + ? new File(inputDir.getParentFile(), inputDir.getName() + "_filtered") + : new File(outputPathStr); + + if (outputDir.exists() && !outputDir.isDirectory()) { + throw new IllegalArgumentException("Output path exists but is not a directory: " + outputDir); + } + if (!outputDir.exists() && !outputDir.mkdirs()) { + throw new IllegalStateException("ImageIO: Failed to create output directory: " + outputDir.getAbsolutePath()); + } + return outputDir; + } + + private static String detectOutputFormat(List inputFiles) { + String firstExt = extensionOfFileName(inputFiles.getFirst().getName()); + return (firstExt == null) ? "png" : firstExt.toLowerCase(); + } + + private record PathAndFormat(Path path, String format) {} + + private static PathAndFormat resolveOutputPathAndFormat(String inputPathStr, String outputPathStr, Path inputPath) { + if (outputPathStr == null) { + String ext = extensionOfFileName(inputPathStr); + String format = (ext == null) ? "png" : ext.toLowerCase(); + + String base = (ext == null) ? inputPathStr : inputPathStr.substring(0, inputPathStr.length() - ext.length() - 1); + Path directory = inputPath.getParent(); + Path outPath = (directory == null) + ? Paths.get(base + "_filtered." + format) + : directory.resolve(base + "_filtered." + format); + + return new PathAndFormat(outPath, format); + } else { + String ext = extensionOfFileName(outputPathStr); + String format = (ext == null) ? "png" : ext.toLowerCase(); + return new PathAndFormat(Paths.get(outputPathStr), format); + } + } + + public BufferedImage getImage() throws IOException { + if (!Files.exists(inputPath)) { + throw new IOException("IOService: getImage: Input file does not exist: " + inputPath + "."); + } + if (!Files.isReadable(inputPath)) { + throw new IOException("IOService: getImage: Input file is not readable: " + inputPath + "."); + } + BufferedImage image = javax.imageio.ImageIO.read(inputPath.toFile()); + if (image == null) { + throw new IOException("IOService: getImage: Could not read image (unsupported or corrupted): " + inputPath); + } + return image; + } + + public void writeImage(BufferedImage image) throws IOException { + if (!javax.imageio.ImageIO.write(image, outputFormat, outputPath.toFile())) { + throw new IOException("IOService: writeImage: Failed to write image in format " + + outputFormat + " to path " + outputPath); + } + } + + private static String extensionOfFileName(String name) { + if (name == null) return null; + int dot = name.lastIndexOf('.'); + if (dot < 0 || dot == name.length() - 1) return null; + return name.substring(dot + 1); + } + + public Path getOutputPath() { + return outputPath.getFileName(); + } + + public File getOutputDir() { + return this.outputDir; + } + + public List getInputFiles() { + return this.inputFiles; + } +} diff --git a/app/src/main/java/com/vicitori/pipeline/ImagePipeline.java b/app/src/main/java/com/vicitori/pipeline/ImagePipeline.java new file mode 100644 index 0000000..78ed5a1 --- /dev/null +++ b/app/src/main/java/com/vicitori/pipeline/ImagePipeline.java @@ -0,0 +1,108 @@ +package com.vicitori.pipeline; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.List; +import java.util.concurrent.*; +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; + +public class ImagePipeline { + private final List inputFiles; + private final File outputDir; + private final int workersCount; + private final Convolution convolution; + private final Filter filter; + + private final BlockingQueue readQueue = new ArrayBlockingQueue<>(10); + private final BlockingQueue writeQueue = new ArrayBlockingQueue<>(10); + + private static final File POISON_FILE = new File("POISON"); + + private record Result(BufferedImage image, String name) {} + + public ImagePipeline(List inputFiles, File outputDir, int workersCount, Convolution convolution, Filter filter) { + // defensive copy to prevent external modification + this.inputFiles = List.copyOf(inputFiles); + this.outputDir = outputDir; + this.workersCount = workersCount; + this.convolution = convolution; + this.filter = filter; + } + + public void start() throws InterruptedException { + Thread reader = createReader(); + Thread writer = createWriter(); + + reader.start(); + writer.start(); + + try (ExecutorService workers = createWorkers()) { + reader.join(); + workers.shutdown(); + boolean finished = workers.awaitTermination(1, TimeUnit.HOURS); + if (!finished) { + System.err.println("Warning: ImagePipeline: start: workers did not finish within timeout"); + workers.shutdownNow(); + } + } + writeQueue.put(new Result(null, null)); + writer.join(); + } + + private Thread createReader() { + return new Thread(() -> { + try { + for (File file : inputFiles) { + readQueue.put(file); + } + readQueue.put(POISON_FILE); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }, "Reader"); + } + + private ExecutorService createWorkers() { + ExecutorService pool = Executors.newFixedThreadPool(workersCount); + for (int i = 0; i < workersCount; i++) { + pool.submit(() -> { + try { + while (!Thread.currentThread().isInterrupted()) { + File file = readQueue.take(); + if (file == POISON_FILE) { + readQueue.put(file); + break; + } + BufferedImage img = ImageIO.read(file); + BufferedImage result = convolution.apply(img, filter); + writeQueue.put(new Result(result, file.getName())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + System.err.println("Error: ImagePipeline: createWorkers: " + e.getMessage()); + } + }); + } + return pool; + } + + private Thread createWriter() { + return new Thread(() -> { + try { + while (!Thread.currentThread().isInterrupted()) { + Result res = writeQueue.take(); + if (res.image == null) break; + File outputFile = new File(outputDir, "filtered_" + res.name); + ImageIO.write(res.image, "png", outputFile); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + System.err.println("Error: ImagePipeline: createWriter: " + e.getMessage()); + } + }, "Writer"); + } +} diff --git a/app/src/main/resources/Tula_society.jpeg b/app/src/main/resources/Tula_society.jpeg new file mode 100644 index 0000000..f64907f Binary files /dev/null and b/app/src/main/resources/Tula_society.jpeg differ diff --git a/app/src/main/resources/dream_tatoo.jpeg b/app/src/main/resources/dream_tatoo.jpeg new file mode 100644 index 0000000..33f2751 Binary files /dev/null and b/app/src/main/resources/dream_tatoo.jpeg differ diff --git a/app/src/main/resources/i_ate_a_lot_of_kittens.jpeg b/app/src/main/resources/i_ate_a_lot_of_kittens.jpeg new file mode 100644 index 0000000..01de2ae Binary files /dev/null and b/app/src/main/resources/i_ate_a_lot_of_kittens.jpeg differ diff --git a/app/src/main/resources/pain.jpeg b/app/src/main/resources/pain.jpeg new file mode 100644 index 0000000..a9da276 Binary files /dev/null and b/app/src/main/resources/pain.jpeg differ diff --git a/app/src/main/resources/prohibited_photo.png b/app/src/main/resources/prohibited_photo.png new file mode 100644 index 0000000..e00f51e Binary files /dev/null and b/app/src/main/resources/prohibited_photo.png differ diff --git a/app/src/main/resources/strong_kittens_club.jpeg b/app/src/main/resources/strong_kittens_club.jpeg new file mode 100644 index 0000000..ebc48a4 Binary files /dev/null and b/app/src/main/resources/strong_kittens_club.jpeg differ diff --git a/app/src/main/resources/study_akkadskiy_with_me.jpeg b/app/src/main/resources/study_akkadskiy_with_me.jpeg new file mode 100644 index 0000000..4acaf6c Binary files /dev/null and b/app/src/main/resources/study_akkadskiy_with_me.jpeg differ diff --git a/app/src/test/java/com/vicitori/ConvolutionTest.java b/app/src/test/java/com/vicitori/ConvolutionTest.java new file mode 100644 index 0000000..b071b99 --- /dev/null +++ b/app/src/test/java/com/vicitori/ConvolutionTest.java @@ -0,0 +1,170 @@ +package com.vicitori; + +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; +import com.vicitori.core.conv.*; +import com.vicitori.core.filters.FiltersLibrary; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.BeforeEach; + +import java.awt.image.BufferedImage; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.*; + +public class ConvolutionTest { + private static final Random RAND = new Random(42); + private Convolution sequentialConv; + private Filter blurFilter; + private Filter embossFilter; + private Filter edgeFilter; + + @BeforeEach + void setUp() { + sequentialConv = new SequentialConvolution(); + blurFilter = FiltersLibrary.get("blur"); + embossFilter = FiltersLibrary.get("emboss"); + edgeFilter = FiltersLibrary.get("find_edges"); + } + + @Test + @DisplayName("Identity filter should return unchanged image") + void testIdentityFilter() { + Filter identity = createIdentityFilter(3); + BufferedImage testImage = createTestImage(50, 50); + + BufferedImage result = sequentialConv.apply(testImage, identity); + + assertTrue(imagesEqual(testImage, result), "Identity filter should return unchanged image"); + } + + @Test + @DisplayName("Zero filter should return black image") + void testZeroFilter() { + Filter zero = createZeroFilter(3); + BufferedImage testImage = createTestImage(50, 50); + + BufferedImage result = sequentialConv.apply(testImage, zero); + + assertTrue(isBlackImage(result), "Zero filter should return black image"); + } + + @Test + @DisplayName("Filter composition should work correctly") + void testFilterComposition() { + Filter leftShift = createShiftFilter(-1, 0); + Filter rightShift = createShiftFilter(1, 0); + BufferedImage testImage = createTestImage(30, 30); + + BufferedImage step1 = sequentialConv.apply(testImage, leftShift); + BufferedImage step2 = sequentialConv.apply(step1, rightShift); + + assertTrue(imagesEqual(testImage, step2), "Composition of left and right shift should return original image"); + } + + @Test + @DisplayName("All convolution types should preserve image dimensions") + void testImageDimensionsPreserved() { + Convolution[] convolutions = { + new SequentialConvolution(), + new RowConvolution(), + new ColumnConvolution(), + new PixelConvolution(), + new GridConvolution() + }; + + BufferedImage testImage = createTestImage(40, 40); + + for (Convolution conv : convolutions) { + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), + conv.getClass().getSimpleName() + " should preserve width"); + assertEquals(testImage.getHeight(), result.getHeight(), + conv.getClass().getSimpleName() + " should preserve height"); + } + } + + @Test + @DisplayName("All convolution types should produce equivalent results") + void testConvolutionEquivalence() { + Convolution[] convolutions = { + new SequentialConvolution(), + new RowConvolution(), + new ColumnConvolution(), + new PixelConvolution(), + new GridConvolution() + }; + + Filter[] filters = {blurFilter, embossFilter, edgeFilter}; + BufferedImage testImage = createTestImage(20, 20); + + for (Filter filter : filters) { + BufferedImage reference = sequentialConv.apply(testImage, filter); + + for (int i = 1; i < convolutions.length; i++) { + BufferedImage result = convolutions[i].apply(testImage, filter); + assertTrue(imagesEqual(reference, result), + convolutions[i].getClass().getSimpleName() + " should produce same result as SequentialConvolution"); + } + } + } + + // Вспомогательные методы + private static Filter createIdentityFilter(int size) { + float[][] kernel = new float[size][size]; + kernel[size/2][size/2] = 1.0f; + return new Filter(kernel, 1.0f, 0.0f); + } + + private static Filter createZeroFilter(int size) { + float[][] kernel = new float[size][size]; + return new Filter(kernel, 1.0f, 0.0f); + } + + private static Filter createShiftFilter(int dx, int dy) { + float[][] kernel = new float[3][3]; + kernel[1+dy][1+dx] = 1.0f; + return new Filter(kernel, 1.0f, 0.0f); + } + + private static BufferedImage createTestImage(int width, int height) { + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int r = RAND.nextInt(256); + int g = RAND.nextInt(256); + int b = RAND.nextInt(256); + img.setRGB(x, y, (r << 16) | (g << 8) | b); + } + } + return img; + } + + private static boolean imagesEqual(BufferedImage img1, BufferedImage img2) { + if (img1.getWidth() != img2.getWidth() || img1.getHeight() != img2.getHeight()) { + return false; + } + + for (int y = 0; y < img1.getHeight(); y++) { + for (int x = 0; x < img1.getWidth(); x++) { + if (img1.getRGB(x, y) != img2.getRGB(x, y)) { + return false; + } + } + } + return true; + } + + private static boolean isBlackImage(BufferedImage img) { + for (int y = 0; y < img.getHeight(); y++) { + for (int x = 0; x < img.getWidth(); x++) { + if (img.getRGB(x, y) != 0) { + return false; + } + } + } + return true; + } +} diff --git a/app/src/test/java/com/vicitori/ConvolutionTypeTest.java b/app/src/test/java/com/vicitori/ConvolutionTypeTest.java new file mode 100644 index 0000000..57776b4 --- /dev/null +++ b/app/src/test/java/com/vicitori/ConvolutionTypeTest.java @@ -0,0 +1,126 @@ +package com.vicitori; + +import com.vicitori.core.Convolution; +import com.vicitori.core.Filter; +import com.vicitori.core.conv.*; +import com.vicitori.core.filters.FiltersLibrary; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.BeforeEach; + +import java.awt.image.BufferedImage; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.*; + +public class ConvolutionTypeTest { + private static final Random RAND = new Random(42); + private Filter blurFilter; + private Filter embossFilter; + private BufferedImage testImage; + + @BeforeEach + void setUp() { + blurFilter = FiltersLibrary.get("blur"); + embossFilter = FiltersLibrary.get("emboss"); + testImage = createTestImage(30, 30); + } + + @Test + @DisplayName("SequentialConvolution should process images correctly") + void testSequentialConvolution() { + Convolution conv = new SequentialConvolution(); + + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + assertNotNull(result, "Result should not be null"); + } + + @Test + @DisplayName("RowConvolution should process images correctly") + void testRowConvolution() { + Convolution conv = new RowConvolution(); + + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + assertNotNull(result, "Result should not be null"); + } + + @Test + @DisplayName("ColumnConvolution should process images correctly") + void testColumnConvolution() { + Convolution conv = new ColumnConvolution(); + + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + assertNotNull(result, "Result should not be null"); + } + + @Test + @DisplayName("PixelConvolution should process images correctly") + void testPixelConvolution() { + Convolution conv = new PixelConvolution(); + + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + assertNotNull(result, "Result should not be null"); + } + + @Test + @DisplayName("GridConvolution should process images correctly") + void testGridConvolution() { + Convolution conv = new GridConvolution(); + + BufferedImage result = conv.apply(testImage, blurFilter); + + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + assertNotNull(result, "Result should not be null"); + } + + @Test + @DisplayName("All convolution types should handle different filters") + void testConvolutionWithDifferentFilters() { + Convolution[] convolutions = { + new SequentialConvolution(), + new RowConvolution(), + new ColumnConvolution(), + new PixelConvolution(), + new GridConvolution() + }; + + Filter[] filters = {blurFilter, embossFilter}; + + for (Convolution conv : convolutions) { + for (Filter filter : filters) { + BufferedImage result = conv.apply(testImage, filter); + + assertNotNull(result, conv.getClass().getSimpleName() + " should handle " + + filter.getClass().getSimpleName() + " filter"); + assertEquals(testImage.getWidth(), result.getWidth(), "Width should be preserved"); + assertEquals(testImage.getHeight(), result.getHeight(), "Height should be preserved"); + } + } + } + + private BufferedImage createTestImage(int width, int height) { + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int r = RAND.nextInt(256); + int g = RAND.nextInt(256); + int b = RAND.nextInt(256); + img.setRGB(x, y, (r << 16) | (g << 8) | b); + } + } + return img; + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..377538c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties + +org.gradle.configuration-cache=true + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..f5172b8 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,10 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +guava = "33.4.5-jre" +junit-jupiter = "5.12.1" + +[libraries] +guava = { module = "com.google.guava:guava", version.ref = "guava" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..2c1df89 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.14.1/userguide/multi_project_builds.html in the Gradle documentation. + */ + +plugins { + // Apply the foojay-resolver plugin to allow automatic download of JDKs + id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0" +} + +rootProject.name = "image-filtering" +include("app")